Goncalo

Goncalo

  • NA
  • 3
  • 4.6k

Merge Fields in PDF using XML and itextsharp

Dec 25 2013 3:41 PM
Hi all,
 
I'm posting here to ask for a huge help from you..
I need to accomplish a task and I'm having some problems..
I need to implement a method to merge fields in a PDF with forms created in Adobe Life Cycle.
I'll receive the template PDF and a XML to populate the PDF and need to return the new filled file. 
The xml is something like this:
 
 <?xml version="1.0" encoding="UTF-8"?>
<form1>
    <ReportDescription>
          <body xmlns="http://www.w3.org/1999/xhtml" xmlns:xfa="http://www.xfa.org/schema/xfa-data/1.0/">
              <p><span style="font:Arial bold 12px">Name of the document</span></p>
          </body>
    </ReportDescription>
    <ReportCode>GEP-DO-PA-XX-000</ReportCode>
   <Contents>
      <UserData>
              <UserName>Ego ille</UserName>
              <UserPhone>Si manu vacuas</UserPhone>
              <UserNIF>999999999</UserNIF>
      </UserData>
   </Contents>
</form1>
 
So, I have something like the following:
 
  private MemoryStream GeneratePDF(string m_FormName, XmlDocument oData)
        {
            PdfReader pdfTemplate;
            PdfStamper stamper;
            PdfReader tempPDF;
            Document doc;
            MemoryStream msTemp;
            PdfWriter pCopy;
            MemoryStream msOutput = new MemoryStream();
            
            pdfTemplate = new PdfReader(m_FormName);
            
            doc = new Document();
            pCopy = new PdfCopy(doc, msOutput);
            
            pCopy.AddViewerPreference(PdfName.PICKTRAYBYPDFSIZE, new PdfBoolean(true));
            pCopy.AddViewerPreference(PdfName.PRINTSCALING, PdfName.NONE);
            
            doc.Open();
            
            for (int i = 1; i < pdfTemplate.NumberOfPages + 1; i++)
            {
                msTemp = new MemoryStream();
                pdfTemplate = new PdfReader(m_FormName);
                
                stamper = new PdfStamper(pdfTemplate, msTemp);
                
                // map xml values to pdf form controls (element name = control name)
                foreach (XmlElement oElem in oData.SelectNodes("/form1/*"))
                {
                    stamper.AcroFields.SetField(oElem.Name, oElem.InnerText);
                }
                
                stamper.FormFlattening = true;
                stamper.Close();
                tempPDF = new PdfReader(msTemp.ToArray());
                ((PdfCopy)pCopy).AddPage(pCopy.GetImportedPage(tempPDF, i));
                pCopy.FreeReader(tempPDF);
               
            }
            doc.Close();

            return msOutput;
        }
 
 
Hope someone can help me.
 
Kind Regards,
GV

Answers (4)