2013-10-15 52 views
1

我的目標是打開一個現有的PDF,添加或刪除一些頁面,同時在Windows.Forms C#應用程序中保留元數據(作者,主題,...)。修改現有的pdf(添加/刪除頁面),同時保留元數據

我使用iTextSharp,並找到示例如何使用PdfConcatenate類添加或刪除頁面。爲了保留元數據,我使用了一個PdfStamper。爲了加快速度,我希望在將結果存儲到磁盤之前在內存中進行修改。

問題是不添加或刪除頁面,而是保持元數據在同一步驟。 那麼有人可以告訴我/ giva一個關於如何實現這個(更好)的例子,還是我在完全錯誤的軌道上?

這裏我當前的代碼(見問題相關的行註釋):需要進行

public void RemovePagesInFile(string documentLocation, int pageIndexFrom, int pageCount) 
{ 
    // TB: open the pdf 
    using (PdfReader sourcePdfReader = new PdfReader(documentLocation)) 
    using (MemoryStream concatenatedTargetStream = new MemoryStream((int)sourcePdfReader.FileLength)) 
    { 
     // TB: use a concatenator to create a new pdf containing only the desired pages 
     PdfConcatenate concatenator = new PdfConcatenate(concatenatedTargetStream); 

     // TB: create a list with the page numbers to keep 
     List<int> pagesToKeep = new List<int>(); 
     for (int i = 1; i <= pageIndexFrom; i++) 
     { 
      pagesToKeep.Add(i); 
     } 

     for (int i = pageIndexFrom + pageCount + 1; i <= sourcePdfReader.NumberOfPages; i++) 
     { 
      pagesToKeep.Add(i); 
     } 

     // TB: execute the page copy 
     sourcePdfReader.SelectPages(pagesToKeep); 
     concatenator.AddPages(sourcePdfReader); 

     // TB: problem(s) here: 
     // 1. when calling concatenator.Close() the memory stream gets disposed as expected. 
     // concatenator.Close(); 
     // 2. even when calling concatenator.WriterFlush() the memory stream seems to be missing content (error when creating targetReader (see below)). 
     // concatenator.Writer.Flush(); 
     // 3. when keeping concatenator open the same error as above occures (I assume not all bytes have been written to the memory stream) 

     // TB: preserve the meta data from the source document 
     // => ERROR here: "Rebuild trailer not found. Original Error: PDF startxref not found" 
     using (PdfReader targetReader = new PdfReader(concatenatedTargetStream)) 
     using (MemoryStream targetStream = new MemoryStream((int)concatenatedTargetStream.Length)) 
     { 
      using (PdfStamper stamper = new PdfStamper(targetReader, targetStream)) 
      { 
       stamper.MoreInfo = sourcePdfReader.Info; 

       // TB: same problem as above with stamper ? 
       stamper.Close(); 
      } 

      // TB: close the reader to be able to access the source pdf 
      sourcePdfReader.Close(); 

      // TB: write the modified pdf to the disk 
      File.WriteAllBytes(documentLocation, targetStream.ToArray()); 
     } 
    } 
} 
+0

我沒有超過10個聲譽點,所以可以請任何人發佈以下答案:...編輯:也不工作 - 文本太長的評論* grrrr * –

+0

簡單和簡單:解決方案在調用「concatenator.Close()」之前調用「concatenator.Writer.CloseStream = false」,並在PdfStamper中調用相同的調用: 。因此,如果有更多聲譽的人會將此作爲答案:謝謝! –

回答

0

兩個變化。呼叫

concatenator.Writer.CloseStream = false 

調用

concatenator.Close() 

做的PdfStamper同樣的事情之前,你就設置。

相關問題