Extract PDF form field names from a PDF form

Viewed 37703

I'm using pdftk to fill in a PDF form with an XFDF file. However, for this project I do not know in advance what fields will be present, so I need to analyse the PDF itself to see what fields need to be filled in, present an interface to the user accordingly, and then generate an XFDF file from that to fill in the PDF form.

How do I get the field names? Preferably command-line, .NET or PHP solutions.

7 Answers

Considering pdftk is abandonware, you can use qpdf library to dump the metadata in JSON format, and use jq to filter only the form relevant data:

qpdf inout.pdf --json | jq '.acroform.fields'

qpdf is a lightweight cross-platform FOSS library and jq is a filtering program for JSON (like grep is a filtering program for lines). If you'd rather not use jq or JSON, you can always dump using qpdf input.pdf then look for the metadata yourself in the dump.

C# / ITextSharp

    public static void TracePdfFields(string pdfFilePath)
    {
        PdfReader pdfReader = new PdfReader(pdfFilePath);
        MemoryStream pdfStream = new MemoryStream();
        PdfStamper pdfStamper = new PdfStamper(pdfReader, pdfStream, '\0', true);

        int i = 1;
        foreach (var f in pdfStamper.AcroFields.Fields)
        {
            pdfStamper.AcroFields.SetField(f.Key, string.Format("{0} : {1}", i, f.Key));
            i++;
            //DoTrace("Field = [{0}] | Value = [{1}]", f.Key, f.Value.ToString());
        }
        pdfStamper.FormFlattening = false;
        pdfStamper.Writer.CloseStream = false;
        pdfStamper.Close();

        FileStream fs = File.OpenWrite(string.Format(@"{0}/{1}-TracePdfFields_{2}.pdf", 
            ConfigManager.GetInstance().LogConfig.Dir, 
            new FileInfo(pdfFilePath).Name, 
            DateTime.Now.Ticks));

        fs.Write(pdfStream.ToArray(), 0, (int)pdfStream.Length);
        fs.Flush();
        fs.Close();
    }

I can get my client to export the XFDF file (which contains field names) using Acrobat along with the PDF, which avoids this problem completely.

Related