Skip to content
Related Articles
Get the best out of our app
GeeksforGeeks App
Open App

Related Articles

Drawing an Object in a PDF with Canvas using Java

Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article

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 :

slf4j (Logging Library)

Example : Drawing a circle in a PDF


  1. Get the current working directory of the running java program to create the PDF file in the same location
  2. Create a PdfWriter object (from itextpdf library) which writes the PDF file to the given path
  3. Create an empty PdfDocument object and add a page to it using PdfPage object
  4. Create the canvas using the PdfCanvas object in the Pdf Page
  5. Create the object on the Canvas and fill the object with color

Below is the implementation of the above approach:


// 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.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, 400, 200);
        // Filling the circle
        // Closing the document
            "Object drawn & PDf created successfully!");


The PDF file is created in the specified path.

My Personal Notes arrow_drop_up
Last Updated : 11 Dec, 2020
Like Article
Save Article
Similar Reads
Related Tutorials