从现有PDF中提取一系列页面到新文件

时间:2013-10-21 06:04:31

标签: c# asp.net pdf itextsharp

public void ExtractPages(string sourcePdfPath, string outputPdfPath, int startPage, int endPage)
{
    PdfReader reader = null;
    Document sourceDocument = null;
    PdfCopy pdfCopyProvider = null;
    PdfImportedPage importedPage = null;
    try
    {
        // Intialize a new PdfReader instance with the contents of the source Pdf file:
        reader = new PdfReader(sourcePdfPath);

        // For simplicity, I am assuming all the pages share the same size
        // and rotation as the first page:
        sourceDocument = new Document(reader.GetPageSizeWithRotation(startPage));

        // Initialize an instance of the PdfCopyClass with the source 
        // document and an output file stream:
        pdfCopyProvider = new PdfCopy(sourceDocument, 
            new System.IO.FileStream(outputPdfPath, System.IO.FileMode.Create));

        sourceDocument.Open();

        // Walk the specified range and add the page copies to the output file:
        for (int i = startPage; i <= endPage; i++)
        {
            importedPage = pdfCopyProvider.GetImportedPage(reader, i);
            pdfCopyProvider.AddPage(importedPage);
        }

        sourceDocument.Close();
        reader.Close();
    }
    catch (Exception ex)
    {
        throw ex;
    }
}

我正在使用asp.net应用程序。我使用以下方法将现有PDF页面范围提取到新文件。但我得到了#34;拒绝访问路径&#34;错误消息。但我得到了#34;拒绝访问路径&#34;错误信息。

修改

这一行引发了错误:

pdfCopyProvider = new PdfCopy(sourceDocument, 

            new System.IO.FileStream(outputPdfPath, System.IO.FileMode.Create));

2 个答案:

答案 0 :(得分:1)

看看下面的代码:

//You have to add GroupDocs.Merger for .NET DLL in your project 
ExtractOptions extractOptions = new ExtractOptions(3, 9); 
using (Merger merger = new Merger(@"D:/source.pdf")) 
{ 
    merger.ExtractPages(extractOptions); 
    merger.Save(@"D:/result.pdf"); 
} 

在这段代码中,我将从页面3到9之间的PDF中提取所有页面。还有更多选项,例如通过指定确切的页面编号或通过specifying page numbers range来提取页面。

答案 1 :(得分:0)

试试这个,

PdfReader R = new PdfReader(srcPdfFilePath);
using (PdfStamper stamper = new PdfStamper(R, new FileStream(dPdfFile, FileMode.Create)))
{
// if you want to do any changes in new pdf do here.
stamper.Close();
}
R.Close();

注意:

源PDf路径&amp;名称和新的pdf路径&amp;名称不应该相同。因为文件打开时无法覆盖。