PDFBox添加图像时内存不足

时间:2012-06-15 13:59:20

标签: image memory pdfbox

我正在使用PDFBox从我的webapp中提取数据并将其放入PDF中。我有一个方法,在每个PDF页面上绘制标题。但是,当我向每个页面添加图像时,文档内存不足。我想知道是否有人对解决方案有任何想法?这是我的drawHeader方法:

public static void drawHeader(PDDocument doc,PDPage page,PDPageContentStream contentStream,int [] columnWidths,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);
    }
}

2 个答案:

答案 0 :(得分: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);
....

答案 1 :(得分:0)

我正在尝试评论蒂姆·霍恩的答案,但还没有足够的代表......

我发现“内存不足”错误的另一个问题是图像是否很大,或者您是否试图将其从页面中删除。

从您的坐标开始为100, 100,然后从那里开始工作。

e.g。 contentStream.drawImage(img, 100, 100);

干杯,

萨姆