2012-07-27 80 views
1

我發現了一個How to break a PDF into parts教程演示如何或者通過網頁或通過使用Adobe Acrobat最大文件大小來分割PDF文件轉換成單獨的PDF文件:如何使用C#按文件大小拆分PDF文件?

Tools > Split Document > Split document by File size

foundmanyexamples在計算器上如何用C#分頁PDF。但我怎麼做後者?如何使用C#以最大文件大小將PDF文件分割爲多個PDF文件?

例如,假設我有一個70頁,40 MB的PDF文件。如何將文件分成大約5個不超過10 MB的PDF文件(每個文件使用C#),而不是將它們分成7個PDF文件(每個文件10頁)?

到目前爲止,我所看到的最好的方法是在Using itextsharp to split a pdf into smaller pdf's based on size其中Cyfer13使用iTextSharp按頁分割文件,然後按大小分組這些頁面文件。但是,在沒有首先分頁的情況下,更直接的方式來實現這一點?

回答

1

這是一個未經測試示例代碼,假設你準備在純二進制級別分裂,即部件將不會受到PDF閱讀器進行閱讀,而你將不得不重新加入部分,使其可讀:

下面的代碼首先獲取一個byte []數組中的pdf文件。然後根據任意分區大小(本例中爲5)獲取每個部分二進制文件的文件大小。然後,它將創建一個臨時內存流並循環直至創建每個分區並寫入新的.part文件。 (您可能需要進行一些更改才能使其可行)。

 byte[] pdfBytes = File.ReadAllBytes("c:\foo.pdf"); 
     int fileSize = pdfBytes.Length/5; //assuming foo is 40MB filesize will be abt 8MB 
     MemoryStream m = new MemoryStream(pdfBytes); 
     for (int i = 0; i < 4; i++) 
     { 
      byte[] tbytes = new byte[fileSize]; 
      m.Read(tbytes,i*fileSize,fileSize); 
      File.WriteAllBytes("C:\foo" + i + ".part",tbytes); 
     } 
+0

感謝您的回答,但我確實需要生成的文件爲PDF格式。我已經更新了我的問題,以便更具體。 – 2012-07-27 19:10:57

+0

在這種情況下,也許您可​​以檢查PDFSharp,這是一個開源庫,可讓您通過.NET處理PDF文件:http://pdfsharp.codeplex.com/ – 2012-07-27 19:15:47

2

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)); 
      } 
     } 
    } 
} 

我將繼續測試,但它的工作至今。