Apache PDFBox is an open source java library used for manipulation of PDF’s. In this post we will see the steps on how to draw rectangle using Apache PDFBox.
We will be using below methods of org.apache.pdfbox.pdmodel.PDPageContentStream class
a) setNonStrokingColor(Color color)
Set the non-stroking color using an AWT color. Conversion uses the default sRGB color space.
b) addRect(float x, float y, float width, float height)
Adds a rectangle to the current path.
Parameters:
x – The lower left x coordinate.
y – The lower left y coordinate.
width – The width of the rectangle.
height – The height of the rectangle.
c) fill()
Fills the path using the nonzero winding number rule.
Example
Lets see full example on the rectangle along with its output.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 |
package com.kscodes.examples.pdfbox; import java.awt.Color; import java.io.IOException; import org.apache.pdfbox.pdmodel.PDDocument; import org.apache.pdfbox.pdmodel.PDPage; import org.apache.pdfbox.pdmodel.PDPageContentStream; public class PdfRectangleExample { public static void main(String args[]) { // Create a Document object. PDDocument pdDocument = new PDDocument(); // Create a Page object PDPage pdPage = new PDPage(); // Add the page to the document and save the document to a desired file. pdDocument.addPage(pdPage); try { // Create a Content Stream PDPageContentStream pdPageContentStream = new PDPageContentStream(pdDocument, pdPage); // Set a Color for the Rectangle pdPageContentStream.setNonStrokingColor(Color.YELLOW); // Give the X, Y coordinates and height and width pdPageContentStream.addRect(20, 600, 200, 50); pdPageContentStream.fill(); // Once all the content is written, close the stream pdPageContentStream.close(); pdDocument.save("K:\\Kscodes\\pdf\\rectangleSample.pdf"); pdDocument.close(); System.out.println("PDF saved to the location !!!"); } catch (IOException ioe) { System.out.println("Error while saving pdf" + ioe.getMessage()); } } } |
Output