检测文本字段溢出

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

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

此代码重新创建外观流以确保它存在,以便有一个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("\\/([Az]+) (\\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