Java Code Examples for org.apache.pdfbox.pdmodel.font.PDFont#getStringWidth()

The following examples show how to use org.apache.pdfbox.pdmodel.font.PDFont#getStringWidth() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: PDFCreator.java    From Knowage-Server with GNU Affero General Public License v3.0 7 votes vote down vote up
private static void writeFrontpageDetails(PDDocument doc, PDFont font, float fontSize, FrontpageDetails details) throws IOException {
	String name = "Name: " + details.getName();
	String description = "Description: " + details.getDescription();
	String date = "Date: " + DEFAULT_DATE_FORMATTER.format(details.getDate());
	PDPage page = doc.getPage(0);
	PDRectangle pageSize = page.getMediaBox();
	float stringWidth = font.getStringWidth(StringUtilities.findLongest(name, description, date)) * fontSize / 1000f;
	float stringHeight = font.getFontDescriptor().getFontBoundingBox().getHeight() * fontSize / 1000f;

	int rotation = page.getRotation();
	boolean rotate = rotation == 90 || rotation == 270;
	float pageWidth = rotate ? pageSize.getHeight() : pageSize.getWidth();
	float pageHeight = rotate ? pageSize.getWidth() : pageSize.getHeight();
	float startX = rotate ? pageHeight / 3f : (pageWidth - stringWidth - stringHeight) / 3f;
	float startY = rotate ? (pageWidth - stringWidth) / 1f : pageWidth / 0.9f;

	// append the content to the existing stream
	try (PDPageContentStream contentStream = new PDPageContentStream(doc, page, AppendMode.APPEND, true, true)) {
		// draw rectangle
		writeText(contentStream, new Color(4, 44, 86), font, fontSize, rotate, startX, startY, name, description, date);
	}
}
 
Example 2
Source File: PDFPage.java    From Open-Lowcode with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * returns the maximum length of the lines provided
 * 
 * @param label true if shown as label, false if shown as normal text
 * @param lines the lines of text
 * @return the text width.
 * @throws IOException
 */
private static float getTextWidth(boolean label, String[] lines) throws IOException {
	PDFont font = datafont;
	float fontSize = LINE_HEIGHT_NORMAL_TEXT;
	if (label) {
		font = labelfont;
		fontSize = LINE_HEIGHT_NORMAL_TEXT * LABEL_SIZE_REDUCTION;
	}
	float maxwidth = 0f;
	for (int i = 0; i < lines.length; i++) {
		float thiswidth = font.getStringWidth(lines[i]) / (MM_TO_POINT * 1000) * fontSize;
		if (thiswidth > maxwidth)
			maxwidth = thiswidth;
	}
	return maxwidth;
}
 
Example 3
Source File: PlainText.java    From gcs with Mozilla Public License 2.0 6 votes vote down vote up
float calculateWidth(PDFont font, float fontSize) throws IOException
{
    final float scale = fontSize/FONTSCALE;
    float calculatedWidth = 0f;
    for (Word word : words)
    {
        calculatedWidth = calculatedWidth + 
                (Float) word.getAttributes().getIterator().getAttribute(TextAttribute.WIDTH);
        String text = word.getText();
        if (words.indexOf(word) == words.size() -1 && Character.isWhitespace(text.charAt(text.length()-1)))
        {
            float whitespaceWidth = font.getStringWidth(text.substring(text.length()-1)) * scale;
            calculatedWidth = calculatedWidth - whitespaceWidth;
        }
    }
    return calculatedWidth;
}
 
Example 4
Source File: PlainText.java    From gcs with Mozilla Public License 2.0 6 votes vote down vote up
float calculateWidth(PDFont font, float fontSize) throws IOException
{
    final float scale = fontSize/FONTSCALE;
    float calculatedWidth = 0f;
    for (Word word : words)
    {
        calculatedWidth = calculatedWidth + 
                (Float) word.getAttributes().getIterator().getAttribute(TextAttribute.WIDTH);
        String text = word.getText();
        if (words.indexOf(word) == words.size() -1 && Character.isWhitespace(text.charAt(text.length()-1)))
        {
            float whitespaceWidth = font.getStringWidth(text.substring(text.length()-1)) * scale;
            calculatedWidth = calculatedWidth - whitespaceWidth;
        }
    }
    return calculatedWidth;
}
 
Example 5
Source File: PDFPage.java    From Open-Lowcode with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * returns the maximum length of the lines provided with paragraphheaderfont
 * 
 * @param lines the lines of text
 * @return the lines of text
 * @throws IOException
 */
