Reputation: 735
I am using the Apache PDFBox java library to create PDFs. However, I am facing problem in rendering multi-line text (line wrap):
//Creating PDF document object
PDDocument doc = new PDDocument();
//Adding the blank page to the document
doc.addPage( new PDPage() );
PDPage page = doc.getPage(0);
PDImageXObject pdImage = PDImageXObject.createFromFile("C:\\Users\\abc\\Desktop\\abc.png", doc);
PDPageContentStream contentStream = new PDPageContentStream(doc, page);
contentStream.drawImage(pdImage, 10, 720);
//Begin the Content stream
contentStream.beginText();
contentStream.newLineAtOffset(50, 735);
//Setting the font to the Content stream
contentStream.setFont( PDType1Font.TIMES_ROMAN, 16 );
contentStream. showText("ABC Management System");
//Setting the leading
//contentStream.setLeading(14.5f);
//Setting the position for the line
contentStream.newLineAtOffset(25, 600);
String text1 = "This is an example of adding text to a page in the pdf document we can add as many lines";
String text2 = "as we want like this using the ShowText() method of the ContentStream class";
//Adding text in the form of string
contentStream. showText(text1);
contentStream.newLine();
contentStream. showText(text2);
//Ending the content stream
contentStream.endText();
System.out.println("Content added");
//Closing the content stream
contentStream.close();
//Saving the document
doc.save("my_doc.pdf");
System.out.println("PDF created");
//Closing the document
doc.close();
The issue I am faciing is the latter half of the text (text1, text2) is not getting rendered in the PDF file. Only the image and the first line ABC Management System
is displayed in the pdf.
To generate multi-line texts, I referred: PDFBox - Adding Multiple Lines.
I do not understand what setLeading
does and hence commented it out and tried again but the text was still not getting rendered.
Upvotes: 0
Views: 1134
Reputation: 18851
newLineAtOffset()
is relative to the current text position. To restart from 0, the easiest is to end your current and start a new text block. Your current code places you at y 1335 (or slightly lower, depending of the leading).
Upvotes: 1