Javatpoint Logo
Javatpoint Logo

PDFBox Adding Text

We can add Text content in the existing PDF document. This section describes how to add new text content to the existing PDF document. PDFBox library provides a PDPageContentStream class. This class contains the required methods to insert text, images, and other types of contents in a page of the PDF Document.

Follow the steps below to add text content in the existing PDF document -

Load Existing Document

We can load the existing PDF document by using the static load() method. This method accepts a file object as a parameter. We can also invoke it using the class name PDDocument of the PDFBox.

Get Required Page

Get the required page in which we want to add text content in the PDF document. getPage() method is used to retrieve the page from PDF document. getPage() method accepts an index of the page as a parameter.

Prepare Content Stream

PDPageContentStream class is used to insert data in the document. In this class, we need to pass the document object and page object as its parameter to insert data.

Begin Text

When we insert text in the PDF document, we can also provide the start position of the text. beginText() method of the PDPageContentStream class is used to start the text content.

Set Position of Text

We can set the position of the text by using newLineAtOffset() method of the PDPageContentStream class which can be shown in the following code.

Set Text Font

We can set the font style and font size of the text by using setFont() method of the PDPageContentStream class.

Write Text Content

We can insert text content in the PDF document by using the showText() method of the PDPageContentStream class.

End Text

When we insert text in the PDF document, we have to provide the end point of the text. endText() method of the PDPageContentStream class is used to end the text content.

Close Content Stream

We can close the PDPageContentStream class by using close() method.

Save Document

After adding the required document, we have to save it to our desired location. save() method is used to save the document. The save() method accepts a string value and passes a path of the document as a parameter.

Close Document

After completing the task, we need to close the PDDocument class object by using the close() method.

Example-

Output:

After successful execution of the above program, we will see the following message.


PDFBox Adding Text

Now, opening the PDF document, we can observe that the text content is added in the page of the PDF document.


PDFBox Adding Text




Help Others, Please Share

facebook twitter google plus pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA