PDFBox Adding RectanglesUsing PDFBox library, we can add rectangular shapes in the PDF page. The PDFbox library provides a addRect() method of the PDPageContentStream class to add rectangle in the PDF page. To add rectangular shapes in the PDF document do the following- Load Existing PDF 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. Retrieve PageIn this, we have to select a page in which the rectangular shape will be inserted. The getPage() method is used to retrieve a page from PDF document. This method needs a page number as a parameter for that page which we want to retrieve. This can be shown in the following code. Prepare Content StreamPDPageContentStream class is used to create an object for inserting the various data elements. The constructor of this class contains the document object and the page object as a parameter. This can be shown in the following code. Set ColourWe can set the color to the rectangular shape by using the setNonStrokingColor() method of the PDPageContentStream class. This method need to pass the required color as a parameter. This can be shown in the following code. Add RectangleThe addRect() method is used to draw the rectangular shape with required dimensions. This method need to pass the dimensions of the rectangle as a parameter. This can be shown in the following code. The addRect() method accepts the following Parameters:
Fill RectangleThe fill() method of the PDPageContentStream class fills the path between the specified dimensions with the required color. This can be shown in the following code. Close DocumentAfter completing the task, we need to close the PDDocument class object by using the close() method. Example-This is a blank PDF document. In this document, we are going to add rectangular shape by using PDFBox library of Java program. Java ProgramOutput: After successful execution, the above program shows the following output. Now for verification, open the PDF Document named as Rectangleshape as shown below-
Next TopicPDFBox Splitting PDF Document
|