Friday, November 9, 2012

C# : Read pdf intearactive form text fields, Write those fields values in CSV and XML format

Create a pdf interactive form using adobeFormsCentral>save it>add it in your project.
-- Download iTextSharp >unzip it>find core iTextSharp.dll>add it as reference in your project >finally include this library for your functions> there you are .. ready..

public string pdfInputFile = "//~Files/pdfTest2.pdf"; 
public string pn, nam, ph;

    private void ReadPDF()
    {
        PdfReader pdfRdr = new PdfReader(pdfInputFile);
        AcroFields frm = pdfRdr.AcroFields;
        var fkeys = frm.Fields.Keys;

        pn = frm.GetField("txtID");
        nam = frm.GetField("txtName");
        ph = frm.GetField("txtPhone");
    }


// Write and save an CSV file from the pdf fields values

    private void WriteCSV()
    {
        StreamWriter swFromFile = new StreamWriter(@"c:\temp\temp.csv");
        swFromFile.WriteLine("\"ID\";\"Name\";\"Phone\"");
        swFromFile.WriteLine("\"" + pn + "\";\"" + nam + "\";\"" + ph + "\"");
        swFromFile.Flush();
        swFromFile.Close();
    }


// Write and save an XML file from the pdf fields values

    private void WriteXML()
    {

        XmlWriterSettings settings = new XmlWriterSettings();
        settings.Indent = true;
        try
        {
            XmlDocument doc1 = new XmlDocument();
            doc1.LoadXml("<root><ID></ID><Name></Name><Phone></Phone></root>");

            XmlNode xID = doc1.SelectSingleNode("/root/ID");
            xID.InnerText = pn;
            XmlNode xNam = doc1.SelectSingleNode("/root/Name");
            xNam.InnerText = nam;

            XmlNode xPh = doc1.SelectSingleNode("/root/Phone");
            xPh.InnerText = ph;

            doc1.Save(@"c:\temp\temp.xml");

           }
        catch (Exception ex)
        {
            lblmsg.Text = ex.Message;
        }
        txtFileName.Text = "xml writen from pdf";

    }

No comments:

Post a Comment