2013-03-09 81 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