检测文本字段溢出

时间:2018-04-04 06:13:39

标签: java pdf pdfbox

假设我有一个PDF文档,其文本字段定义了一些字体和大小,是否可以使用PDFBox确定某些文本是否适合字段矩形?

我试图避免在字段内没有完全显示文本的情况,所以如果文本溢出给定字体和大小,我想将字体大小更改为Auto(0 )。

1 个答案:

答案 0 :(得分:1)

此代码重新创建外观流,以确保它存在,以便有一个bbox(可能比矩形小一点)。

public static void main(String[] args) throws IOException
{
    // file can be found at https://issues.apache.org/jira/browse/PDFBOX-142
    // https://issues.apache.org/jira/secure/attachment/12742551/Testformular1.pdf
    try (PDDocument doc = PDDocument.load(new File("Testformular1.pdf")))
    {
        PDAcroForm acroForm = doc.getDocumentCatalog().getAcroForm();
        PDTextField field = (PDTextField) acroForm.getField("Name");
        PDAnnotationWidget widget = field.getWidgets().get(0);
        // force generation of appearance stream
        field.setValue(field.getValue());
        PDRectangle rectangle = widget.getRectangle();
        PDAppearanceEntry ap = widget.getAppearance().getNormalAppearance();
        PDAppearanceStream appearanceStream = ap.getAppearanceStream();
        PDRectangle bbox = appearanceStream.getBBox();
        float fieldWidth = Math.min(bbox.getWidth(), rectangle.getWidth());
        String defaultAppearance = field.getDefaultAppearance();
        System.out.println(defaultAppearance);

        // Pattern must be improved, font may have numbers
        // /Helv 12 Tf 0 g
        final Pattern p = Pattern.compile("\\/([A-z]+) (\\d+).+");
        Matcher m = p.matcher(defaultAppearance);
        if (!m.find() || m.groupCount() != 2)
        {
            System.out.println("oh-oh");
            System.exit(-1);
        }
        String fontName = m.group(1);
        int fontSize = Integer.parseInt(m.group(2));
        PDResources resources = appearanceStream.getResources();
        if (resources == null)
        {
            resources = acroForm.getDefaultResources();
        }
        PDFont font = resources.getFont(COSName.getPDFName(fontName));
        float stringWidth = font.getStringWidth("Tilman Hausherr Tilman Hausherr");
        System.out.println("stringWidth: " + stringWidth * fontSize / 1000);
        System.out.println("field width: " + fieldWidth);
    }
}

输出结果为:

/Helv 12 Tf 0 g
stringWidth: 180.7207
field width: 169.29082