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.
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.
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.
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.
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-
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.
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.
Once the rectangle is drawn, we need to fill the path between the dimensions specified with required color using fill() method of PDPageContentStream class.
Lastly, to close the document use close() method of the PDDocument class as depicted below.
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.
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 Related Interview Questions
|Adv Java Interview Questions||Core Java Interview Questions|
|Java applet Interview Questions||Java Developer Interview Questions|
|Java collections framework Interview Questions||Apache Hive Interview Questions|
|Apache Pig Interview Questions||Java Management Extensions (JMX) Interview Questions|
|Angular 5 Interview Questions||Apache Wicket Interview Questions|
|Java 9 Interview Questions|
All rights reserved © 2020 Wisdom IT Services India Pvt. Ltd
Wisdomjobs.com is one of the best job search sites in India.