I have an application that uses itextsharp to populate the fields of a PDF form.
I have a new requirement from the client to emphasize the meaning of the fields.
I read many posts, including answers to questions on this site, but I could not figure out how to do this.
My code currently does the following:
- Creates an instance of PDFStamper
- Get form fields using the stamper.AcroFields property
- Set the field value using the AcroFields.SetFieldRichValue () method.
But when I open the PDF, the field is empty.
I checked that the field is set as rich text in the PDF file itself.
Any idea what I'm doing wrong?
Here is the snnipest of my code:
FileStream stream = File.Open(targetFile, FileMode.Create);
var pdfStamper = new PdfStamper(new PdfReader(sourceFile), stream);
// Iterate the fields in the PDF
foreach (var fieldName in pdfStamper.AcroFields.Fields.Keys)
{
// Get the field value of the current field
var fieldValue = "<?xml version=\"1.0\"?><body xmlns=\"http://www.w3.org/1999/xtml\" xmlns:xfa=\"http://www.xfa.org/schema/xfa-data/1.0/\" xfa:contentType=\"text/html\" xfa:APIVersion=\"Acrobat:8.0.0\" xfa:spec=\"2.4\"><p style=\"text-align:left\"><b><i>Here is some bold italic text</i></b></p><p style= \"font-size:16pt\">This text uses default text state parameters but changes the font size to 16.</p></body>"
// Set the field value
if (String.IsNullOrEmpty(fieldValue) == false)
{
pdfStamper.AcroFields.SetFieldRichValue(key, fieldValue);
}
}
Edit:
Mark Storer (http://stackoverflow.com/questions/1454701/adding-rich-text-to-an-acrofield-in-itextsharp). :
var reader = new PdfReader(sourceFile);
var stream = File.Open(targetFile, FileMode.Create);
var pdfStamper = new PdfStamper(reader, stream);
var fieldName = "myfield";
var fieldValue = "<?xml version=\"1.0\"?><body xfa:APIVersion=\"Acroform:2.7.0.0\" xfa:spec=\"2.1\" xmlns=\"http://www.w3.org/1999/xhtml\" xmlns:xfa=\"http://www.xfa.org/schema/xfa-data/1.0/\"><p dir=\"ltr\" style=\"margin-top:0pt;margin-bottom:0pt;font-family:Helvetica;font-size:12pt\"><b>write line1 bold</b></p</body>";
var msOutput = new FileStream(@"d:\temp.pdf", FileMode.Create);
var textReader = new StringReader(fieldValue);
var document = new Document(pdfStamper.AcroFields.GetFieldPositions(fieldName)[0].position);
var writer = PdfWriter.GetInstance(document, msOutput);
document.Open();
var list = HTMLWorker.ParseToList(textReader, null);
foreach (var element in list)
{
document.Add(element);
}
document.Close();
var button = new PushbuttonField(pdfStamper.Writer, pdfStamper.AcroFields.GetFieldPositions(fieldName)[0].position, fieldName + "_")
{
Layout = PushbuttonField.LAYOUT_ICON_ONLY,
BackgroundColor = null,
Template = pdfStamper.Writer.GetImportedPage(new PdfReader(targetFile, 1)
};
pdfStamper.AddAnnotation(button.Field, 1);
pdfStamper.FormFlattening = true;
pdfStamper.Close();
pdfStamper.Dispose();
, ....
?