使用pdfbox - 如何从COSName获取字体?

时间:2017-10-11 13:54:34

标签: pdfbox

如何从COSName获取字体?

我正在寻找的解决方案看起来像这样:

COSDictionary dict = new COSDictionary();
dict.add(fontname, something); // fontname COSName from below code
PDFontFactory.createFont(dict);

如果您需要更多背景资料,我在下面添加了整个故事:

我尝试在pdf中替换一些字符串。这成功(只要所有文本都存储在一个标记中)。为了保持格式,我喜欢重新定位文本。据我所知,我可以通过获取旧字符串和新字符串的宽度来做到这一点,做一些简单的计算并设置新的位置。

我在stackoverflow上找到了一些替换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。这是我放弃并向你请求帮助的一点。

2 个答案:

答案 0 :(得分:2)

名称与页面资源中的字体对象相关联。

假设您使用PDFBox 2.0.x且pagePDPage个实例,则可以使用以下命令解析名称fontname

PDFont font = page.getResources().getFont(fontname);

但是评论中对你提到的问题的警告仍然存在:这种方法仅适用于非常简单的PDF,甚至可能会损害其他PDF格式。

答案 1 :(得分:0)

try {
    //Loading an existing document 
    File file = new File("UKRSICH_Mo6i-Spikyer_z1560-FAV.pdf");
    PDDocument document = PDDocument.load(file);

    PDPage page = document.getPage(0);
    PDResources pageResources = page.getResources();

            System.out.println(pageResources.getFontNames() );

    for (COSName key : pageResources.getFontNames())
    {
    PDFont font = pageResources.getFont(key);

            System.out.println("Font: " + font.getName());
    }


    document.close();
}
相关问题