2013-03-09 82 views
0

這裏素有代碼意想不到的元素拆分PDF文檔:iTextSharp的:在複印頁面

 try 
     { 
      FileInfo file = new FileInfo(@"d:\С.pdf"); 
      string name = file.Name.Substring(0, file.Name.LastIndexOf(".")); 
      // we create a reader for a certain document 
      PdfReader reader = new PdfReader(@"d:\С.pdf"); 
      // we retrieve the total number of pages 
      int n = reader.NumberOfPages; 
      int digits = 1 + (n/10); 
      System.Console.WriteLine("There are " + n + " pages in the original file."); 
      Document document; 
      int pagenumber; 
      string filename; 

      for (int i = 0; i < n; i++) 
      { 
       pagenumber = i + 1; 
       filename = pagenumber.ToString(); 
       while (filename.Length < digits) filename = "0" + filename; 
       filename = "_" + filename + ".pdf"; 
       // step 1: creation of a document-object 
       document = new Document(reader.GetPageSizeWithRotation(pagenumber)); 
       // step 2: we create a writer that listens to the document 
       PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(name + filename, FileMode.Create)); 
       // step 3: we open the document 
       document.Open(); 
       PdfContentByte cb = writer.DirectContent; 
       PdfImportedPage page = writer.GetImportedPage(reader, pagenumber); 
       int rotation = reader.GetPageRotation(pagenumber); 
       if (rotation == 90 || rotation == 270) 
       { 
        cb.AddTemplate(page, 0, -1f, 1f, 0, 0, reader.GetPageSizeWithRotation(pagenumber).Height); 
       } 
       else 
       { 
        cb.AddTemplate(page, 1f, 0, 0, 1f, 0, 0); 
       } 
       // step 5: we close the document 
       document.Close(); 
      } 
     } 
     catch (DocumentException de) 
     { 
      System.Console.Error.WriteLine(de.Message); 
     } 
     catch (IOException ioe) 
     { 
      System.Console.Error.WriteLine(ioe.Message); 
     } 

這裏留下一個分裂頁面的左上角: enter image description here

您可以在這裏看到(和其他角落)意外的線條,輪..我怎樣才能避免它們?

回答

1

正如前面解釋過多次(ITextSharp include all pages from the input fileItext pdf Merge : Document overflow outside pdf (Text truncated) page and not displaying,等等),你應該看過我的書iText in Action(你可以找到的例子here C#版本)的chapter 6

您正在使用Document,PdfWriterPdfImportedPage的組合來拆分PDF。請告訴我是誰讓你這樣做,這樣我就可以詛咒那些激勵你的人(因爲我之前已經回答了這個問題數百次,而且我厭倦了重複自己)。這些類不適合那份工作是不錯的選擇:

  • 你失去所有的交互性,
  • 你需要的內容自己旋轉,如果頁面是橫向(你已經發現了這一點),
  • 你需要採取原網頁大小兼顧,
  • ...

你的問題是與此類似Itext pdf Merge : Document overflow outside pdf (Text truncated) page and not displaying。顯然你想分割的原始文件包含一個MediaBox和一個CropBox。當您查看原始文檔時,僅顯示CropBox內的內容。當您查看您的副本時,會顯示MediaBox內的內容,並顯示「打印機標記」。這些打印機標記顯示了在發佈環境中需要切割頁面的位置。打印書籍或雜誌時,打印內容的頁面通常比最終頁面大。在組裝書籍或雜誌之前,額外的內容被切斷。

長話短說:閱讀說明文件,用PdfCopy替換PdfWriter,用AddPage()替換AddTemplate()

+0

PdfCopy是我需要的。我在這裏採取了錯誤的代碼http://blog.rubypdf.com/2006/10/11/burstcs-split-a-pdf-in-several-separate-pdf-files-1-per-page/ – 2013-03-09 12:13:03

+0

謝謝,我添加了評論。 – 2013-03-09 12:22:38