Search code examples
javaitext7

Difference between PdfCanvas and Canvas in itext 7


What is the difference between the PdfCanvas and Canvas classes in the iText7 library? When should I use each one of them?


Solution

  • In a nutshell, PdfCanvas is designed for low-level operations and Canvas - for high-level ones.

    You want to write rectangles / pathes / text and any other operators to the content stream of a pdf? Use the PdfCanvas instance.

    You want to add high-level iText objects (Paragraphs, Tables, Lists, ...) to your PdfCanvas? Use the Canvas instance.

    PdfCanvas example

            PdfDocument pdfDoc = new PdfDocument(new PdfWriter(destinationFolder + "simpleCanvas.pdf"));
    
        PdfPage page1 = pdfDoc.addNewPage();
    
        PdfCanvas canvas = new PdfCanvas(page1);
        canvas.rectangle(100, 100, 100, 100).fill();
    
        pdfDoc.close();
    

    The resultant pdf: enter image description here

    Canvas example

                PdfDocument pdf = new PdfDocument(new PdfWriter(out));
    
        PdfPage page = pdf.addNewPage();
        PdfCanvas pdfCanvas = new PdfCanvas(page);
    
        Rectangle rectangle = new Rectangle(100, 100, 100, 100);
    
        Canvas canvas = new Canvas(pdfCanvas, pdf, rectangle);
        canvas.add(new Paragraph("Hello World"));
    
        canvas.close();
    
        pdf.close();
    

    The resultant pdf: enter image description here