2012-06-15 150 views
2

我正在使用PDFBox從我的webapp中提取數據並將其放入PDF中。我有一個方法可以在每個PDF頁面上繪製標題。但是,當我將圖像添加到每個頁面時,文檔耗盡內存。我想知道是否有人對解決方案有任何想法?這裏是我的drawHeader方法:PDFBox添加圖像時內存不足

公共靜態無效drawHeader(PDDocument DOC,PDPage頁,PDPageContentStream contentStream,INT []列寬,INT PAGENUMBER)拋出IOException異常{

contentStream.beginText(); 
    PDFont font = PDType1Font.HELVETICA_BOLD; 
    contentStream.setFont(font, 24); 
    contentStream.moveTextPositionByAmount(50, 750); 
    contentStream.drawString("Producer License Report"); 
    contentStream.endText(); 

    contentStream.beginText(); 
    contentStream.moveTextPositionByAmount(550, 750); 

    contentStream.setFont(PDType1Font.HELVETICA_BOLD, 8); 
    contentStream.drawString("Page " + pageNumber); 
    contentStream.endText(); 

    contentStream.drawLine(50, 740, 340, 740); 
    contentStream.drawLine(16, 680, 595, 680); 

    List<String> headerList = new LinkedList<String>(); 
    headerList.add("NPN"); 
    headerList.add("First Name"); 
    headerList.add("Last Name"); 
    headerList.add("Suffix"); 
    headerList.add("License State"); 
    headerList.add("Resident State"); 
    headerList.add("License Number"); 

    contentStream.setFont(PDType1Font.HELVETICA_BOLD, 9); 
    float textx = 15; 
    float texty = 685; 

    InputStream in = new FileInputStream(new File("logo.jpg")); 
    PDJpeg img = new PDJpeg(doc, in); 
    contentStream.drawImage(img, 375, 720); 


    for (int i = 0; i < headerList.size(); i++) { 
     String text = headerList.get(i); 
     contentStream.beginText(); 
     contentStream.moveTextPositionByAmount(textx, texty); 
     contentStream.drawString(text); 
     contentStream.endText(); 
     textx += (columnWidths[i] * 6.5); 
    } 
} 
+0

忘了提,圖像只有6 KB有同樣的問題 – FrenchMyToast

+0

IM,我懷疑它可能是圖像不適合在PDF頁面由於其大小 –

回答

4

我找到了解決辦法!您必須在打開contentStream之前創建Image-Object。

例子:

/* Step 1: Prepare the document. 
       */ 
      doc = new PDDocument(); 
      PDPage page = new PDPage(); 
      doc.addPage(page); 

      /* Step 2: Prepare the image 
       * PDJpeg is the class you use when dealing with jpg images. 
       * You will need to mention the jpg file and the document to which it is to be added 
       * Note that if you complete these steps after the creating the content stream the PDF 
       * file created will show "Out of memory" error. 
       */ 

      PDXObjectImage image = null; 
      image = new PDJpeg(doc, new FileInputStream("image.jpg")); 
      PDPageContentStream contentStream = new PDPageContentStream(doc, 
        page); 
.... 
+4

是不是缺少「drawImage」步驟?我有同樣的「內存不足」問題,您的解決方案不適合我。令人沮喪! – seinecle

0

我想評論通過蒂莫霍恩的答案,但沒有足夠的代表尚未...

另一個問題,我用「出來的發現內存「錯誤是如果圖像很大,或者您試圖將其從頁面上拖出。

從您的座標開始爲100, 100,然後從那裏開始工作。

例如contentStream.drawImage(img, 100, 100);

乾杯,

山姆