首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用iTextsharp将PDF拆分为多个PDF

使用iTextsharp将PDF拆分为多个PDF
EN

Stack Overflow用户
提问于 2013-09-12 18:40:29
回答 4查看 33.5K关注 0票数 18
代码语言:javascript
复制
public int SplitAndSave(string inputPath, string outputPath)
    {
        FileInfo file = new FileInfo(inputPath);
        string name = file.Name.Substring(0, file.Name.LastIndexOf("."));

        using (PdfReader reader = new PdfReader(inputPath))
        {

            for (int pagenumber = 1; pagenumber <= reader.NumberOfPages; pagenumber++)
            {
                string filename = pagenumber.ToString() + ".pdf";

                Document document = new Document();
                PdfCopy copy = new PdfCopy(document, new FileStream(outputPath + "\\" + filename, FileMode.Create));

                document.Open();

                copy.AddPage(copy.GetImportedPage(reader, pagenumber));

                document.Close();
            }
            return reader.NumberOfPages;
        }

    }

我想把Pdf分成50页间隔的多个PDF。(假设有400页的PDF,我想8个PDF)。上面的代码将每个页面拆分成一个pdf。请帮帮我...我正在和iTextSharp一起使用asp.net。

EN

回答 4

Stack Overflow用户

发布于 2013-09-12 20:45:06

每次前进一个页面时,您都会遍历pdf并创建一个新文档。您需要跟踪您的页面,以便每50页才执行一次拆分。就我个人而言,我会把它放在一个单独的方法中,然后从你的循环中调用它。如下所示:

代码语言:javascript
复制
private void ExtractPages(string sourcePDFpath, string outputPDFpath, int startpage,  int endpage)
{
    PdfReader reader = null;
    Document sourceDocument = null;
    PdfCopy pdfCopyProvider = null;
    PdfImportedPage importedPage = null;

    reader = new PdfReader(sourcePDFpath);
    sourceDocument = new Document(reader.GetPageSizeWithRotation(startpage));
    pdfCopyProvider = new PdfCopy(sourceDocument, new System.IO.FileStream(outputPDFpath, System.IO.FileMode.Create));

    sourceDocument.Open();

    for (int i = startpage; i <= endpage; i++)
    {
        importedPage = pdfCopyProvider.GetImportedPage(reader, i);
        pdfCopyProvider.AddPage(importedPage);
    }
    sourceDocument.Close();
    reader.Close();
}

所以在你的原始代码中,循环遍历你的pdf,每50页调用一次上面的方法。您只需要在块中添加变量来跟踪开始/结束页面。

票数 15
EN

Stack Overflow用户

发布于 2013-09-12 18:45:09

这将是有用的。非常符合您的要求

http://www.codeproject.com/Articles/559380/SplittingplusandplusMergingplusPdfplusFilesplusinp

票数 4
EN

Stack Overflow用户

发布于 2019-01-07 21:56:02

这里有一个较短的解决方案。还没有测试哪种方法的性能更好。

代码语言:javascript
复制
private void ExtractPages(string sourcePDFpath, string outputPDFpath, int startpage, int endpage)
{
  var pdfReader = new PdfReader(sourcePDFpath);
  try
  {
    pdfReader.SelectPages($"{startpage}-{endpage}");
    using (var fs = new FileStream(outputPDFpath, FileMode.Create, FileAccess.Write))
    {
      PdfStamper stamper = null;
      try
      {
        stamper = new PdfStamper(pdfReader, fs);
      }
      finally
      {
        stamper?.Close();
      }
    }
  }
  finally
  {
    pdfReader.Close();
  }
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/18762007

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档