Search code examples
c#pdfitext7xfa

Using C# iText 7 to flatten an XFA PDF


Is it possible to use iText 7 to flatten an XFA PDF? I'm only seeing Java documentation about it (http://developers.itextpdf.com/content/itext-7-examples/itext-7-form-examples/flatten-xfa-using-pdfxfa).

It seems like you can use iTextSharp, however to do this.

I believe it's not an AcroForm PDF because doing something similar to this answer How to flatten pdf with Itext in c#? simply created a PDF that wouldn't open properly.


Solution

  • It looks like you have to use iTextSharp and not iText7. Looking at the NuGet version it looks like iTextSharp is essentially the iText5 .NET version and like Bruno mentioned in the comments above, the XFA stuff simply hasn't been ported to iText7 for .NET.

    The confusion stemmed from having both iText7 and iTextSharp versions in NuGet and also the trial page didn't state that the XFA worker wasn't available for the .NET version of iText7 (yet?)

    I did the following to accomplish what I needed at least for a trial:

    1. Request trial copy here: http://demo.itextsupport.com/newslicense/

    2. You'll be emailed an xml license key, you can just place it on your desktop for now.

    3. Create a new console application in Visual Studio

    4. Open the Project Manager Console and type in the following and press ENTER (this will install other dependencies as well)

      Install-Package itextsharp.xfaworker
      
    5. Use the following code:

    static void Main(string[] args)
    {
        ValidateLicense();
        var sourcePdfPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory), "<your_xfa_pdf_file>");
        var destinationPdfPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory), "output.pdf");
        FlattenPDF(sourcePdfPath, destinationPdfPath);
    }
    
    private static void ValidateLicense()
    {
        var licenseFileLocation = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory), "itextkey.xml");
        iTextSharp.license.LicenseKey.LoadLicenseFile(licenseFileLocation);
    }
    
    private static void FlattenPDF(string sourcePdfPath, string destinationPdfPath)
    {
        using (var sourcePdfStream = File.OpenRead(sourcePdfPath))
        {
            var document = new iTextSharp.text.Document();
            var writer = iTextSharp.text.pdf.PdfWriter.GetInstance(document, new FileStream(destinationPdfPath, FileMode.Create));
            var xfaf = new iTextSharp.tool.xml.xtra.xfa.XFAFlattener(document, writer);
            sourcePdfStream.Position = 0;
            xfaf.Flatten(new iTextSharp.text.pdf.PdfReader(sourcePdfStream));
            document.Close();
        }
    }
    

    The trial will put a huge watermark on the resulting PDF, but at least you can get it working and see how the full license should work.