Create a PDF file and write text into it using PDFBox 2.0
Create a PDF file and write text into it using PDFBox 2.0 – In this PDFBox Tutorial, we shall see how to create a PDF file and write text into it using PDFBox 2.0. We shall take a step by step understanding in doing this.
Following are the programatical steps required to create and write text to a PDF file using PDFBox 2.0 :
Step 1: Create a PDF document in-memory
PDDocument doc = new PDDocument();
Step 2: Create a PDF page.
PDPage page = new PDPage();
Step 3: Add the page to the PDF document.
page.add(doc)
Step 4: Ready the contents to be written in the page. Use a stream. This stream has to be closed after usage.
PDPageContentStream contents = new PDPageContentStream(doc, page);
Step 5: Begin some text operations.
contents.beginText();
Step 6: Set the font and font size of text, to draw it on PDF page.
PDFont font = PDType1Font.HELVETICA_BOLD;
contents.setFont(font, 30);
Step 7: Start a new line at offset (x,y) as shown below (say for a characters ‘g’) :
contents.newLineAtOffset(50, 700);
Step 8: Show the text at the location specified.
contents.showText(message);
Step 9: Stop the text operations.
contents.endText();
Step 10: Close the content stream.
contents.close();
Step 11: Save the PDF document.
doc.save(filename);
Step 12: Close the in-memory pdf document.
doc.close();
The complete program is given below.
CreatePdfWithTextDemo.java
import java.io.IOException;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.font.PDFont;
import org.apache.pdfbox.pdmodel.font.PDType1Font;
/**
* Creates a sample.pdf document and write a message at an offset with HELVETICA_BOLD font style.
*/
public class CreatePdfWithTextDemo {
public static void main(String[] args) throws IOException {
String filename = "sample.pdf";
String message = "This is a sample PDF document created using PDFBox.";
PDDocument doc = new PDDocument();
try {
PDPage page = new PDPage();
doc.addPage(page);
PDFont font = PDType1Font.HELVETICA_BOLD;
PDPageContentStream contents = new PDPageContentStream(doc, page);
contents.beginText();
contents.setFont(font, 30);
contents.newLineAtOffset(50, 700);
contents.showText(message);
contents.endText();
contents.close();
doc.save(filename);
}
finally {
doc.close();
}
}
}
The pdf generated is as shown in the following picture.
The pdf file is created at the root of project.
Conclusion
In this PDFBox Tutorial, we have seen how to create a PDF file and write text into it using PDFBox 2.0.