I'm trying to insert an image in an existing PDF file but iText puts it on the first page and I'm losing the rest of the page content. How can I insert it without losing existing content?
I used this code:
public static void main(String[] args) {
Document document = new Document(PageSize.A4);
try {
PdfWriter.getInstance(document, new FileOutputStream(
"/home/amira/work/APPS-579/word/generatedMergedDocs/FinalTest/1.pdf"));
document.open();
Image image = Image.getInstance(
"/home/amira/work/APPS-579/word/generatedMergedDocs/FinalTest/a.jpg");
document.add(image);
} catch (DocumentException de) {
de.printStackTrace();
} catch (IOException ioe) {
ioe.printStackTrace();
}
document.close();
}
You're adding the image to an empty document, because you're not reading the original document, just overwriting it.
To modify an existing document with itext with an image, please see the following tutorial which explains it perfectly.
Related
I can easily get the content from the PDF file, but I got some file which text is not selectable when I open it. My existing code doesn't able to extract those text with following code block -
public class PDFBoxExample {
public static void main(String[] args) {
try {
File file = new File("C:\\pdf\\pdf_result.pdf");
try (PDDocument document = PDDocument.load(new FileInputStream(file))) {
document.getClass();
if (!document.isEncrypted()) {
PDFTextStripperByArea stripper = new PDFTextStripperByArea();
stripper.setSortByPosition(false);
stripper.setShouldSeparateByBeads(true);
PDFTextStripper tStripper = new PDFTextStripper();
String content = tStripper.getText(document);
System.out.println(content);
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Please find the following link of my pdf file-
https://1drv.ms/b/s!AmRKaLhGJhJphvMOUBGADveatrx0hA?e=a0seG7
Can you please provide some solution for the same.
I have been trying to write PDF files on android ,when i am using internal storage it shows no error but i am unable to see the file created and if i change path to external storage i get permission denied even though i have given permission in my manifest file.
I have creating a class which i am calling from activity to write files it fetches data from database.
Here is the code.
public boolean createPdfFile(String path, Employee employee,String month,Context context){
boolean status=false;
if(path!=null && employee!=null){
Document document=new Document();
try{
if(!Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())){
Toast.makeText(this, "External SD card not mounted", Toast.LENGTH_LONG).show();
}
File sdCard=Environment.getExternalStorageDirectory();
File file=new File(sdCard,month+"_"+employee.getEmployeeName()+".pdf");
PdfWriter writer=PdfWriter.getInstance(document,new FileOutputStream(file));
writer.setEncryption(employee.getDateOfBirth().getBytes(),employee.getEmployeeName().getBytes(), PdfWriter.ALLOW_PRINTING,PdfWriter.ENCRYPTION_AES_128);
document.open();
Paragraph p=new Paragraph();
p.add("Payslip for the month of January");
p.setFont(new Font(Font.FontFamily.TIMES_ROMAN, 12, Font.BOLD, new BaseColor(1, 1, 1)));
p.setAlignment(Element.ALIGN_CENTER);
document.add(p);
PdfPTable table=new PdfPTable(2);
table.setWidthPercentage(100); //Width 100%
table.setSpacingBefore(10f); //Space before table
table.setSpacingAfter(10f); //Space after table
float[] columnWidths = {1.5f, 1.5f};
table.setWidths(columnWidths);
table.addCell("Employee Code");
table.addCell(employee.getEmployeeID());
table.addCell("Department");
table.addCell(employee.getDepartment().getDepartmentName());
table.addCell("Date of Birth");
table.addCell(employee.getDateOfBirth());
table.addCell("Date of Joining");
table.addCell(employee.getDateOfJoining());
table.addCell("Employee Name");
table.addCell(employee.getEmployeeName());
document.add(table);
document.close();
writer.close();
status=true;
}catch (FileNotFoundException e) {
status=false;
Log.e("PDF exception aaa",e.getMessage());
}catch (DocumentException e) {
status=false;
Log.e("PDF exception abc",e.getMessage());
} catch (IOException e) {
status=false;
Log.e("PDF exception",e.getMessage());
}
}
return status;
}
If you are developing for API level 23 or newer you need to explicitly ask the user for permission.
See: https://developer.android.com/training/permissions/requesting.html#perm-check
I am using JPedal free version jar to render PDF in my java swing program. The normal PDF is getting rendered properly but while rendering the PDF image(Image file converted to PDF file) the quality drops considerably(not readable at all).
Example code :
public OpenViewer() {
//create and initialise JPedal viewer component
final Viewer myViewer =new Viewer();
myViewer.setupViewer();
//code to open when required
final File file=null; //example is commented out below
final InputStream stream = null;
//open the stream or File
try {
file = new File("/Users/markee/Desktop/myfile.pdf"); // This PDF is converted from tiff
} catch (Exception e) {
e.printStackTrace();
}
if(file!=null) {
myViewer.executeCommand(Commands.OPENFILE, new Object[]{file});
}
}
I am trying to create a pdf file and save it to sd card. I searched for solutions to my problem but what i found in the net was about creating and saving a file or image. But neither solves my problem. Here's my sample code:
public void createPdf(){
Document document = new Document();
try {
PdfWriter.getInstance(document, new FileOutputStream(android.os.Environment.getExternalStoragePublicDirectory("DIRECTORY_PDF") + java.io.File.separator + "droidtext" + java.io.File.separator + "HelloWorld"));
document.open();
document.add(new Paragraph("Hello World"));
} catch (DocumentException de) {
System.err.println(de.getMessage());
} catch (IOException ioe) {
System.err.println(ioe.getMessage());
}
document.close();
and here's what the logcat says:
02-21 06:28:08.001: W/System.err(859): /mnt/sdcard/DIRECTORY_PDF/droidtext/HelloWorld: open failed: ENOENT (No such file or directory)
My requirement is that I should read a template file and change some values in its content and write it back to another file. Most importantly it should have the same styles as that of the template.
The problem I face is that I am able to read and write, but its very difficult to transfer the styles as well. Especially I am tired trying to apply the paragraph styles to the document. Pls help me..... this is my code
public static void main(String[] args) {
try {
HWPFDocument templateFile = new HWPFDocument(new FileInputStream("D:\\POI\\testPOIin.doc"));
HWPFDocument blankFile = new HWPFDocument(new FileInputStream("D:\\POI\\blank.doc"));
ParagraphProperties pp = templateFile.getRange().getParagraph(4).cloneProperties();
blankFile.getRange().insertAfter(pp, 0);
OutputStream out = new FileOutputStream("D:\\POI\\testPOIout.doc");
blankFile.write(out);
} catch (FileNotFoundException fnfe) {
// TODO: Add catch code
fnfe.printStackTrace();
} catch (Exception ioe) {
// TODO: Add catch code
ioe.printStackTrace();
}
}
}
Pls let me know that I am doing wrong.....
I also had similar task and after investigation i created solution, but it works only for docx files:
public static void main(String[] args) throws Exception {
FileOutputStream fos = new FileOutputStream(new File("transformed.docx"));
XWPFDocument doc = new XWPFDocument(new FileInputStream(new File("original.docx")));
for(XWPFParagraph p:doc.getParagraphs()){
for(XWPFRun r:p.getRuns()){
for(CTText ct:r.getCTR().getTList()){
String str = ct.getStringValue();
if(str.contains("NAME")){
str = str.replace("NAME", "Java Dev");
ct.setStringValue(str);
}
}
}
}
doc.write(fos);
}
it operates on low level elements so it saves styles and other props. Hope it will help somebody.