PDFBox Adding Rectangles - PDFBox

What is PDFBox - Adding Rectangles?

In the previous section, we went through on how to extract an image in the document. In this section, we will learn how to create color boxes in a page of the PDF document.

Creating Boxes in a PDF Document

We make use of addRect() method of PDPageContentStream class provided by PDFBox library. This method adds rectangular boxes in a PDF page.

Below steps should be followed to create rectangular shapes in a page of PDF document.

Step 1: Loading an Existing PDF Document

To load an existing document, use the load() method of the PDDocument class. Instantiate this class to load the PDF document as depicted below. It accepts a file object as parameter.

Step 2: Getting the Page Object

Firstly, we need to retrieve the PDPage object of the required page. It can be done using getPage() method of the PDDocument class. We need to pass the index of the page to the getPage() method to add rectangles.

Step 3: Preparing the Content Stream

PDPageContentStream class is used to insert various kinds of data elements. To the constructor of this class, we need to pass the document object and the page object. So instantiate this class by sending or passing these two objects as depicted below-

Step 4: Setting the Non-stroking Color

Below code sets the non-stroking color to the rectangle. It is done by using setNonStrokingColor() method of the PDPageContentStream class. This method accepts the required color as a parameter as depicted below.

Step 5: Drawing the rectangle

Once the color is selected, we need to draw the rectangle with the dimensions required. This is done by using addRect() method. It accepts four parameters which are dimensions of the rectangle.

Step 6: Filling the Rectangle

Once the rectangle is drawn, we need to fill the path between the dimensions specified with required color using fill() method of PDPageContentStream class.

Step 7: Closing the Document

Lastly, to close the document use close() method of the PDDocument class as depicted below.

Example

Let us consider a PDF document by name blankpage.pdf in the path C:/PdfBox_Examples/ which contains a single blank page as depicted below.

PDFBox - Adding Rectangles

Example below explains on how to create/insert rectangles in mentioned PDF documen. We will create a box in Blank PDF and save. Save the above code in a file by name AddRectangles.java.

Once the file is saved, compile and execute it from command prompt using the below commands-

Above program will create a rectangle in the given PDF document. Below message is rendered upon execution-

Verify the path given while saving the document and open the saved document. We will find a box is inserted in it as depicted below.

PDFBox - Adding Rectangles

All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd DMCA.com Protection Status

PDFBox Topics