iText内存管理 - PdfReader / Watermarking加载太多

时间:2011-08-16 15:07:41

标签: java memory-management itext watermark

我正在为文档加水印,我不想将它们完全加载到内存中,因为它们可能非常大。我发现RandomAccessFileOrArray可以缓冲读数,但是它很好但是仍然加载得太多了。

也就是说,在我加载一个5 Mb的PDF文件后,使用的内存增加了23Mb!当我开始加水印时,它再跳跃27Mb!之后使用的记忆逐渐增加,但并非可怕。

这种行为有理由吗?你知道一种定义PdfReader或RandomAccessFileOrArray或其他东西的缓冲区大小的方法吗?

感谢您的意见。


方法printMem通过显示free - used - total。

来显示内存的状态

这是我的代码

printMem("Before load");
    PdfReader reader = null;
    try {
        reader = new PdfReader(new RandomAccessFileOrArray(new FileInputStream("C:/TEMP/zip/100258.pdf")),null);
        printMem("After load");
        FileOutputStream out = new FileOutputStream(f);
        PdfStamper stamp = new PdfStamper(reader, out);

        int numPages = reader.getNumberOfPages();
        int page=1;
        BaseFont baseFont = 
            BaseFont.createFont(BaseFont.HELVETICA_BOLDOBLIQUE,
                BaseFont.WINANSI, BaseFont.EMBEDDED);
        float width;
        float height;

        while (page <= numPages) {
            printMem("Page " + page);
            PdfContentByte cb = stamp.getOverContent(page);
            height = reader.getPageSizeWithRotation(page).getHeight() / 2;
            width = reader.getPageSizeWithRotation(page).getWidth() / 2;

            cb.saveState();
            cb.setColorFill(MEDIUM_GRAY);

            // Primary Text
            cb.beginText();
            cb.setFontAndSize(baseFont, PRIMARY_FONT_SIZE);
            cb.showTextAligned(Element.ALIGN_CENTER, "WatermarkText", width,
                    height, TEXT_TILT_ANGLE);
            cb.endText();

            cb.restoreState();
            page++;
        }
        stamp.close();
    } catch(Throwable e) {
        reader = null;
        System.gc();
    }

这是部分输出:

Before load | 1566248160 6615840 1572864000
After load | 1542392472 30471528 1572864000
Page 1 | 1515096880 57767120 1572864000
Page 2 | 1515095992 57768008 1572864000
Page 47 | 1512998840 59865160 1572864000
Page 48 | 1512998840 59865160 1572864000

1 个答案:

答案 0 :(得分:3)

如果使用包含文件路径的String构造RandomAccessFileOrArray,则仅部分读取文档(例如,新的RandomAccessFileOrArray(“/ path / to / pdf”);)。使用InputStream或URL,整个文档将复制到内部字节数组。