public float getParagraphHeaderTextWidth(String[] lines) throws IOException {
	PDFont font = PDFPage.sectionheaderfont;
	float fontSize = PDFPage.LINE_HEIGHT_SECTION_HEADER;
	float maxwidth = 0f;
	for (int i = 0; i < lines.length; i++) {
		float thiswidth = font.getStringWidth(lines[i]) / (MM_TO_POINT * 1000) * fontSize;
		if (thiswidth > maxwidth)
			maxwidth = thiswidth;
	}
	return maxwidth;
}
 
Example 6
Source File: PDFCreator.java    From Knowage-Server with GNU Affero General Public License v3.0 5 votes vote down vote up
private static void writePageNumbering(PDDocument doc, PDFont font, float fontSize, PageNumbering pageNumbering) throws IOException {
	int totalPages = doc.getNumberOfPages();
	int numberOfPages = pageNumbering.isLastIncluded() ? doc.getNumberOfPages() : doc.getNumberOfPages() - 1;
	for (int pageIndex = pageNumbering.isFirstIncluded() ? 0 : 1; pageIndex < numberOfPages; pageIndex++) {
		String footer = "Page " + (pageIndex + 1) + " of " + totalPages;
		PDPage page = doc.getPage(pageIndex);
		PDRectangle pageSize = page.getMediaBox();
		float stringWidth = font.getStringWidth(footer) * fontSize / 1000f;
		float stringHeight = font.getFontDescriptor().getFontBoundingBox().getHeight() * fontSize / 1000f;

		int rotation = page.getRotation();
		boolean rotate = rotation == 90 || rotation == 270;
		float pageWidth = rotate ? pageSize.getHeight() : pageSize.getWidth();
		float pageHeight = rotate ? pageSize.getWidth() : pageSize.getHeight();
		float startX = rotate ? pageHeight / 2f : (pageWidth - stringWidth - stringHeight) / 2f;
		float startY = rotate ? (pageWidth - stringWidth) : stringHeight;

		// append the content to the existing stream
		try (PDPageContentStream contentStream = new PDPageContentStream(doc, page, AppendMode.APPEND, true, true)) {

			// draw rectangle
			contentStream.setNonStrokingColor(255, 255, 255); // gray background
			// Draw a white filled rectangle
			drawRect(contentStream, Color.WHITE, new java.awt.Rectangle((int) startX, (int) startY - 3, (int) stringWidth + 2, (int) stringHeight), true);
			writeText(contentStream, new Color(4, 44, 86), font, fontSize, rotate, startX, startY, footer);
		}
	}
}
 
Example 7
Source File: PDFGenerator.java    From scim2-compliance-test-suite with Apache License 2.0 5 votes vote down vote up
/**
 * Method to separate lines of the PDF.
 * @param text
 * @param fontSize
 * @param pdfFont
 * @param width
 * @return
 * @throws IOException
 */
private static List<String> getLines(String text, float fontSize, PDFont pdfFont, float width)
        throws IOException {
    width = width - 150 ;
    java.util.List<String> lines = new ArrayList<String>();
    int lastSpace = -1;
    while (text.length() > 0) {
        int spaceIndex = text.indexOf(' ', lastSpace + 1);
        if (spaceIndex < 0)
            spaceIndex = text.length();
        String subString = text.substring(0, spaceIndex);
        float size = fontSize * pdfFont.getStringWidth(subString) / 1000;
        if (size > width) {
            float requiredSize = (width * 1000)/fontSize;
            int characterSize = getCharacterCount(requiredSize, subString, pdfFont);
            //if (lastSpace < 0)
            lastSpace = characterSize;
            subString = text.substring(0, lastSpace);
            lines.add(subString);
            text = text.substring(lastSpace).trim();
            lastSpace = -1;
        } else if (spaceIndex == text.length()) {
            lines.add(text);
            text = "";
        } else {
            lastSpace = spaceIndex;
        }
    }
    return lines;
}
 
Example 8
Source File: PDFGenerator.java    From scim2-compliance-test-suite with Apache License 2.0 5 votes vote down vote up
/**
 * This return the character count of a given text.
 * @param requiredSize
 * @param subString
 * @param pdfFont
 * @return
 * @throws IOException
 */
private static int getCharacterCount(float requiredSize, String subString, PDFont pdfFont) throws IOException {
    double factor = 0.95;
    String string  = subString;
    while (pdfFont.getStringWidth(string) > requiredSize) {
        string = string.substring(0, (int) Math.round(string.length()*factor));
    }
    return string.length();
}
 
