【问题标题】:Extract a Range of Pages from Existing PDF to a new File从现有 PDF 中提取一系列页面到新文件
【发布时间】:2013-10-29 12:23:54
【问题描述】:
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 提取到新文件。但是我收到“拒绝访问路径”错误消息。但是我收到“拒绝访问路径”错误消息。

编辑:

这行抛出错误:

pdfCopyProvider = new PdfCopy(sourceDocument, 

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

【问题讨论】:

  • 访问路径被拒绝 - 这样的消息很可能与本地文件系统权限有关,因此与 iTextSharp 本身无关。哪个代码行触发了该消息?请确保您的进程有足够的权限来访问代码要求的sourcePdfPathoutputPdfPath

标签: c# asp.net pdf itextsharp


【解决方案1】:

试试这个,

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 路径和名称与新的 pdf 路径和名称不应相同。因为文件在打开时不能被覆盖。

【讨论】:

  • OP 是否应该使用PdfStamper 而不是PdfCopy, 取决于他的任务要求。不过,您最好强调源 PDf 路径和名称与新的 pdf 路径和名称不应该相同。
  • 抱歉,我仍然收到“访问路径被拒绝”的错误消息
  • @Billy 你检查过哪一行抛出了那个错误吗?您是否检查了所涉及路径的权限?
  • @mkl,问题已更新。如何检查所涉及路径的权限?
  • 看看这个你就会明白的。 (stackoverflow.com/questions/4877741/…),并检查其他应用程序打开的 src PDF 文件。
猜你喜欢
  • 2010-12-31
  • 1970-01-01
  • 2016-03-16
  • 1970-01-01
  • 2021-11-21
  • 2016-04-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多