2014-02-11 39 views
1

我有要求將pdf合併在一起的要求。我需要將特定頁面的pdf導入到另一個頁面。在特定頁面導入pdf

讓我來向你說明一下。

我有兩個pdf,第一個是50頁長,第二個是4頁長。我需要在第一個pdf的第13頁導入第二個。

我沒有找到任何例子。關於如何合併PDF文件有很多例子,但沒有關於在特定頁面合併的內容。

基於this exemple它看起來像我需要逐一遍歷所有頁面並將它們導入到一個新的pdf中。這看起來有點痛苦,如果你有大pdf並且需要合併很多。我會創建x新pdf以合併x + 1 pdf。

有什麼我不明白或是真的要走的路?

+0

這很容易在Acrobat。工具 - >從文件插入 - >選擇文件,位於第13頁後面的位置。 –

+0

@OtávioDécio我需要以編程方式完成此操作,理想情況是取決於Acrobat –

回答

2

從示例中借用,這應該很容易做一些修改。您只需要在合併之前添加所有頁面,然後添加第二個文檔中的所有頁面,然後添加原始頁面的所有其餘頁面。

嘗試這樣的事情(未測試或健壯 - 只是一個起點,也許):

// Used the ExtractPages as a starting point. 
public void MergeDocuments(string sourcePdfPath1, string sourcePdfPath2, 
    string outputPdfPath, int insertPage) { 
    PdfReader reader1 = null; 
    PdfReader reader2 = null; 
    Document sourceDocument1 = null; 
    Document sourceDocument2 = null; 
    PdfCopy pdfCopyProvider = null; 
    PdfImportedPage importedPage = null; 

    try { 
     reader1 = new PdfReader(sourcePdfPath1); 
     reader2 = new PdfReader(sourcePdfPath2); 

     // Note, I'm assuming pages are 0 based. If that's not the case, change to 1. 
     sourceDocument1 = new Document(reader1.GetPageSizeWithRotation(0)); 
     sourceDocument2 = new Document(reader2.GetPageSizeWithRotation(0)); 

     pdfCopyProvider = new PdfCopy(sourceDocument1, 
      new System.IO.FileStream(outputPdfPath, System.IO.FileMode.Create)); 

     sourceDocument1.Open(); 
     sourceDocument2.Open(); 

     int length1 = reader1.NumberOfPages; 
     int length2 = reader2.NumberOfPages; 
     int page1 = 0; // Also here I'm assuming pages are 0-based. 

     // Having these three loops is the key. First is pages before the merge.   
     for (;page1 < insertPage && page1 < length1; page1++) { 
      importedPage = pdfCopyProvider.GetImportedPage(reader1, page1); 
      pdfCopyProvider.AddPage(importedPage); 
     } 

     // These are the pages from the second document. 
     for (int page2 = 0; page2 < length2; page2++) { 
      importedPage = pdfCopyProvider.GetImportedPage(reader2, page2); 
      pdfCopyProvider.AddPage(importedPage); 
     } 

     // Finally, add the remaining pages from the first document. 
     for (;page1 < length1; page1++) { 
      importedPage = pdfCopyProvider.GetImportedPage(reader1, page1); 
      pdfCopyProvider.AddPage(importedPage); 
     } 

     sourceDocument1.Close(); 
     sourceDocument2.Close(); 
     reader1.Close(); 
     reader2.Close(); 
    } catch (Exception ex) { 
     throw ex; 
    } 
} 
+0

我會試一試謝謝 –