2014-12-03 142 views
2

我有兩個PDF文件(名爲:A1.pdf和B1.pdf)。現在我想以編程方式將第二個PDF文件(B1.pdf)的一些頁面替換爲第一個(A1.pdf)。在這種情況下,我正在使用PDFBox庫。使用PDFBox替換PDF頁面

這裏是我的示例代碼:

try { 
     File file = new File("/Users/test/Desktop/A1.pdf"); 
     PDDocument pdDoc = PDDocument.load(file); 

     PDDocument document = PDDocument.load(new File("/Users/test/Desktop/B1.pdf")); 
     document.removePage(3); 
     document.addPage((PDPage) pdDoc.getDocumentCatalog().getAllPages().get(0)); 
     document.save("/Users/test/Desktop/"+"generatedPDFBox"+".pdf"); 
     document.close(); 
    }catch(Exception e){} 

的想法是,以取代第3頁。在這個實現中,頁面被附加到輸出pdf的最後一頁。任何人都可以幫我實現這個嗎?如果不使用PDFBOX。你能否在Java中推薦一些其他庫?

+0

@Anuff,感謝您的代碼片段。但我的主要目標是使用開源軟件包。如果不是庫/ API,那麼是否有可用的命令行實用工具?這也應該完成我的任務..在那裏的任何志願者? – Rivu 2014-12-03 22:54:28

+0

@Tilman,感謝代碼片段 – Rivu 2014-12-04 14:45:27

回答

1

此解決方案創建第三個PDF文件,其中包含您要求的內容。請注意,頁面爲零,所以您問題中的「3」必須是「2」。

PDDocument a1doc = PDDocument.load(file1); 
    PDDocument b1doc = PDDocument.load(file2); 
    PDDocument resDoc = new PDDocument(); 

    List<PDPage> a1Pages = a1doc.getDocumentCatalog().getAllPages(); 
    List<PDPage> b1Pages = b1doc.getDocumentCatalog().getAllPages(); 

    // replace the 3rd page of the 2nd file with the 1st page of the 1st one 
    for (int p = 0; p < b1Pages.size(); ++p) 
    { 
     if (p == 2) 
      resDoc.addPage(a1Pages.get(0)); 
     else 
      resDoc.addPage(b1Pages.get(p)); 
    } 

    resDoc.save(file3); 
    a1doc.close(); 
    b1doc.close(); 
    resDoc.close(); 

如果你想在命令行工作,而不是,請看這裏: https://pdfbox.apache.org/commandline/

然後使用PDFSplit和PDFMerge。

+0

我只是想知道......頁面導入的AcroForm字段註釋是什麼,這些字段在'addPage或稍後的步驟?'期間還添加到文檔AcroForm字典中? – mkl 2014-12-04 09:55:35

+0

請勿知道......我相信即使使用PDFMerge也存在問題,但在某個地方存在問題。 – 2014-12-04 09:58:55

1

我不太熟悉PDFBox的工作原理,但爲了回答您的後續問題我知道您可以用Datalogics APDFL SDK以相當簡單的方式完成您想要的工作。如果您想查看它,可以免費試用。下面的代碼片段,所以你可以看到它是如何完成的:

Document Doc1 = new Document("/Users/test/Desktop/A1.pdf"); 
Document Doc2 = new Document("/Users/test/Desktop/B1.pdf"); 

/* Delete pages on the page range 3-3*/ 
Doc2.deletePages(3, 3) 

/* LastPage is where in Doc2 you want to insert the page, Doc1 the document from which the page is coming from, 0 is the page number in Doc1 that will be inserted first, 1 is the number of pages that will be inserted (beginning from the page number specified in the previous parameter), and PageInsertFlags which would let you customize what gets/doesn't get copied */ 
Doc2.insertPages(Document.LastPage, Doc1, 0, 1, PageInsertFlags.All); 

Doc2.save(EnumSet.of(SaveFlags.FULL), "out.pdf") 

另外,有一個名爲replacePages另一種方法,這使得刪除不必要的。當然,這一切都取決於你的最終目標是什麼。