不幸的是,PDFBox开箱即用并没有提供一个类来呈现任意XObject的内容(类型3字体字符特效),至少据我所见。
但它确实提供了一个用于呈现完整PDF页面的类;因此,为了呈现给定的第3种字体字形,可以简单地创建仅包含该字形的页面并呈现该临时页面!
假设,例如,类型3字体被定义一个PDDocument document
的第一页上,并且具有名称F1
,它的所有字符的特效可以呈现这样的:
PDPage page = document.getPage(0);
PDResources pageResources = page.getResources();
COSName f1Name = COSName.getPDFName("F1");
PDType3Font fontF1 = (PDType3Font) pageResources.getFont(f1Name);
Map<String, Integer> f1NameToCode = fontF1.getEncoding().getNameToCodeMap();
COSDictionary charProcsDictionary = fontF1.getCharProcs();
for (COSName key : charProcsDictionary.keySet())
{
COSStream stream = (COSStream) charProcsDictionary.getDictionaryObject(key);
PDType3CharProc charProc = new PDType3CharProc(fontF1, stream);
PDRectangle bbox = charProc.getGlyphBBox();
if (bbox == null)
bbox = charProc.getBBox();
Integer code = f1NameToCode.get(key.getName());
if (code != null)
{
PDDocument charDocument = new PDDocument();
PDPage charPage = new PDPage(bbox);
charDocument.addPage(charPage);
charPage.setResources(pageResources);
PDPageContentStream charContentStream = new PDPageContentStream(charDocument, charPage);
charContentStream.beginText();
charContentStream.setFont(fontF1, bbox.getHeight());
charContentStream.getOutput().write(String.format("<%2X> Tj\n", code).getBytes());
charContentStream.endText();
charContentStream.close();
File result = new File(RESULT_FOLDER, String.format("4700198773-%s-%s.png", key.getName(), code));
PDFRenderer renderer = new PDFRenderer(charDocument);
BufferedImage image = renderer.renderImageWithDPI(0, 96);
ImageIO.write(image, "PNG", result);
charDocument.close();
}
}
(RenderType3Character.java测试方法testRender4700198773
)
考虑到在OP的代码textPosition
变量,从文本中提取他很可能尝试此离子使用案例。因此,他必须预先生成上述的位图,并简单地按名称查找它们,或者调整代码以匹配其用例中的可用信息(例如,他可能没有原始页面,只有字体对象;在这种情况下,他不能复制原始页面的资源,而是可以创建一个新的资源对象并将字体对象添加到它)。
不幸的是,OP没有提供样本PDF。因此,我用另一个堆栈溢出问题4700198773.pdf从extract text with custom font result non readble进行测试。 OP自己的文件显然可能存在问题。
来源
2017-02-06 12:22:51
mkl
我的回答有帮助吗?如果没有,请分享您的Type 3字体的样本PDF代表。正如我在回答中已经提到的,然后在@Tilman的评论中讨论过的,可能会有类型3字体变体的处理方式不同...... – mkl