2013-10-28 26 views
0

我有兩個Document對象如何使用iTextSharp的

如何使用一個合併iTextSharp的這兩個Document對象合併兩個文檔對象?

+0

http://stackoverflow.com/questions/2233129/merging-pdfs-with-itextsharp –

+0

作爲iText的已經在最近幾個月和幾年相當大的變化,對從2010年和2011年的答案指向不一定是有幫助的。 – mkl

+3

我打算把這個標記爲重複,但問題與通常要求的稍有不同。 OP不是合併兩個PDF,而是詢問如何合併兩個「Document」對象。不幸的是,據我所知,沒有辦法合併兩個'Document'對象。這些對象是助手類,可以抽象出PDF文件格式的複雜性。這些抽象的「成本」之一是,你僅限於單個文檔。但是,正如其他人指出的那樣,您可以創建單獨的PDF(甚至是內存),然後合併它們。 –

回答

0

上齶有一點更容易:

你必須採取PDF文檔存儲流,並將它們合併起來!

這是一個簡單的功能,可以實現這個功能!

 public MemoryStream MemoryStreamMerger(List<MemoryStream> streams) 
     { 

      MemoryStream OurFinalReturnedMemoryStream; 
      using (OurFinalReturnedMemoryStream = new MemoryStream()) 
      { 
       //Create our copy object 
       PdfCopyFields copy = new PdfCopyFields(OurFinalReturnedMemoryStream); 

       //Loop through each MemoryStream 
       foreach (MemoryStream ms in streams) 
       { 
        //Reset the position back to zero 
        ms.Position = 0; 
        //Add it to the copy object 
        copy.AddDocument(new PdfReader(ms)); 
        //Clean up 
        ms.Dispose(); 
       } 
       //Close the copy object 
       copy.Close(); 

       //Get the raw bytes to save to disk 
       //bytes = finalStream.ToArray(); 
      } 
      return new MemoryStream(OurFinalReturnedMemoryStream.ToArray()); 

     } 
1

按照哈斯先生(與他的代碼幫助某處SO),

「不幸的是,據我所知,沒有辦法合併兩個文檔對象。這些對象是輔助類它抽象出PDF文件格式的複雜性,這些抽象的「成本」之一是你僅限於單個文檔,但正如其他人指出的那樣,你可以創建單獨的PDF(甚至在內存中)和然後合併它們。「

所以我就是這樣做的:

我用PdfCopyFields對象。

MemoryStream realfinalStream = new MemoryStream(); 
MemoryStream[] realstreams = { stream,new MemoryStream(finalStream.ToArray()) }; 

using (realfinalStream) 
     { 
      //Create our copy object 
      PdfCopyFields copy = new PdfCopyFields(realfinalStream); 

      //Loop through each MemoryStream 
      foreach (MemoryStream ms in realstreams) 
      { 
       //Reset the position back to zero 
       ms.Position = 0; 
       //Add it to the copy object 
       copy.AddDocument(new PdfReader(ms)); 
       //Clean up 
       ms.Dispose(); 
      } 
      //Close the copy object 
      copy.Close(); 
     } 
return File(new MemoryStream(realfinalStream.ToArray()), "application/pdf","hello.pdf"); 

FYI

new MemoryStream(realfinalStream.ToArray()) 

我這樣做,是因爲MemoryString被關閉。

+0

*我這樣做是因爲MemoryString是關閉的。* - 像任何'PdfWriter'一樣,可以告訴'PdfCopy'在關閉時不關閉輸出流。只需在'copy.Close()'之前執行'copy.SetCloseStream(false)'。 – mkl