From f4238acccd5f60dadb13a119a176f5e72c65b47a Mon Sep 17 00:00:00 2001 From: Danny McPherson Date: Fri, 20 Dec 2019 15:12:28 -0600 Subject: [PATCH] Support auto size font for multiline PDTextField https://issues.apache.org/jira/browse/PDFBOX-3812 --- .../form/AppearanceGeneratorHelper.java | 35 ++++++++++++++++++- 1 file changed, 34 insertions(+), 1 deletion(-) diff --git a/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/interactive/form/AppearanceGeneratorHelper.java b/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/interactive/form/AppearanceGeneratorHelper.java index b88b8c7c035..f2589b26951 100644 --- a/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/interactive/form/AppearanceGeneratorHelper.java +++ b/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/interactive/form/AppearanceGeneratorHelper.java @@ -80,7 +80,12 @@ class AppearanceGeneratorHelper * The default font size used for multiline text */ private static final float DEFAULT_FONT_SIZE = 12; - + + /** + * The minimum font size used for multiline text auto sizing + */ + private static final float MINIMUM_FONT_SIZE = 4; + /** * The default padding applied by Acrobat to the fields bbox. */ @@ -785,6 +790,34 @@ private float calculateFontSize(PDFont font, PDRectangle contentRect) throws IOE { if (isMultiLine()) { + PlainText textContent = new PlainText(value); + if (textContent.getParagraphs() != null) + { + float fs = DEFAULT_FONT_SIZE; + while (fs > MINIMUM_FONT_SIZE) + { + // determine the number of lines needed for this font and contentRect + int numLines = 0; + for (PlainText.Paragraph paragraph : textContent.getParagraphs()) + { + numLines += paragraph.getLines(font, fs, contentRect.getWidth()).size(); + } + // calculate the height using the capHeight and leading for this font size + float fontScaleY = fs / FONTSCALE; + float fontCapAtSize = font.getFontDescriptor().getCapHeight() * fontScaleY; + float leading = font.getBoundingBox().getHeight() * fontScaleY; + float height = fontCapAtSize + ((numLines - 1) * leading); + + // if within bounds, return this font size + if (height <= contentRect.getHeight()) { + return fs; + } + + // otherwise, try again with a smaller font + fs -= 1; + } + } + // Acrobat defaults to 12 for multiline text with size 0 return DEFAULT_FONT_SIZE; }