使用pdfbox - 如何从COSName获取字体?
问题描述:
如何从COSName获取字体?使用pdfbox - 如何从COSName获取字体?
我正在寻找某种方式看起来像这样的解决方案:
COSDictionary dict = new COSDictionary();
dict.add(fontname, something); // fontname COSName from below code
PDFontFactory.createFont(dict);
如果你需要更多的背景,我在下面的原委:
我试图取代PDF中一些字符串。这会成功(只要所有文本都存储在一个令牌中)。为了保持我喜欢的格式来重新定位文本。据我所知,我可以通过获取旧字符串和新字符串的宽度来做到这一点,做一些简单的计算并设置新的位置。
我发现计算器一些启示更换https://stackoverflow.com/a/36404377(是的,它有一些问题,但是适合我的简单的PDF文件,并How to center a text using PDFBox。不幸的是这个例子中使用的字体不变。
因此,使用第一个链接的代码中,我得到对于运营商处理“TJ”,一个用于“TJ”。
PDFStreamParser parser = new PDFStreamParser(page);
parser.parse();
java.util.List<Object> tokens = parser.getTokens();
for (int j = 0; j < tokens.size(); j++)
{
Object next = tokens.get(j);
if (next instanceof Operator)
{
Operator op = (Operator) next;
// Tj and TJ are the two operators that display strings in a PDF
if (op.getName().equals("Tj"))
{
// Tj takes one operator and that is the string to display so lets
// update that operator
COSString previous = (COSString) tokens.get(j - 1);
String string = previous.getString();
String replaced = prh.getReplacement(string);
if (!string.equals(replaced))
{ // if changes are there, replace the content
previous.setValue(replaced.getBytes());
float xpos = getPosX(tokens, j);
//if (true) // center the text
if (6 * xpos > page.getMediaBox().getWidth()) // check if text starts right from 1/xth page width
{
float fontsize = getFontSize(tokens, j);
COSName fontname = getFontName(tokens, j);
// TODO
PDFont font = ?getFont?(fontname);
// TODO
float widthnew = getStringWidth(replaced, font, fontsize);
setPosX(tokens, j, page.getMediaBox().getWidth()/2F - (widthnew/2F));
}
replaceCount++;
}
}
考虑TODO标签之间的代码,我会从令牌列表中获得所需要的数值。(是这个代码是可怕的,但现在它让我专注于主要问题)
具有字符串,大小和字体我应该能够从示例代码中调用getWidth(..)方法。
不幸的是我遇到了麻烦,从COSName变量创建一个字体。
PDFont不提供按名称创建字体的方法。 PDFontFactory看起来不错,但请求一个COSDictionary。这是我放弃并向你请求帮助的一点。
答
名称与页面资源中的字体对象相关联。
假设你使用PDFBox的2.0.x版本和page
是PDPage
实例,可以解决使用名称fontname
:
PDFont font = page.getResources().getFont(fontname);
不过从评论到您引用问题的警告依然是:这种方法将只适用于非常简单的PDF文件,甚至可能会损坏其他文件。