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

The following examples show how to use org.apache.pdfbox.pdmodel.font.PDFont. These examples are extracted from open source projects. 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 Project: testarea-pdfbox2   Author: mkl-public   File: JoinPages.java    License: 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 #2
Source Project: Knowage-Server   Author: KnowageLabs   File: PDFCreator.java    License: 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 #3
Source Project: testarea-pdfbox2   Author: mkl-public   File: JoinPages.java    License: 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 #4
Source Project: gcs   Author: richardwilkes   File: DefaultResourceCache.java    License: 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 #5
Source Project: Knowage-Server   Author: KnowageLabs   File: PDFCreator.java    License: 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 #6
Source Project: gcs   Author: richardwilkes   File: PlainText.java    License: 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 #7
Source Project: Pdf2Dom   Author: radkovo   File: FontTable.java    License: 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 #8
Source Project: gcs   Author: richardwilkes   File: PDDocument.java    License: 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 #9
Source Project: Open-Lowcode   Author: openlowcode   File: PDFPage.java    License: 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 #10
Source Project: FontVerter   Author: m-abboud   File: TestType0ToOpenTypeConverter.java    License: 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 #11
Source Project: blog-codes   Author: fancyerii   File: HelloWorldFont.java    License: 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 #12
Source Project: gcs   Author: richardwilkes   File: PDAbstractContentStream.java    License: 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 #13
Source Project: pdf-unstamper   Author: hwding   File: TextStampRecognizer.java    License: 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 #14
Source Project: easytable   Author: vandeseer   File: VerticalTextCellDrawer.java    License: 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 #15
Source Project: eplmp   Author: polarsys   File: TitleBlockWriter.java    License: 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 #16
Source Project: ctsms   Author: phoenixctms   File: PDFUtil.java    License: 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 #17
Source Project: eplmp   Author: polarsys   File: TitleBlockWriter.java    License: 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 #18
Source Project: FontVerter   Author: m-abboud   File: TestType0ToOpenTypeConverter.java    License: 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 #19
Source Project: gcs   Author: richardwilkes   File: PDPageContentStream.java    License: 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 #20
Source Project: testarea-pdfbox2   Author: mkl-public   File: BoundingBoxFinder.java    License: 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 #21
Source Project: pdfxtk   Author: tamirhassan   File: TextFragment.java    License: 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 #22
Source Project: gcs   Author: richardwilkes   File: PageDrawer.java    License: 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 #23
Source Project: ctsms   Author: phoenixctms   File: TrainingRecordPDFBlockCursor.java    License: GNU Lesser General Public License v2.1 4 votes vote down vote up
public PDFont getFontC() {
	return painter.getFontC();
}
 
Example #24
Source Project: Open-Lowcode   Author: openlowcode   File: PDFPage.java    License: Eclipse Public License 2.0 4 votes vote down vote up
/**
 * @param texttype a texttype as declared in this page
 * @return Font and font size in the adhoc inner class
 */
static FontAndSize getFontAndSize(int texttype) {
	PDFont font = getFont(texttype);
	float fontsize = getLineHeight(texttype);
	return new FontAndSize(font, fontsize);
}
 
Example #25
Source Project: gcs   Author: richardwilkes   File: PDFStreamEngine.java    License: Mozilla Public License 2.0 4 votes vote down vote up
/**
 * Called when a string of text with spacing adjustments is to be shown.
 *
 * @param array array of encoded text strings and adjustments
 * @throws IOException if there was an error showing the text
 */
public void showTextStrings(COSArray array) throws IOException
{
    PDTextState textState = getGraphicsState().getTextState();
    float fontSize = textState.getFontSize();
    float horizontalScaling = textState.getHorizontalScaling() / 100f;
    PDFont font = textState.getFont();
    boolean isVertical = false;
    if (font != null)
    {
        isVertical = font.isVertical();
    }

    for (COSBase obj : array)
    {
        if (obj instanceof COSNumber)
        {
            float tj = ((COSNumber)obj).floatValue();

            // calculate the combined displacements
            float tx;
            float ty;
            if (isVertical)
            {
                tx = 0;
                ty = -tj / 1000 * fontSize;
            }
            else
            {
                tx = -tj / 1000 * fontSize * horizontalScaling;
                ty = 0;
            }

            applyTextAdjustment(tx, ty);
        }
        else if(obj instanceof COSString)
        {
            byte[] string = ((COSString)obj).getBytes();
            showText(string);
        }
        else
        {
            throw new IOException("Unknown type in array for TJ operation:" + obj);
        }
    }
}
 
Example #26
Source Project: FontVerter   Author: m-abboud   File: TestType0ToOpenTypeConverter.java    License: GNU Lesser General Public License v3.0 4 votes vote down vote up
public static PDFont extractFont(PDDocument pdfFile, String name) throws IOException {
    PdfFontExtractor extractor = new PdfFontExtractor();
    List<PDFont> fonts = extractor.extractToPDFBoxFonts(pdfFile);
    return findFont(fonts, name);
}
 
Example #27
Source Project: website   Author: Paperight   File: PdfBoxPDFWatermarkWriter.java    License: GNU Affero General Public License v3.0 4 votes vote down vote up
public void setFont(PDFont font) {
	this.font = font;
}
 
Example #28
Source Project: ctsms   Author: phoenixctms   File: ReimbursementsPDFPainter.java    License: GNU Lesser General Public License v2.1 4 votes vote down vote up
public PDFont getFontE() {
	return fontE;
}
 
Example #29
Source Project: ctsms   Author: phoenixctms   File: ProbandListEntryTagsPDFPainter.java    License: GNU Lesser General Public License v2.1 4 votes vote down vote up
public PDFont getFontA() {
	return fontA;
}
 
Example #30
Source Project: synopsys-detect   Author: blackducksoftware   File: FontLoaderTest.java    License: Apache License 2.0 4 votes vote down vote up
@Test
public void loadsCJKBoldFont() {
    final DetectFontLoader fontLoader = new DetectFontLoader();
    final PDFont font = fontLoader.loadBoldFont(new PDDocument());
    Assertions.assertTrue(font.getName().contains("CJK"));
}