Skip to content

Commit

Permalink
PDFBOX-3812: initial support for auto font sizing in multiline text f…
Browse files Browse the repository at this point in the history
…ields as suggested by dannymcpherson in #78

git-svn-id: https://svn.apache.org/repos/asf/pdfbox/branches/2.0@1871927 13f79535-47bb-0310-9956-ffa450edef68
  • Loading branch information
Maruan Sahyoun committed Dec 23, 2019
1 parent 5daa9f7 commit 73cd4ee
Showing 1 changed file with 35 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,12 @@ class AppearanceGeneratorHelper
/**
* The default font size used for multiline text
*/
private static final float DEFAULT_FONT_SIZE = 12;
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.
Expand Down Expand Up @@ -787,6 +792,35 @@ 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;
}
Expand Down

0 comments on commit 73cd4ee

Please sign in to comment.