In our last post we had seen How to Create Simple PDF using Apache PDFBox.
Now in this post we will see steps to add text to PDF using Apache PDFBox.
The PDPageContentStream is the class from the PDFBox library that is used to write text.
Below are few of the methods from this class that will be used
1. beginText() – Begins the text operation
2. newLineAtOffset(x,y) – Moves to the new lines and determines the X and Y positions for the text.
3. setFont(name,size) – Sets the desired font and its size.
4. showText(text) – Shows the text at the given position
5. endText() – Ends the text operation
Lets see an examples for this. We have used 2 different fonts for testing text in various fonts in the PDF.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 |
package com.kscodes.examples.pdfbox; 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.PDType1Font; public class SimplePdf { public static void main(String args[]) { // Create a Document object. PDDocument pdDocument = new PDDocument(); // Create a Page object PDPage pdPage = new PDPage(); // Add the page to the document and save the document to a desired file. pdDocument.addPage(pdPage); try { // Create a Content Stream PDPageContentStream pdPageContentStream = new PDPageContentStream(pdDocument, pdPage); // Start the stream pdPageContentStream.beginText(); // Set the X and Y corodinates for the text to be positioned pdPageContentStream.newLineAtOffset(25, 700); // Set a Font and its Size pdPageContentStream.setFont(PDType1Font.HELVETICA, 12); pdPageContentStream.showText("This is a simple text example - kscodes"); // End the Stream pdPageContentStream.endText(); // Lets try a different font and size pdPageContentStream.beginText(); pdPageContentStream.newLineAtOffset(25, 600); pdPageContentStream.setFont(PDType1Font.COURIER, 24); pdPageContentStream.showText("This is a simple text example - kscodes"); pdPageContentStream.endText(); // Once all the content is written, close the stream pdPageContentStream.close(); pdDocument.save("K:\\Kscodes\\pdf\\sample.pdf"); pdDocument.close(); System.out.println("PDF saved to the location !!!"); } catch (IOException ioe) { System.out.println("Error while saving pdf" + ioe.getMessage()); } } } |
Output