Skip to main content
 首页 » 编程设计

c#之如何使用 C# 按文件大小拆分 PDF 文件

2024年02月20日13mayingbao

我找到了一个 How to break a PDF into parts演示如何使用 Adob​​e Acrobat 按页面或最大文件大小将 PDF 文件拆分为单独的 PDF 文件的教程:

我有found many examples关于如何使用 C# 按页拆分 PDF 的 StackOverflow。但是我该怎么做后者呢?如何使用 C# 将一个 PDF 文件按最大文件大小拆分为多个 PDF 文件?

例如,假设我有一个 70 页和 40 MB 的 PDF 文件。我如何使用 C# 将文件拆分为大约 5 个不超过 10 MB 的 PDF 文件,而不是拆分为每个 10 页的 7 个 PDF 文件?

到目前为止,我看到的最好的方法是 Using itextsharp to split a pdf into smaller pdf's based on size其中 Cyfer13二手 iTextSharp按页面拆分文件,然后按大小对这些页面文件进行分组。但是,是否有更直接的方法来实现这一点而无需先按页面拆分?

请您参考如下方法:

从PDFsharp Sample: Split Document开始,我写了下面的 SplitBySize 方法:

public static void SplitBySize(string filename, long limit) 
{ 
    PdfDocument input = PdfReader.Open(filename, PdfDocumentOpenMode.Import); 
    PdfDocument output = CreateDocument(input); 
 
    string name = Path.GetFileNameWithoutExtension(filename); 
    string temp = string.Format("{0} - {1}.pdf", name, 0); 
    int j = 1; 
    for (int i = 0; i < input.PageCount; i++) 
    { 
        PdfPage page = input.Pages[i]; 
        output.AddPage(page); 
        output.Save(temp); 
        FileInfo info = new FileInfo(temp); 
        if (info.Length <= limit) 
        { 
            string path = string.Format("{0} - {1}.pdf", name, j); 
            if (File.Exists(path)) 
            { 
                File.Delete(path); 
            } 
            File.Move(temp, path); 
        } 
        else 
        { 
            if (output.PageCount > 1) 
            { 
                output = CreateDocument(input); 
                ++j; 
                --i; 
            } 
            else 
            { 
                throw new Exception( 
                    string.Format("Page #{0} is greater than the document size limit of {1} MB (size = {2})", 
                    i + 1, 
                    limit / 1E6, 
                    info.Length)); 
            } 
        } 
    } 
} 

我会继续测试,但到目前为止它是有效的。