Skip to content

Commit

Permalink
Support auto size font for multiline PDTextField
Browse files Browse the repository at this point in the history
  • Loading branch information
dannymcpherson committed Dec 20, 2019
1 parent 201efd0 commit f4238ac
Showing 1 changed file with 34 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -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.
*/
Expand Down Expand Up @@ -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;
}
Expand Down

0 comments on commit f4238ac

Please sign in to comment.