Weew
Weew

Reputation: 75

Converting iTextSharp to iText7: How do I re-create iTextSharp's nested PdfDocument objects in iText7?

I am converting a heavy implementation of iText5 to iText7 in vb.net. What hair I have not lost is now gray, thanks to the complete API rewrite.

So in many cases, the OLD iTextSharp code will do something like this:

... and so on.

Now in iText7 I can create a PdfCanvas object that can be drawn on using many of the same drawing functions as iTextSharp, etc. But a PdfCanvas cannot be added to another PdfCanvas in the same manner as with iTextSharp.

I looked at the tutorials but the solution didn't seem apparent. I know it can be done but I'm not sure how to accomplish the same.

I've tried to use Xobjects but that is somewhat limiting; can I convert a PdfCanvas to a PdfFormXObject?

Upvotes: 2

Views: 3252

Answers (1)

Alexey Subach
Alexey Subach

Reputation: 12312

You cannot convert PdfCanvas into PdfFormXObject, but you can use PdfCanvas to draw on PdfFormXObject directly. In fact, PdfFormXObject class in iText 7 is the direct alternative of PdfTemplate class in iText 5, it just has different name which is closer to the PDF specification terminology.

Here is an example of how you can create a PdfFormXObject, draw something on it via PdfCanvas, and then add this object to a page, again with PdfCanvas:

//Create form XObject and flush to document.
PdfFormXObject form = new PdfFormXObject(new Rectangle(0, 0, 50, 50));
PdfCanvas canvas = new PdfCanvas(form, document);
canvas.rectangle(10, 10, 30, 30);
canvas.fill();
canvas.release();

//Create page1 and add forms to the page.
PdfPage page1 = document.addNewPage();
canvas = new PdfCanvas(page1);
canvas.addXObject(form, 0, 0).addXObject(form, 50, 0).addXObject(form, 0, 50).addXObject(form, 50, 50);
canvas.release();

As you can see, PdfCanvas is an abstraction that can be used to draw on pages or PdfFormXObject, so you would be able to add objects one into another one with PdfCanvas easily.

Upvotes: 1

Related Questions