简体   繁体   中英

pdfbox: how to load a font once and use it many times?

I am trying to create a lot of pdf files in a loop.

for(int i=0; i<10000; ++i){
    PDDocument doc = PDDocument.load(inputstream);
    PDPage page = doc.getPage(0);
    PDPageContentStream content = new PDPageContentStream(doc, page, PDPageContentStream.AppendMode.APPEND, true, true);
    content.beginText();
    //what happens here?
    PDFont font = PDType0Font.load(doc, Thread.currentThread().getContextClassLoader().getResourceAsStream("font/simsun.ttf") );
    content.setFont(font, 10);
    //...
    doc.save(outstream);
    doc.close();
}

what does it happen by calling PDType0Font.load... ? Because the ttf file is large (10M), will it create ephemeral big objects of font 10000 times? If so, is there a way to make the font as embedded as PDType1Font, so I can just load it once and use it many times in the loop? I encountered a full GC problem here, and am trying to figure it out.

Create the font at the fontbox level:

TrueTypeFont ttf = new TTFParser().parse(...);

You can now reuse ttf in different PDDocument objects like this:

PDFont font = PDType0Font.load(doc, ttf, true);

When done with all documents, don't forget to close ttf .

See also PDFontTest.testPDFBox3826() in the source code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM