Java Examples - Draw Objects in a PDF


Advertisements

Problem Description

How to draw an object in a PDF using canvas.

Solution

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 
      canvas.circle(300, 400, 200);              
      
      //Filling the circle 
      canvas.fill(); 
      
      //Closing the document 
      doc.close();  
      System.out.println("Object drawn on pdf successfully"); 
   }
}

Output

Canvas Circle
java_itext
Advertisements