iTextSharp add text to form copying information from a form field

88 Views Asked by At

TL;DR - Convert 'Acrofields.Item' font and size data to Phrase / TextField equivalents to create a clone copy of a form field as a Text label.

I realise iTextSharp has been replaced with iText7 but using that is not an option unfortunately. I have the unusual situation of having to read in a PDF document containing form fields using iTextSharp, and then having to duplicate those fields on further pages (in this example for generating an invoice where I want the invoice date etc. to appear on every page, or add invoice lines at a position specified by a 'marker field' in the template).

To do this I have been using PdfStamper and ColumnText.ShowTextAligned to add a duplicate label:

PdfStamper _stamper = ...
AcroFields.Item field = _stamper.AcroFields.Fields["Name"]
PdfDictionary fieldControlDict = field.GetWidget(0);
PdfArray fieldRect = fieldControlDict.GetAsArray(PdfName.RECT);
PdfNumber alignmentObj = fieldControlDict.GetAsNumber(PdfName.Q);

Phrase phrase = new Phrase("Joe Bloggs");
ColumnText.ShowTextAligned(_stamper.GetOverContent(pageNumber), alignmentObj.IntValue, phrase, fieldRect.x, fieldRect.y, 0);

This works ok but it won't copy the font or font size information from the original field. I've also tried using TextField and PdfFormField with simlar results.

I can use the Widget property to get the rectangle and alignment, but the font is proving more tricky. It also feels like there must be a simpler way to do this, but finding much info on iTextSharp nowadays is difficult. There is a 'DA' property with what looks like a PostScript style font tag (e.g. '/HELV 11 Tf 0 g') but not sure how to get a PdfFont out of this to use with the Phrase (the biggest problem being mapping the string 'HELV' to a PdfFont equivalent without a lookup table covering every font ever invented).

UPDATE: Found iText5 API docs here (for java but its close enough) https://api.itextpdf.com/iText5/java/5.5.11/index.html

0

There are 0 best solutions below