如何從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。這是我放棄並向你請求幫助的一點。