简体   繁体   English

pdfbox:如何加载一次字体并多次使用?

[英]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.我试图在一个循环中创建很多 pdf 文件。

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... ?调用PDType0Font.load...会发生什么? Because the ttf file is large (10M), will it create ephemeral big objects of font 10000 times?因为 ttf 文件很大(10M),它会创建 10000 次font的临时大对象吗? 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?如果是这样,有没有办法让字体像 PDType1Font 一样嵌入,所以我可以只加载一次并在循环中多次使用它? I encountered a full GC problem here, and am trying to figure it out.我在这里遇到了一个完整的 GC 问题,并试图解决这个问题。

Create the font at the fontbox level:在字体框级别创建字体:

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

You can now reuse ttf in different PDDocument objects like this:您现在可以在不同的PDDocument对象中重用ttf ,如下所示:

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

When done with all documents, don't forget to close ttf .完成所有文档后,不要忘记关闭ttf

See also PDFontTest.testPDFBox3826() in the source code.另请参阅源代码中的PDFontTest.testPDFBox3826()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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