2012-12-21 73 views
7

我正在使用iText(特別是iTextSharp 4.1.6),並且我想通過組合來自現有PDF的頁面創建PDF,但也插入從圖像創建的新頁面。iText - 如何將頁面添加到使用PdfCopy創建的文檔

我得到了這兩個部分分別使用PdfCopy和PdfWriter分別工作。從圖像中創建一個頁面的代碼如下所示:

PdfWriter pw = PdfWriter.GetInstance(doc, outputStream); 
Image img = Image.GetInstance(inputStream); 
doc.Add(img); 
doc.NewPage(); 

現在,由於PdfCopy從PdfWriter繼承,我想我應該能夠添加使用相同的技術,例如「圖像」我PdfCopy對象,但它不起作用(如果你在上面的例子中實例化一個PdfCopy而不是PdfWriter,那麼頁面上沒有任何東西出現)。

從源代碼的快速瀏覽我注意到,當PdfCopy的contstructor調用超類的構造函數時,它使用新的Document對象,而不是傳入的,所以我想這就是原因。

有沒有更好的方法來解決這個問題?目前我最好的猜測是使用PdfWriter從圖像中創建一個頁面Pdf,然後使用PdfCopy將其添加到文檔中,但這似乎有點解決方法。

+1

你身邊描述爲一個工作,我什麼似乎是一個妥善的解決辦法。 PdfCopy設計用於合併多個PDF文件,並將其應用到您以前存在的PDF文件中,並將其應用於您的新文件。如果圖像不太大,可以在內存中創建該PDF(byte [])並從那裏讀取;因此,甚至不需要額外的臨時文件。 – mkl

+0

謝謝 - 我不太熟悉iText,它看起來如此全面,我只是不確定是否有其他方式來完成此操作。我已經實現了它在內存中創建臨時PDF,並且它的所有工作都很可愛:-) – Andy

回答

7

我最近有這個問題,這裏的答案實際上並沒有幫助。我的用例基本上是「帶一堆PDF和圖像(.jpg,.png等),並將它們全部合併爲一個PDF」。我不得不使用PdfCopy,因爲它保留了PdfWriter所不具備的表單域和標籤等內容。

基本上,由於PdfCopy不允許您使用addPage()創建新頁面,因此必須在頁面上使用圖像在內存中創建一個新的PDF,然後使用PdfCopy從該PDF中複製頁面。

例如:

Document pdfDocument = new Document(); 
    ByteArrayOutputStream pdfOutputStream = new ByteArrayOutputStream(); 
    PdfCopy copy = new PdfCopy(pdfDocument, pdfOutputStream); 

    pdfDocument.open(); 

    for (File file : allFiles) { 
     if (/* file is PDF */) { 
      /* Copy all the pages in the PDF file into the new PDF */ 
      PdfReader reader = new PdfReader(file.getAllBytes()); 
      for (int i = 1; i <= reader.getNumberOfPages(); i++) { 
       copy.addPage(copy.getImportedPage(reader, i); 
      } 
     } else { 
      /* File is image. Create a new PDF in memory, write the image to its first page, and then use PdfCopy to copy that first page back into the main PDF */ 
      Document imageDocument = new Document(); 
      ByteArrayOutputStream imageDocumentOutputStream = new ByteArrayOutputStream(); 
      PdfWriter imageDocumentWriter = PdfWriter.getInstance(imageDocument, imageDocumentOutputStream); 

      imageDocument.open(); 

      if (imageDocument.newPage()) { 

       image = Image.getInstance(file.getAllBytes()); 

       if (!imageDocument.add(image)) { 
        throw new Exception("Unable to add image to page!"); 
       } 

       imageDocument.close(); 
       imageDocumentWriter.close(); 

       PdfReader imageDocumentReader = new PdfReader(imageDocumentOutputStream.toByteArray()); 

       copy.addPage(copy.getImportedPage(imageDocumentReader, 1)); 

       imageDocumentReader.close(); 
     } 

    } 
相關問題