What is the difference between the PdfCanvas and Canvas classes in the iText7 library? When should I use each one of them?
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 (Paragraph
s, Table
s, List
s, ...) 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();
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();