Example 9
Source File: AppearanceGeneratorHelper.java    From gcs with Mozilla Public License 2.0 5 votes vote down vote up
/**
 * Generate the appearance for comb fields.
 * 
 * @param contents the content stream to write to
 * @param appearanceStream the appearance stream used
 * @param font the font to be used
 * @param fontSize the font size to be used
 * @throws IOException
 */
private void insertGeneratedCombAppearance(PDPageContentStream contents, PDAppearanceStream appearanceStream,
        PDFont font, float fontSize) throws IOException
{
    
    // TODO:    Currently the quadding is not taken into account
    //          so the comb is always filled from left to right.
    
    int maxLen = ((PDTextField) field).getMaxLen();
    int numChars = Math.min(value.length(), maxLen);
    
    PDRectangle paddingEdge = applyPadding(appearanceStream.getBBox(), 1);
    
    float combWidth = appearanceStream.getBBox().getWidth() / maxLen;
    float ascentAtFontSize = font.getFontDescriptor().getAscent() / FONTSCALE * fontSize;
    float baselineOffset = paddingEdge.getLowerLeftY() +  
            (appearanceStream.getBBox().getHeight() - ascentAtFontSize)/2;
    
    float prevCharWidth = 0f;
    
    float xOffset = combWidth / 2;

    for (int i = 0; i < numChars; i++) 
    {
        String combString = value.substring(i, i+1);
        float currCharWidth = font.getStringWidth(combString) / FONTSCALE * fontSize/2;
        
        xOffset = xOffset + prevCharWidth/2 - currCharWidth/2;
        
        contents.newLineAtOffset(xOffset, baselineOffset);
        contents.showText(combString);
        
        baselineOffset = 0;
        prevCharWidth = currCharWidth;
        xOffset = combWidth;
    }
}
 
Example 10
Source File: AppearanceGeneratorHelper.java    From gcs with Mozilla Public License 2.0 5 votes vote down vote up
/**
 * My "not so great" method for calculating the fontsize. It does not work superb, but it
 * handles ok.
 * 
 * @return the calculated font-size
 * @throws IOException If there is an error getting the font information.
 */
private float calculateFontSize(PDFont font, PDRectangle contentRect) throws IOException
{
    float fontSize = defaultAppearance.getFontSize();
    
    // zero is special, it means the text is auto-sized
    if (fontSize == 0)
    {
        if (isMultiLine())
        {
            // Acrobat defaults to 12 for multiline text with size 0
            return DEFAULT_FONT_SIZE;
        }
        else
        {
            float yScalingFactor = FONTSCALE * font.getFontMatrix().getScaleY();
            float xScalingFactor = FONTSCALE * font.getFontMatrix().getScaleX();
            
            // fit width
            float width = font.getStringWidth(value) * font.getFontMatrix().getScaleX();
            float widthBasedFontSize = contentRect.getWidth() / width * xScalingFactor;

            // fit height
            float height = (font.getFontDescriptor().getCapHeight() +
                           -font.getFontDescriptor().getDescent()) * font.getFontMatrix().getScaleY();
            if (height <= 0)
            {
                height = font.getBoundingBox().getHeight() * font.getFontMatrix().getScaleY();
            }

            float heightBasedFontSize = contentRect.getHeight() / height * yScalingFactor;
            
            return Math.min(heightBasedFontSize, widthBasedFontSize);
        }
    }
    return fontSize;
}
 
Example 11
Source File: AppearanceGeneratorHelper.java    From gcs with Mozilla Public License 2.0 4 votes vote down vote up
private void insertGeneratedListboxAppearance(PDPageContentStream contents, PDAppearanceStream appearanceStream,
        PDRectangle contentRect, PDFont font, float fontSize) throws IOException
{
    contents.setNonStrokingColor(0);
    
    int q = field.getQ();

    if (q == PDVariableText.QUADDING_CENTERED || q == PDVariableText.QUADDING_RIGHT)
    {
        float fieldWidth = appearanceStream.getBBox().getWidth();
        float stringWidth = (font.getStringWidth(value) / FONTSCALE) * fontSize;
        float adjustAmount = fieldWidth - stringWidth - 4;

        if (q == PDVariableText.QUADDING_CENTERED)
        {
            adjustAmount = adjustAmount / 2.0f;
        }

        contents.newLineAtOffset(adjustAmount, 0);
    }
    else if (q != PDVariableText.QUADDING_LEFT)
    {
        throw new IOException("Error: Unknown justification value:" + q);
    }

    List<String> options = ((PDListBox) field).getOptionsDisplayValues();
    int numOptions = options.size();

    float yTextPos = contentRect.getUpperRightY();

    int topIndex = ((PDListBox) field).getTopIndex();
    
    for (int i = topIndex; i < numOptions; i++)
    {
       
        if (i == topIndex)
        {
            yTextPos = yTextPos - font.getFontDescriptor().getAscent() / FONTSCALE * fontSize;
        }
        else
        {
            yTextPos = yTextPos - font.getBoundingBox().getHeight() / FONTSCALE * fontSize;
            contents.beginText();
        }

        contents.newLineAtOffset(contentRect.getLowerLeftX(), yTextPos);
        contents.showText(options.get(i));

        if (i != (numOptions - 1))
        {
            contents.endText();
        }
    }
}
 
