首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >为什么我的PDF文件大小增加后分裂和合并回来?(使用PDFSharp c#)

为什么我的PDF文件大小增加后分裂和合并回来?(使用PDFSharp c#)
EN

Stack Overflow用户
提问于 2022-09-27 07:50:11
回答 1查看 60关注 0票数 0

我基本上是把一个PDF文档分成多个文件,每个文档包含一页。拆分后,我执行一些操作,并将文档合并回一个PDF格式。我正在使用PDFsharp中的c#来完成这个任务。现在,我面临的问题是,当我拆分文档并将它们添加回时,文件大小从1.96Mbs增加到12.2Mbs。经过彻底测试后,我指出问题不在于我在拆分后所执行的操作,而在于PDF文件的实际分割和合并。以下是我所创造的功能。

代码语言:javascript
复制
 public static List<Stream> SplitPdf(Stream PdfDoc)
    {
        System.Text.Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance);
        List<Stream> outputStreamList = new List<Stream>();
        PdfSharp.Pdf.PdfDocument inputDocument = PdfReader.Open(PdfDoc, PdfDocumentOpenMode.Import);

        for (int idx = 0; idx < inputDocument.PageCount; idx++)
        {
            PdfSharp.Pdf.PdfDocument outputDocument = new PdfSharp.Pdf.PdfDocument();
            outputDocument.Version = inputDocument.Version;
            outputDocument.Info.Title =
              String.Format("Page {0} of {1}", idx + 1, inputDocument.Info.Title);
            outputDocument.Info.Creator = inputDocument.Info.Creator;

            outputDocument.AddPage(inputDocument.Pages[idx]);
            MemoryStream stream = new MemoryStream();
            outputDocument.Save(stream);
            outputStreamList.Add(stream);
        }
        return outputStreamList;
    }

 public static Stream MergePdfs(List<Stream> PdfFiles)
    {
        System.Text.Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance);
        PdfSharp.Pdf.PdfDocument outputPDFDocument = new PdfSharp.Pdf.PdfDocument();
        foreach (Stream pdfFile in PdfFiles)
        {
            PdfSharp.Pdf.PdfDocument inputPDFDocument = PdfReader.Open(pdfFile, PdfDocumentOpenMode.Import);
            outputPDFDocument.Version = inputPDFDocument.Version;
            foreach (PdfSharp.Pdf.PdfPage page in inputPDFDocument.Pages)
            {
                outputPDFDocument.AddPage(page);
            }
        }
        Stream compiledPdfStream = new MemoryStream();
        outputPDFDocument.Save(compiledPdfStream);
        return compiledPdfStream;
    }

我的问题是:

  1. 为什么我会有这种行为?
  2. 有一个解决方案,可以执行拆分和合并,然后得到相同大小的文件吗?(可以是任何开放源码 c#库)
EN

回答 1

Stack Overflow用户

发布于 2022-09-27 16:06:08

对问题1的答复:

当分割文件时,每个文件将包含它所包含的页面所需的所有资源。

当再次与PDFsharp合并时,资源将不会合并,最终文档可能包含重复的资源(字体、图像),从而导致更大的文件。

这是故意的。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73864088

复制
相关文章

相似问题

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