Java Examples - Draw Objects in a PDF

Problem Description

How to draw an object in a PDF using canvas.


Following is the program to draw an objects in a PDF Using Canvas.

import com.itextpdf.kernel.color.Color; 
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;  

public class DrawingCircle { 
   public static void main(String args[]) throws Exception { 

      //Creating a PdfWriter 
      String dest = "C:/itextExamples/drawingCircle.pdf";       
      PdfWriter writer = new PdfWriter(dest); 

      //Creating a PdfDocument object 
      PdfDocument pdfDoc = new PdfDocument(writer);     

      //Creating a Document object 
      Document doc = new Document(pdfDoc);   

      //Creating a new page 
      PdfPage pdfPage = pdfDoc.addNewPage();          
      //Creating a PdfCanvas object 
      PdfCanvas canvas = new PdfCanvas(pdfPage);  
      //Setting color to the circle 
      Color color = Color.GREEN;
      canvas.setColor(color, true); 

      //creating a circle, 400, 200);              
      //Filling the circle 
      //Closing the document 
      System.out.println("Object drawn on pdf successfully"); 


Canvas Circle