Javatpoint Logo
Javatpoint Logo

PDFBox Adding Multiple Lines

In the previous section, we discussed how to add text content to the pages of a PDF document. The previous program writes the only single line in a page. If we want to insert more than one line in the page than it will not allow and end inserting text after ending the line.

To add multiple lines in a PDF document we need to use the setLeading() method and after finishing each line we use newline() method to insert text from a new line.

Follow the steps below to insert multiple line 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

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

Set Text Font

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

Set Text Leading

We can set the text leading by using the setLeading() method. The setLeading() method decides how much to move down to get to the next baseline.

Insert Multiple Lines using newLine()

We can insert multiple lines by using showText() and divide each line by using newline() method as shown below.

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 need 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 need 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 can see the following message.


PDFBox Adding Multiple Lines

Now, opening the PDF document, we can observe that the multiple lines are added in the page of the PDF document.


PDFBox Adding Multiple Lines




Help Others, Please Share

facebook twitter google plus pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA