org.apache.pdfbox.pdmodel.font.PDFont Java Examples

The following examples show how to use org.apache.pdfbox.pdmodel.font.PDFont. 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: JoinPages.java    From testarea-pdfbox2 with Apache License 2.0 7 votes vote down vote up
/**
 * @see #testJoinSmallAndBig()
 */
PDDocument prepareSmallPdf() throws IOException {
    PDDocument document = new PDDocument();
    PDPage page = new PDPage(new PDRectangle(72, 72));
    document.addPage(page);
    PDPageContentStream contentStream = new PDPageContentStream(document, page);
    contentStream.setNonStrokingColor(Color.YELLOW);
    contentStream.addRect(0, 0, 72, 72);
    contentStream.fill();
    contentStream.setNonStrokingColor(Color.BLACK);
    PDFont font = PDType1Font.HELVETICA;
    contentStream.beginText();
    contentStream.setFont(font, 18);
    contentStream.newLineAtOffset(2, 54);
    contentStream.showText("small");
    contentStream.newLineAtOffset(0, -48);
    contentStream.showText("page");
    contentStream.endText();
    contentStream.close();
    return document;
}
 
Example #3
Source File: PDDocument.java    From gcs with Mozilla Public License 2.0 6 votes vote down vote up
/**
 * This will save the document to an output stream.
 *
 * @param output The stream to write to. It will be closed when done. It is recommended to wrap
 * it in a {@link java.io.BufferedOutputStream}, unless it is already buffered.
 *
 * @throws IOException if the output could not be written
 */
public void save(OutputStream output) throws IOException
{
    if (document.isClosed())
    {
        throw new IOException("Cannot save a document which has been closed");
    }

    // subset designated fonts
    for (PDFont font : fontsToSubset)
    {
        font.subset();
    }
    fontsToSubset.clear();
    
    // save PDF
    COSWriter writer = new COSWriter(output);
    try
    {
        writer.write(this);
    }
    finally
    {
        writer.close();
    }
}
 
Example #4
Source File: FontTable.java    From Pdf2Dom with GNU Lesser General Public License v3.0 6 votes vote down vote up
public void addEntry(PDFont font)
{
    FontTable.Entry entry = get(font);

    if (entry == null)
    {
        String fontName = font.getName();
        String family = findFontFamily(fontName);

        String usedName = nextUsedName(family);
        FontTable.Entry newEntry = new FontTable.Entry(font.getName(), usedName, font);

        if (newEntry.isEntryValid())
            add(newEntry);
    }
}
 
Example #5
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 #6
Source File: PDFCreator.java    From Knowage-Server with GNU Affero General Public License v3.0 6 votes vote down vote up
private static void writeText(PDPageContentStream contentStream, Color color, PDFont font, float fontSize, boolean rotate, float x, float y, String... text)
		throws IOException {
	contentStream.beginText();
	// set font and font size
	contentStream.setFont(font, fontSize);
	// set text color
	contentStream.setNonStrokingColor(color.getRed(), color.getGreen(), color.getBlue());
	if (rotate) {
		// rotate the text according to the page rotation
		contentStream.setTextMatrix(Matrix.getRotateInstance(Math.PI / 2, x, y));
	} else {
		contentStream.setTextMatrix(Matrix.getTranslateInstance(x, y));
	}
	if (text.length > 1) {
		contentStream.setLeading(25f);

	}
	for (String line : text) {
		contentStream.showText(line);
		contentStream.newLine();
	}
	contentStream.endText();
}
 
Example #7
Source File: DefaultResourceCache.java    From gcs with Mozilla Public License 2.0 6 votes vote down vote up
@Override
public PDFont getFont(COSObject indirect) throws IOException
{
    SoftReference<PDFont> font = fonts.get(indirect);
    if (font != null)
    {
        return font.get();
    }
    return null;
}
 
Example #8
Source File: JoinPages.java    From testarea-pdfbox2 with Apache License 2.0 6 votes vote down vote up
/**
 * @see #testJoinSmallAndBig()
 */
PDDocument prepareBiggerPdf() throws IOException {
    PDDocument document = new PDDocument();
    PDPage page = new PDPage(PDRectangle.A5);
    document.addPage(page);
    PDPageContentStream contentStream = new PDPageContentStream(document, page);
    contentStream.setNonStrokingColor(Color.GREEN);
    contentStream.addRect(0, 0, PDRectangle.A5.getWidth(), PDRectangle.A5.getHeight());
    contentStream.fill();
    contentStream.setNonStrokingColor(Color.BLACK);
    PDFont font = PDType1Font.HELVETICA;
    contentStream.beginText();
    contentStream.setFont(font, 18);
    contentStream.newLineAtOffset(2, PDRectangle.A5.getHeight() - 24);
    contentStream.showText("This is the Bigger page");
    contentStream.newLineAtOffset(0, -48);
    contentStream.showText("BIGGER!");
    contentStream.endText();
    contentStream.close();
    return document;
}
 
Example #9
Source File: TextStampRecognizer.java    From pdf-unstamper with GNU General Public License v3.0 5 votes vote down vote up
static boolean recognize(@NotNull String[] keywords,
                         @NotNull byte[] inputText,
                         @NotNull Set<PDFont> pdFonts,
                         @NotNull boolean useStrict) {
    return recognizePlain(keywords, inputText, useStrict) ||
            recognizeWithFont(keywords, inputText, pdFonts, useStrict);
}
 
Example #10
Source File: HelloWorldFont.java    From blog-codes with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws IOException {
	// Create a document and add a page to it
	PDDocument document = new PDDocument();
	PDPage page = new PDPage();
	document.addPage( page );

	// Create a new font object selecting one of the PDF base fonts
	PDFont font = PDType1Font.HELVETICA_BOLD;

	// Start a new content stream which will "hold" the to be created content
	PDPageContentStream contentStream = new PDPageContentStream(document, page);

	// Define a text content stream using the selected font, moving the cursor and drawing the text "Hello World"
	contentStream.beginText();
	contentStream.setFont( font, 12 );
	contentStream.newLineAtOffset( 100, 700 );
	contentStream.showText( "Hello World" );
	contentStream.endText();

	// Make sure that the content stream is closed:
	contentStream.close();

	// Save the results and ensure that the document is properly closed:
	document.save( "/home/lili/data/Hello World.pdf");
	document.close();

}
 
Example #11
Source File: PDAbstractContentStream.java    From gcs with Mozilla Public License 2.0 5 votes vote down vote up
/**
 * Set the font and font size to draw text with.
 *
 * @param font The font to use.
 * @param fontSize The font size to draw the text.
 * @throws IOException If there is an error writing the font information.
 */
public void setFont(PDFont font, float fontSize) throws IOException
{
    if (fontStack.isEmpty())
    {
        fontStack.add(font);
    }
    else
    {
        fontStack.pop();
        fontStack.push(font);
    }

    // keep track of fonts which are configured for subsetting
    if (font.willBeSubset())
    {
        if (document != null)
        {
            document.getFontsToSubset().add(font);
        }
        else
        {
            LOG.warn("attempting to use subset font " + font.getName() + " without proper context");
        }
    }

    writeOperand(resources.add(font));
    writeOperand(fontSize);
    writeOperator(OperatorName.SET_FONT_AND_SIZE);
}
 
Example #12
Source File: PageDrawer.java    From gcs with Mozilla Public License 2.0 5 votes vote down vote up
@Override
protected void showFontGlyph(Matrix textRenderingMatrix, PDFont font, int code, String unicode,
                             Vector displacement) throws IOException
{
    AffineTransform at = textRenderingMatrix.createAffineTransform();
    at.concatenate(font.getFontMatrix().createAffineTransform());

    Glyph2D glyph2D = createGlyph2D(font);
    drawGlyph2D(glyph2D, font, code, displacement, at);
}
 
Example #13
Source File: TitleBlockWriter.java    From eplmp with Eclipse Public License 1.0 5 votes vote down vote up
private boolean isCharacterEncodeable(char character, PDFont font) throws IOException {
    try {
        font.encode(Character.toString(character));
        return true;
    } catch (IllegalArgumentException iae) {
        LOGGER.log(Level.WARNING, "Character cannot be encoded", iae);
        return false;
    }
}
 
Example #14
Source File: TextFragment.java    From pdfxtk with Apache License 2.0 5 votes vote down vote up
public TextFragment(
      float x1,
      float x2,
      float y1,
      float y2,
      String text,
      PDFont font,
      float fontSize
      )
  {
super(x1, x2, y1, y2, text, findFontName(font), fontSize);
  }
 
Example #15
Source File: TestType0ToOpenTypeConverter.java    From FontVerter with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Test
public void given_type0_withCFF_convertToOtf_thenCmapSameNumberOfEntries() throws Exception {
    PDFont rawType0Font = extractFont(doc, "ZGBKQN+HelveticaNeue-Bold-Identity-H");
    OpenTypeFont font = (OpenTypeFont) PdfFontExtractor.convertType0FontToOpenType((PDType0Font) rawType0Font);

    Assert.assertEquals(41, font.getCmap().getGlyphMappings().size());
}
 
Example #16
Source File: BoundingBoxFinder.java    From testarea-pdfbox2 with Apache License 2.0 5 votes vote down vote up
@Override
protected void showGlyph(Matrix textRenderingMatrix, PDFont font, int code, Vector displacement)
        throws IOException {
    super.showGlyph(textRenderingMatrix, font, code, displacement);
    Shape shape = calculateGlyphBounds(textRenderingMatrix, font, code);
    if (shape != null) {
        Rectangle2D rect = shape.getBounds2D();
        add(rect);
    }
}
 
Example #17
Source File: PDFUtil.java    From ctsms with GNU Lesser General Public License v2.1 5 votes vote down vote up
public static PDFont loadFont(String fontFileName, PDDocument doc, PDFont defaultBaseFont) throws IOException {
	PDFont font = null;
	if (fontFileName != null && fontFileName.length() > 0) {
		font = PDType1Font.getStandardFont(fontFileName);
		if (font == null) {
			font = PDTrueTypeFont.loadTTF(doc, fontFileName);
			// http://stackoverflow.com/questions/5570225/workaround-for-pdfbox-pdtruetypefont-bad-widths-bug
		}
	} else {
		font = defaultBaseFont;
	}
	return font;
}
 
Example #18
Source File: VerticalTextCellDrawer.java    From easytable with MIT License 5 votes vote down vote up
/**
 * Does not yet support the settings of alignments.
 *
 * @param drawingContext
 */
@Override
@SneakyThrows
public void drawContent(DrawingContext drawingContext) {
    final float startX = drawingContext.getStartingPoint().x;
    final float startY = drawingContext.getStartingPoint().y;

    final PDFont currentFont = cell.getFont();
    final int currentFontSize = cell.getFontSize();
    final Color currentTextColor = cell.getTextColor();

    float yOffset = startY + cell.getPaddingBottom();

    float height = cell.getRow().getHeight();

    if (cell.getRowSpan() > 1) {
        float rowSpanAdaption = cell.calculateHeightForRowSpan() - cell.getRow().getHeight();
        yOffset -= rowSpanAdaption;

        height = cell.calculateHeightForRowSpan();
    }

    final List<String> lines = cell.isWordBreak()
            ? PdfUtil.getOptimalTextBreakLines(cell.getText(), currentFont, currentFontSize, (height - cell.getVerticalPadding()))
            : Collections.singletonList(cell.getText());

    float xOffset = startX + cell.getPaddingLeft() - PdfUtil.getFontHeight(currentFont, currentFontSize);
    for (int i = 0; i < lines.size(); i++) {
        final String line = lines.get(i);

        xOffset += (
                PdfUtil.getFontHeight(currentFont, currentFontSize) // font height
                        + (i > 0 ? PdfUtil.getFontHeight(currentFont, currentFontSize) * cell.getLineSpacing() : 0f) // line spacing
        );

        drawText(line, currentFont, currentFontSize, currentTextColor, xOffset, yOffset, drawingContext.getContentStream());
    }
}
 
Example #19
Source File: PDFPage.java    From Open-Lowcode with Eclipse Public License 2.0 5 votes vote down vote up
static PDFont getFont(int texttype) {
	if (texttype == TEXTTYPE_PLAIN)
		return datafont;
	if (texttype == TEXTTYPE_PLAIN_BOLD)
		return datafontbold;
	if (texttype == TEXTTYPE_PLAIN_ITALIC)
		return datafontitalic;
	if (texttype == TEXTTYPE_PLAIN_BOLD_ITALIC)
		return datafontitalicbold;

	if (texttype == TEXTTYPE_LABEL)
		return labelfont;
	if (texttype == TEXTTYPE_SECTION_HEADER)
		return sectionheaderfont;
	if (texttype == TEXTTYPE_PARAGRAPH_HEADER)
		return paragraphheaderfont;

	if (texttype == TEXTTYPE_TITLE)
		return titlefont;
	if (texttype == TEXTTYPE_BULLET_L1)
		return datafont;
	if (texttype == TEXTTYPE_BULLET_L2)
		return datafont;
	if (texttype == TEXTTYPE_BULLET_L3)
		return datafont;

	throw new RuntimeException("Text type not supported " + texttype);
}
 
Example #20
Source File: PDPageContentStream.java    From gcs with Mozilla Public License 2.0 5 votes vote down vote up
/**
 * Outputs a string using the correct encoding and subsetting as required.
 *
 * @param text The Unicode text to show.
 * 
 * @throws IOException If an io exception occurs.
 */
protected void showTextInternal(String text) throws IOException
{
    if (!inTextMode)
    {
        throw new IllegalStateException("Must call beginText() before showText()");
    }

    if (fontStack.isEmpty())
    {
        throw new IllegalStateException("Must call setFont() before showText()");
    }

    PDFont font = fontStack.peek();

    // Unicode code points to keep when subsetting
    if (font.willBeSubset())
    {
        int offset = 0;
        while (offset < text.length())
        {
            int codePoint = text.codePointAt(offset);
            font.addToSubset(codePoint);
            offset += Character.charCount(codePoint);
        }
    }

    COSWriter.writeString(font.encode(text), output);
}
 
Example #21
Source File: TitleBlockWriter.java    From eplmp with Eclipse Public License 1.0 5 votes vote down vote up
private String getTextWithSymbol(String text, PDFont font) throws IOException {

        StringBuilder nonSymbolBuffer = new StringBuilder();
        for (char character : text.toCharArray()) {
            if (isCharacterEncodeable(character, font)) {
                nonSymbolBuffer.append(character);
            } else {
                nonSymbolBuffer.append(SUBSTITUTION_CHAR);
            }
        }
        return nonSymbolBuffer.toString();
    }
 
Example #22
Source File: TestType0ToOpenTypeConverter.java    From FontVerter with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Test
public void given_type0_withTTF_withNoNameTable_whenConverted_thenHasNamesSet() throws IOException {
    PDFont rawType0Font = extractFont(doc, "UMAVUG+Garuda-Identity-H");

    FVFont font = PdfFontExtractor.convertType0FontToOpenType((PDType0Font) rawType0Font);
    font.normalize();
    OpenTypeFont otfFont = ((OpenTypeFont) font);

    Assert.assertEquals("UMAVUG+Garuda-Identity-H", otfFont.getNameTable().getName(RecordType.FULL_FONT_NAME));
    Assert.assertEquals("Garuda", otfFont.getNameTable().getName(RecordType.FONT_FAMILY));
    Assert.assertEquals("Normal", otfFont.getNameTable().getName(RecordType.FONT_SUB_FAMILY));
}
 
Example #23
Source File: PDDefaultAppearanceString.java    From gcs with Mozilla Public License 2.0 4 votes vote down vote up
/**
 * Returns the font.
 */
PDFont getFont() throws IOException
{
    return font;
}
 
Example #24
Source File: PageDrawer.java    From gcs with Mozilla Public License 2.0 4 votes vote down vote up
/**
 * Render the font using the Glyph2D interface.
 * 
 * @param glyph2D the Glyph2D implementation provided a GeneralPath for each glyph
 * @param font the font
 * @param code character code
 * @param displacement the glyph's displacement (advance)
 * @param at the transformation
 * @throws IOException if something went wrong
 */
private void drawGlyph2D(Glyph2D glyph2D, PDFont font, int code, Vector displacement,
                         AffineTransform at) throws IOException
{
    PDGraphicsState state = getGraphicsState();
    RenderingMode renderingMode = state.getTextState().getRenderingMode();

    GeneralPath path = glyph2D.getPathForCharacterCode(code);
    if (path != null)
    {
        // Stretch non-embedded glyph if it does not match the height/width contained in the PDF.
        // Vertical fonts have zero X displacement, so the following code scales to 0 if we don't skip it.
        // TODO: How should vertical fonts be handled?
        if (!font.isEmbedded() && !font.isVertical() && !font.isStandard14() && font.hasExplicitWidth(code))
        {
            float fontWidth = font.getWidthFromFont(code);
            if (fontWidth > 0 && // ignore spaces
                    Math.abs(fontWidth - displacement.getX() * 1000) > 0.0001)
            {
                float pdfWidth = displacement.getX() * 1000;
                at.scale(pdfWidth / fontWidth, 1);
            }
        }

        // render glyph
        Shape glyph = at.createTransformedShape(path);

        if (renderingMode.isFill())
        {
            graphics.setComposite(state.getNonStrokingJavaComposite());
            graphics.setPaint(getNonStrokingPaint());
            setClip();
            if (isContentRendered())
            {
                graphics.fill(glyph);
            }
        }

        if (renderingMode.isStroke())
        {
            graphics.setComposite(state.getStrokingJavaComposite());
            graphics.setPaint(getStrokingPaint());
            graphics.setStroke(getStroke());
            setClip();
            if (isContentRendered())
            {
                graphics.draw(glyph);
            }
        }

        if (renderingMode.isClip())
        {
            textClippings.add(glyph);
        }
    }
}
 
Example #25
Source File: EcrfPDFPainter.java    From ctsms with GNU Lesser General Public License v2.1 4 votes vote down vote up
public PDFont getFontD() {
	return fontD;
}
 
Example #26
Source File: EcrfPDFPainter.java    From ctsms with GNU Lesser General Public License v2.1 4 votes vote down vote up
public PDFont getFontC() {
	return fontC;
}
 
Example #27
Source File: EcrfPDFBlockCursor.java    From ctsms with GNU Lesser General Public License v2.1 4 votes vote down vote up
@Override
public PDFont getFontB() {
	return painter.getFontB();
}
 
Example #28
Source File: InquiriesPDFPainter.java    From ctsms with GNU Lesser General Public License v2.1 4 votes vote down vote up
public PDFont getFontB() {
	return fontB;
}
 
Example #29
Source File: EcrfPDFBlockCursor.java    From ctsms with GNU Lesser General Public License v2.1 4 votes vote down vote up
@Override
public PDFont getFontC() {
	return painter.getFontC();
}
 
Example #30
Source File: InquiriesPDFBlockCursor.java    From ctsms with GNU Lesser General Public License v2.1 4 votes vote down vote up
@Override
public PDFont getFontD() {
	return painter.getFontD();
}