PDFBox Adding TextWe 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 DocumentWe 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 PageGet 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 StreamPDPageContentStream 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 TextWhen 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 TextWe 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 FontWe can set the font style and font size of the text by using setFont() method of the PDPageContentStream class. Write Text ContentWe can insert text content in the PDF document by using the showText() method of the PDPageContentStream class. End TextWhen 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 StreamWe can close the PDPageContentStream class by using close() method. Save DocumentAfter 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 DocumentAfter 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. Now, opening the PDF document, we can observe that the text content is added in the page of the PDF document.
Next TopicPDFBox Adding Multiple Lines
|