Example 12
Source File: PlainText.java    From gcs with Mozilla Public License 2.0 4 votes vote down vote up
/**
 * Break the paragraph into individual lines.
 * 
 * @param font the font used for rendering the text.
 * @param fontSize the fontSize used for rendering the text.
 * @param width the width of the box holding the content.
 * @return the individual lines.
 * @throws IOException
 */
List<Line> getLines(PDFont font, float fontSize, float width) throws IOException
{
    BreakIterator iterator = BreakIterator.getLineInstance();
    iterator.setText(textContent);
    
    final float scale = fontSize/FONTSCALE;
    
    int start = iterator.first();
    int end = iterator.next();
    float lineWidth = 0;
    
    List<Line> textLines = new ArrayList<Line>();
    Line textLine = new Line();

    while (end != BreakIterator.DONE)
    {
        String word = textContent.substring(start,end);
        float wordWidth = font.getStringWidth(word) * scale;
        
        lineWidth = lineWidth + wordWidth;

        // check if the last word would fit without the whitespace ending it
        if (lineWidth >= width && Character.isWhitespace(word.charAt(word.length()-1)))
        {
            float whitespaceWidth = font.getStringWidth(word.substring(word.length()-1)) * scale;
            lineWidth = lineWidth - whitespaceWidth;
        }
        
        if (lineWidth >= width)
        {
            textLine.setWidth(textLine.calculateWidth(font, fontSize));
            textLines.add(textLine);
            textLine = new Line();
            lineWidth = font.getStringWidth(word) * scale;
        }
        
        AttributedString as = new AttributedString(word);
        as.addAttribute(TextAttribute.WIDTH, wordWidth);
        Word wordInstance = new Word(word);
        wordInstance.setAttributes(as);
        textLine.addWord(wordInstance);
        start = end;
        end = iterator.next();
    }
    textLine.setWidth(textLine.calculateWidth(font, fontSize));
    textLines.add(textLine);
    return textLines;
}
 
Example 13
Source File: PlainText.java    From gcs with Mozilla Public License 2.0 4 votes vote down vote up
/**
 * Break the paragraph into individual lines.
 * 
 * @param font the font used for rendering the text.
 * @param fontSize the fontSize used for rendering the text.
 * @param width the width of the box holding the content.
 * @return the individual lines.
 * @throws IOException
 */
List<Line> getLines(PDFont font, float fontSize, float width) throws IOException
{
    BreakIterator iterator = BreakIterator.getLineInstance();
    iterator.setText(textContent);
    
    final float scale = fontSize/FONTSCALE;
    
    int start = iterator.first();
    int end = iterator.next();
    float lineWidth = 0;
    
    List<Line> textLines = new ArrayList<Line>();
    Line textLine = new Line();

    while (end != BreakIterator.DONE)
    {
        String word = textContent.substring(start,end);
        float wordWidth = font.getStringWidth(word) * scale;
        
        lineWidth = lineWidth + wordWidth;

        // check if the last word would fit without the whitespace ending it
        if (lineWidth >= width && Character.isWhitespace(word.charAt(word.length()-1)))
        {
            float whitespaceWidth = font.getStringWidth(word.substring(word.length()-1)) * scale;
            lineWidth = lineWidth - whitespaceWidth;
        }
        
        if (lineWidth >= width)
        {
            textLine.setWidth(textLine.calculateWidth(font, fontSize));
            textLines.add(textLine);
            textLine = new Line();
            lineWidth = font.getStringWidth(word) * scale;
        }
        
        AttributedString as = new AttributedString(word);
        as.addAttribute(TextAttribute.WIDTH, wordWidth);
        Word wordInstance = new Word(word);
        wordInstance.setAttributes(as);
        textLine.addWord(wordInstance);
        start = end;
        end = iterator.next();
    }
    textLine.setWidth(textLine.calculateWidth(font, fontSize));
    textLines.add(textLine);
    return textLines;
}