PDFBox Adding Rectangles
Using 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 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.
Retrieve Page
In 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 Stream
PDPageContentStream 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 Colour
We 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 Rectangle
The 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:
- X– The x coordinate of the rectangle
- Y– The y coordinate of the rectangle
- Width– The width of the rectangle.
- Height– The height of the rectangle.
Fill Rectangle
The 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 Document
After 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 Program
Output:
After successful execution, the above program shows the following output.
Now for verification, open the PDF Document named as Rectangleshape as shown below-