在特定页面导入pdf

时间:2014-02-11 18:14:03

标签: c# itextsharp

我要求将pdf合并在一起。我需要将特定页面的pdf导入另一页。

让我向你说明一下。

我有两个pdf,第一个是50页长,第二个是4页长。我需要在第一个pdf的第13页导入第二个。

我没有找到任何例子。关于如何合并pdf有很多例子,但没有关于在特定页面合并的内容。

基于this exemple看起来我需要逐个迭代所有页面并将其导入新的pdf中。如果你有大的pdf并且需要合并很多,那看起来有点痛苦。我会创建x new pdf来合并x + 1 pdf。

有什么我不明白的,或者它真的是要走的路?

1 个答案:

答案 0 :(得分: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;
    }
}
相关问题