I am working on migration from iText 5 to iText 7. I have iText 5 code as below. I am not sure which alternative from iText 7(may be Canvas) should be used to implement PdfContentByte and PdfTemplate.
produce(com.itextpdf.text.pdf.PdfWriter writer, width, height, ...) {
com.itextpdf.text.pdf.PdfContentByte cb = writer.getDirectContent();
com.itextpdf.text.pdf.PdfTemplate template = cb.createTemplate(width, height);
try
{
template.beginText();
template.setFontAndSize(font, fontSize);
template.setTextMatrix(0, 0);
template.showTextAligned(com.itextpdf.text.pdf.PdfContentByte.ALIGN_CENTER, value, width/2, linePos, 0);
template.endText();
}
catch(Exception e)
{
}
cb.addTemplate(template, left, areaTop - top - height);
}
Can anyone please suggest the correct alternative to achieve this?
Thanks!
The PdfContentByte instance returned by iText 5 PdfWriter.getDirectContent() essentially is the content of the current page plus a number of methods to add more content.
An iText 5 PdfTemplate essentially is a PDF form XObject and its content plus a number of methods to add more content.
In iText 7 there are dedicated classes PdfPage and PdfFormXObject for pages and PDF form XObjects respectively, and there are classes PdfCanvas and Canvas providing low level and high level methods respectively to add more content to pages or form XObjects.
Thus, the following corresponds approximately to your iText 5 code:
PdfDocument pdfDoc = ...
PdfPage page = ... // e.g. pdfDoc.addNewPage();
PdfFormXObject pdfFormXObject = new PdfFormXObject(new Rectangle(width, height));
try (Canvas canvas = new Canvas(pdfFormXObject, pdfDoc)) {
canvas.showTextAligned(value, width/2, linePos, TextAlignment.CENTER);
}
PdfCanvas pdfCanvas = new PdfCanvas(page);
pdfCanvas.addXObject(pdfFormXObject, left, bottom);
(From AddCanvasToDocument test testAddCanvasForManjushaDC)
I say "approximately" because the architecture of iText 5 and iText 7 differ, so there is not necessarily an exact correspondence, in particular best practices in iText 5 don't directly translate to best practices in iText 7.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With