2011-08-30 56 views
2

我正在與iText庫一起在Java中進行一些PDF操作,但我正在嘗試做一些iText API開始壓倒我的東西。我真的只需要一個快速教程或一些僞代碼,但這是我想要實現的:Java iText結合衝壓文件

  1. 用戶選擇一系列複選框,指示他或她希望打印哪些PDF。
  2. 根據用戶輸入,抓取1-x PDF模板文件。每個頁面都有一系列需要填寫的AcroFields。
  3. 一個這樣的頁面需要在PDF上繪製一些自定義圖形,即訪問PdfContentByte對象並對其進行操作以插入圖像和矩形。
  4. 如果可能,我想避免將臨時PDF寫入磁盤。之前的程序員做到了這一點,處理這件事一直很麻煩。我更喜歡抓取模板文件,在內存中操作它並直接將其提供給瀏覽器。

我似乎有所有的作品,但我不能完全把它放在一起。點#4是真的讓我沮喪。

TIA。

+1

我可以不記得如何填寫acroforms,但該過程看起來應該不需要任何臨時文件。您可以創建PDF並將其寫入「ByteArrayOutputStream」,並且它將保留在內存中。使用正確的內容類型:'application/pdf',您可以直接使用它。 – Jes

+0

Jes - 這幾乎是我需要的答案。關於BAOS的提示讓我看到了這個教程:http://itextpdf.com/examples/iia.php?id=172。問題是,在我第一次寫入請求輸出流(對於第一個加蓋的PDF)後,再次寫入該文件會增加文件大小,但是當PDF打開時,我只能看到第二頁。彷彿應用程序無法訪問第一頁或其他東西。很奇怪。 – user470714

+0

很高興你找到答案。你描述的問題我還沒有遇到過使用PDFCopy,看來你的答案使用它。 – Jes

回答

2

所以,這裏是我終於能想出答案:

//Open an input stream to the PDF template 
InputStream is = getInputStreamToEachFile(); 


//Declare a document object, as well as a PdfCopy for 
//copying in each PdfFile we open in memory and edit. 
Document doc = new Document(); 
PdfCopy copy = new PdfCopy(doc, outputStreamToBrowser); 


//Be sure to open the document or it will throw an exception! 
doc.open(); 


//Since the PdfStamper class wants to output everything to an 
//output stream you can declare a ByteArrayOutputStream object 
//and direct it there, since we need to tack on more PDFs and 
//can't just output to the response's output stream directly. 
ByteArrayOutputStream byteStream = new ByteArrayOutputStream(); 
PdfStamper stamper = new PdfStamper(new PdfReader(is), byteStream); 


//Pseduocode - set form fields - just check out 
//the documentation for AcroFields in the API 
//this part is easy. 
... 


//if form has custom graphics declare a PdfContentByte array 
//the 1 argument in the getUnderContent refers to the page number 

PdfContentByte cb = stamper.getUnderContent(1); 

//pseduocode - do custom graphics. This can be a lot of different things, 
//so check the documentation 
... 


//Wrap things up - set the dyanamic form fields to read only 
//and call the stamper's close function to close the streams 
stamper.setFormFlatterning(true); 
stamper.close() 


//Finally, declare a new PdfReader, reading the stamper's byte array stream 
//which was declared in memory. 
PdfReader outReader = new PdfReader(byteStream.toByteArray()); 

//Use this function call to add each page that you need. Repeat this process 
//for as many PDFs as are being stitched together. 
copy.addPage(copy.getImportedPage(outReader,1)); 

//Finally, tell the browser you are done generating the file, and output it. 
//If there are a lot of pages being generated this way, I guess you could use the flush 
//function instead, and then call close when they are all done. 
copy.close(); 

要感謝這個教程中,我對我自己的最終發現:

http://itextpdf.com/examples/iia.php?id=127