使用C#iText 7压平XFA PDF

时间:2017-04-11 19:36:47

标签: c# pdf itext7 xfa

是否可以使用iText 7压平XFA PDF?我只看到有关它的Java文档(http://developers.itextpdf.com/content/itext-7-examples/itext-7-form-examples/flatten-xfa-using-pdfxfa)。

看起来您可以使用iTextSharp来执行此操作。

我认为它不是AcroForm PDF,因为做类似于这个答案的How to flatten pdf with Itext in c#?只是创建了一个无法正常打开的PDF。

2 个答案:

答案 0 :(得分:2)

看起来你必须使用iTextSharp而不是iText7。看看NuGet版本,它看起来像iTextSharp本质上是iText5 .NET版本,就像上面评论中提到的Bruno一样,XFA的东西根本没有被移植到iText7 for .NET。

混淆源于在NuGet中同时拥有iText7和iTextSharp版本,而且试用页面也没有说明XFA工作者不能用于iText7的.NET版本(还有?)

我做了以下工作来完成我至少需要试用的东西:

  1. 请在此处申请试用版:http://demo.itextsupport.com/newslicense/
  2. 您将通过电子邮件发送xml许可证密钥,暂时可以将其放在桌面上。
  3. 在Visual Studio中创建新的控制台应用程序
  4. 打开项目管理器控制台并输入以下内容并按ENTER键(这也将安装其他依赖项)

    Install-Package itextsharp.xfaworker
    
  5. 使用以下代码:

     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();
            }
        }
    
  6. 试用版会在生成的PDF上留下巨大的水印,但至少你可以让它工作,看看完整的许可证应该如何运作。

答案 1 :(得分:1)

对于IText 7,这可以通过以下方式完成

LicenseKey.LoadLicenseFile(@"Path of the license file");
MemoryStream dest_File = new MemoryStream();
XFAFlattener xfaFlattener = new XFAFlattener();
xfaFlattener.Flatten(new MemoryStream( File.ReadAllBytes(@"C:\\Unflattened file")), dest_File);
File.WriteAllBytes("flatten.pdf", dest_File.ToArray());
相关问题