Question

I need to add some formatted text to a PDF form field using iTextSharp and I can't seem to figure it out. This is how I'm currently setting the fields, but certain portions of the inserted text will need to be bold or have other formatting.

stamper.AcroFields.SetField("fieldName", "fieldValue")
stamper.FormFlattening = True

I've seen elsewhere that I should be able to insert some xml that includes formatting information instead, but I have no idea what this xml should look like.

Here's the section from that page that leads me to believe that what I want is possible:

It still stamps the actual XML code onto the field and the Reader will not render it as rich text in the stamped PDF.

And the working response to this:

For that to work you'll have to call AcroFields.setGenerateAppearances(false). Note that older Reader versions don't generate appearances.

What should this xml look like, or is there another way to accomplish this?

Was it helpful?

Solution

A while back, I added the ability to iText to set the rich text value of a field. I didn't add any rendering code to back this up.

That means the only way to see that rich value is via a PDF viewer that supports it (Reader/Acrobat). In order for them to know they need to rebuild all field appearances, you have to call acroFields.setGenerateAppearances(false). This disables iText's appearance generation, and instead requests that the PDF viewer do it for you.

If you want flattened rich text wholly within iText[Sharp] you're going to have to do something screwy:

  1. Draw your rich text into a PDF page in a separate document. The size of this page should match the size of the field. Save it out (a memory stream is fine).
  2. Add a new PushbuttonField, set to LAYOUT_ICON_ONLY. Use the same bounding box as the original text field. Set the pushbutton's background color to null (transparent).
  3. Create a PdfImportedPage of your rich-text page and set this imported page to be the new PushbuttonField's icon (template).
  4. Flatten.

Painful, but effective.

You can do #1 with HTMLWorker and use your original rich text/HTML as input.

In fact, you could probably get quite a bit more efficient with an HTMLWorker feeding a ColumnText object to render your HTML in the same document rather than a new one, then write it out and read it back in again. Whip up a PdfTemplate from any old page's DirectContent with the appropriate bounding box.

That would suck much less.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top