2012-12-21 53 views
7

iText(特にiTextSharp 4.1.6)を使用しています。既存のPDFからページを結合するだけでなく、イメージから作成した新しいページを挿入してPDFを作成したいと思います。iText - PdfCopyで作成したドキュメントにページを追加する方法

私はこれら2つの部分をそれぞれPdfCopyとPdfWriterを使って別々に動作させています。画像からページを作成するためのコードは次のようになります。今

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

PdfCopyがPDFWriterのから継承しているので、私は、私は同じ技術を使用して、私のPdfCopy対象に、そのような「画像ページ」を追加することができるだろうと思いました上記の例でPdfWriterの代わりにPdfCopyをインスタンス化すると、ページに何も表示されません)。

私は、PdfCopyのコンストラクタがスーパークラスのコンストラクタを呼び出すときに渡されたものではなく、新しいDocumentオブジェクトを使用していることに気づいたので、これが理由です。

これについてもっと良い方法がありますか?現時点では、私の最高の推測は、PdfWriterを使用してイメージから単一のページPdfを作成し、それをPdfCopyを使用してドキュメントに追加することですが、これは回避策のようです。

+1

あなたは私に周りの仕事として記述何が適切なソリューションです。 PdfCopyは、複数のPDFを結合するように設計されており、既存のPDFとそれを新しく作成したPDFに適用します。画像が大きすぎない場合は、そのPDFをメモリ(バイト[])で作成してそこから読み取ることができます。したがって、一時ファイルを追加する必要はありません。 – mkl

+0

ありがとう - 私はiTextにあまり慣れていないので、完全に機能しているように思えます。私は一時的なPDFをメモリ内に作成して実装しました。それはすべてうまく動作します:-) – Andy

答えて

7

私は最近、この問題を抱えていました。私のユースケースは、基本的には「PDFと画像の束(.jpg、.pngなど)を1つのPDFにまとめる」でした。私はPdfCopyを使う必要がありました。なぜなら、PdfWriterがどこでないフォームフィールドやラベルのようなものを保存しているからです。

基本的には、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(); 
     } 

    } 
関連する問題