To create an object in a PDF with Canvas using Java can be done by using a library called iText. iText is a Java library originally created by Bruno Lowagie which allows creating PDF, read PDF, and manipulate them.
Libraries required :
iText slf4j (Logging Library)
Example : Drawing a circle in a PDF
Approach:
- Get the current working directory of the running java program to create the PDF file in the same location
- Create a PdfWriter object (from itextpdf library) which writes the PDF file to the given path
- Create an empty PdfDocument object and add a page to it using PdfPage object
- Create the canvas using the PdfCanvas object in the Pdf Page
- Create the object on the Canvas and fill the object with color
Below is the implementation of the above approach:
Java
// Drawing an object in a PDF with Canvas using Java import com.itextpdf.kernel.colors.*; import com.itextpdf.kernel.pdf.PdfDocument; import com.itextpdf.kernel.pdf.PdfPage; import com.itextpdf.kernel.pdf.PdfWriter; import com.itextpdf.kernel.pdf.canvas.PdfCanvas; import com.itextpdf.layout.Document; // importing generic packages import java.io.*; import java.util.*; public class DrawPDF { public static void main(String args[]) throws Exception { // getting path of current working directory // to create the pdf file in the same directory of // the running java program String path = System.getProperty( "user.dir" ); path += "/DrawPDF.pdf" ; // Creating a PdfWriter object using the path PdfWriter writer = new PdfWriter(path); // Creating a PdfDocument object PdfDocument pdfDoc = new PdfDocument(writer); // Creating a Document object Document doc = new Document(pdfDoc); // Creating a new page and adding to the pdfDoc // object PdfPage pdfPage = pdfDoc.addNewPage(); // Creating a PdfCanvas object to draw the circle // object PdfCanvas canvas = new PdfCanvas(pdfPage); // Setting Green color to the circle, boolean fill // set to true. ColorsConstants from itext library // hosts an array of different colors canvas.setColor(ColorConstants.GREEN, true ); // creating a circle with parameters : X-coordinate, // Y-coordinate , Circle Diameter canvas.circle( 300 , 400 , 200 ); // Filling the circle canvas.fill(); // Closing the document doc.close(); System.out.println( "Object drawn & PDf created successfully!" ); } } |
Output:
The PDF file is created in the specified path.