检测文本字段溢出 [英] Detecting text field overflow

查看:167
本文介绍了检测文本字段溢出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Assuming I have a PDF document with a text field with some font and size defined, is there a way to determine if some text will fit inside the field rectangle using PDFBox?

我正在尝试避免在字段中未完全显示文本的情况,因此,如果在给定字体和大小的情况下文本溢出,我想将字体大小更改为Auto(0).

I'm trying to avoid cases where text is not fully displayed inside the field, so in case the text overflows given the font and size, I would like to change the font size to Auto (0).

推荐答案

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

This code recreates the appearance stream to be sure that it exists so that there is a bbox (which can be a little bit smaller than the rectangle).

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

这篇关于检测文本字段溢出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