如何在Java中将动态PDF文件与iText库合并?

时间:2012-07-12 10:04:54

标签: java adobe itext livecycle

使用iText库,我可以合并静态PDF文件,但不能合并动态文件。

我该如何完成这项任务?

修改 :(从以下评论中收集):
我很抱歉没有明确说明动态pdf的意思。我现在正在写作 动态pdf文件由adobe livecycle designer创建。它叫“XFA pdf files” Ravinder的代码非常适用于静态pdf。但不适用于XFA pdf文件 它们在合并时不可读(组合)。

我使用了这个动态的pdf文件。

  1. Pdf - > turbobit.net/9rn2r3quw5gx.html
  2. Pdf - > turbobit.net/4e6q7a1ts4jw.html
  3. 如何将它们合并为一个pdf文件?

1 个答案:

答案 0 :(得分:2)

更新了答案

您拥有的PDF文件是使用XFA (XML Forms Architecture)构建的 iText仅对XFA提供部分支持,但对AcroForms完全支持。

您需要展平XFA表单,然后根据需要使用。

您可以参考以下各种有关处理XFA表单的讨论:

  1. dynamic XFA forms; forms created with Adobe LiveCycle Designer
  2. How do you flatten a dynamic XFA form?
  3. iText Demo: Dynamic XFA forms in PDF
  4. 演示:XFA到PDF(Bruno Lowagie的在线公报)
  5. XfaMovie Java example
  6. XFA to PDF: articles/examples on itextpdf.com
  7. 可能更多......

    XfaMovie示例对解决您的要求更有帮助。


    原始答案

    您可以使用所有动态pdf文件的byte[]InputStream形式构建相关的PdfReader对象,并将它们组合以生成单个PDF文件。

    我在示例中使用FileInputStream实例,但您可以从动态PDF内容生成ByteArrayInputStream实例并使用它。

    示例

    import com.itextpdf.text.pdf.PdfCopyFields;
    import com.itextpdf.text.pdf.PdfReader;
    //import com.lowagie.text.pdf.PdfCopyFields;
    //import com.lowagie.text.pdf.PdfReader;
    
    public class CombineDynamicPdfContents
    {
        // throws FileNotFoundException, IOException, DocumentException
        public static void main( String ... a ) throws Exception
        {
            String fileHome = System.getProperty( "user.home" ) + "/Desktop/";
    
            System.out.println( "Start combine PDF files" );
            FileInputStream fis1 = new FileInputStream( fileHome + "pdf-file-1.pdf" );
            FileInputStream fis2 = new FileInputStream( fileHome + "pdf-file-2.pdf" );
    
            // now create pdfreaders using inputstreams of pdf contents
            PdfReader file1 = new PdfReader( fis1 );
            PdfReader file2 = new PdfReader( fis2 );
    
            FileOutputStream fos = new FileOutputStream( fileHome + "Pdf-Combined.pdf" );
            PdfCopyFields copy = new PdfCopyFields( fos );
    
            copy.addDocument( file1 );
            copy.addDocument( file2 );
            copy.close();
    
            System.out.println( "Done ..." );
        } // psvm( .. )
    } // class CombineDynamicPdfContents