COSNameからフォントを取得する方法は?私は何とかこのようなルックスを探していますpdfboxを使用する - COSNameからフォントを取得するには?
ソリューション:
COSDictionary dict = new COSDictionary();
dict.add(fontname, something); // fontname COSName from below code
PDFontFactory.createFont(dict);
あなたはより多くの背景が必要な場合は、私は以下の一部始終を追加しました:
私はPDFファイルでいくつかの文字列を置換してみてください。これは成功します(すべてのテキストが1つのトークンに格納されている限り)。フォーマットを維持するために、私はテキストを再センタリングするのが好きです。私が理解している限り、古い文字列と新しい文字列の幅を取得して、これを行うことができます。いくつかの簡単な計算を行い、新しい位置を設定します。
私はhttps://stackoverflow.com/a/36404377を交換するためのstackoverflow上のいくつかのインスピレーション(はい、それはいくつかの問題がありますが、私の単純なPDFファイルのために働く。そしてHow to center a text using PDFBoxを見つけました。残念ながら、この例では、フォントの定数を使用しています。
だから私が得る最初のリンクのコードを使用してオペレータのための取扱い「TJ」と「Tjの」の1。
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を要求します。これは私があきらめた点であり、あなたに助けを求める。