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

The following are top voted examples for showing how to use org.apache.pdfbox.pdmodel.font.PDFont. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: esup-ecandidat   File: CandidatureController.java   View source code 9 votes vote down vote up
/**
 * @param textHeader
 * @param font
 * @param PAGE_SIZE_A4
 * @param contentStream
 * @return ajoute un header a la piece
 * @throws IOException
 */
private Float addHeaderPJ(final String textHeader, final PDFont font, final PDRectangle PAGE_SIZE_A4,
		final PDPageContentStream contentStream) throws IOException {
	Float marginTop = 0f;
	// si font Ok, on ajoute le text
	if (font != null && ConstanteUtils.DOSSIER_ADD_HEADER_IMG) {

		// calcul de la largeur et hauteur du txt
		Float titleWidth = font.getStringWidth(textHeader) / 1000 * ConstanteUtils.DOSSIER_FONT_SIZE;
		Float titleHeight = font.getFontDescriptor().getFontBoundingBox().getHeight() / 1000
				* ConstanteUtils.DOSSIER_FONT_SIZE;

		// calcul de la marge du haut : hauteur du text + marge
		marginTop = titleHeight + ConstanteUtils.DOSSIER_MARGIN;

		// calcul de la position du text
		Float xText = (PAGE_SIZE_A4.getWidth() - 2 * ConstanteUtils.DOSSIER_MARGIN - titleWidth) / 2;
		Float yText = PAGE_SIZE_A4.getHeight() - marginTop;

		// ecriture du text
		contentStream.beginText();
		contentStream.setFont(PDType1Font.HELVETICA_BOLD, ConstanteUtils.DOSSIER_FONT_SIZE);
		contentStream.newLineAtOffset(xText, yText);
		contentStream.showText(textHeader);
		contentStream.endText();
	}
	return marginTop;
}
 
Example 2
Project: pdfbox-graphics2d   File: PdfBoxGraphics2DFontTextDrawer.java   View source code 9 votes vote down vote up
private void showTextOnStream(IFontTextDrawerEnv env, PDPageContentStream contentStream, Font attributeFont,
		PDFont font, boolean isStrikeThrough, boolean isUnderline, boolean isLigatures, String text)
		throws IOException {
	if (isStrikeThrough || isUnderline) {
		// noinspection unused
		float stringWidth = font.getStringWidth(text);
		// noinspection unused
		LineMetrics lineMetrics = attributeFont.getLineMetrics(text, env.getFontRenderContext());
		/*
		 * TODO: We can not draw that yet, we must do that later. While in textmode its
		 * not possible to draw lines...
		 */
	}
	// noinspection StatementWithEmptyBody
	if (isLigatures) {
		/*
		 * No idea how to map this ...
		 */
	}
	contentStream.showText(text);
}
 
Example 3
Project: git-rekt   File: BillPdfGenerator.java   View source code 8 votes vote down vote up
private void generateBillHeader(PDPage firstPage, PDPageContentStream contentStream)
        throws IOException {
    // Add header text
    PDFont currentFont;
    int currentFontSize;
    String headerLine1 = "Git Rekt Resort";
    String headerLine2 = "Customer Bill";
    contentStream.setLeading(10);
    currentFont = BOLD;
    currentFontSize = 14;
    contentStream.setFont(currentFont, currentFontSize);
    contentStream.beginText();
    float offsetX = getCenteredTextXPos(firstPage, headerLine1, currentFont, currentFontSize);
    contentStream.newLineAtOffset(offsetX, 750f);
    contentStream.showText(headerLine1);
    currentFont = PDType1Font.COURIER_BOLD;
    currentFontSize = 12;
    contentStream.setFont(currentFont, currentFontSize);
    float offsetX2 = getCenteredTextXPos(firstPage, headerLine2, currentFont, currentFontSize);
    contentStream.newLineAtOffset(-offsetX + offsetX2, -5f);
    contentStream.newLine();
    contentStream.showText(headerLine2);
    contentStream.endText();
}
 
Example 4
Project: git-rekt   File: BillPdfGenerator.java   View source code 7 votes vote down vote up
private float getCenteredTextXPos(PDPage page, String text, PDFont font, int fontSize)
        throws IOException {
    float textWidth = getStringWidth(text, font, fontSize);
    PDRectangle pageSize = page.getMediaBox();
    float pageCenterX = pageSize.getWidth() / 2F;
    float textX = pageCenterX - textWidth/2F;
    return textX;
}
 
Example 5
Project: pdf-unstamper   File: TextStampRecognizer.java   View source code 6 votes vote down vote up
private static boolean recognizeWithFont(
        @NotNull String[] keywords,
        @NotNull byte[] inputText,
        @NotNull Set<PDFont> pdFonts,
        @NotNull boolean useStrict) {
    String encodedInput = generateByteString(inputText);
    for (PDFont f : pdFonts) {
        if (f == null) continue;
        for (String k : keywords) {
            try {
                byte[] encodedKeywordBytes = f.encode(k);
                final String encodedKeyword = generateByteString(encodedKeywordBytes);
                if (checkDuplicate(encodedInput, encodedKeyword, useStrict)) return true;
            } catch (IOException | IllegalArgumentException ignored) {
            }
        }
    }
    return false;
}
 
Example 6
Project: pdfbox-graphics2d   File: PdfBoxGraphics2DFontTextDrawerDefaultFonts.java   View source code 6 votes vote down vote up
/**
 * Get a PDType1Font.TIMES-variant, which matches the given font
 * 
 * @param font
 *            Font to get the styles from
 * @return a PDFont Times variant which matches the style in the given Font
 *         object.
 */
public static PDFont chooseMatchingTimes(Font font) {
	if ((font.getStyle() & (Font.ITALIC | Font.BOLD)) == (Font.ITALIC | Font.BOLD))
		return PDType1Font.TIMES_BOLD_ITALIC;
	if ((font.getStyle() & Font.ITALIC) == Font.ITALIC)
		return PDType1Font.TIMES_ITALIC;
	if ((font.getStyle() & Font.BOLD) == Font.BOLD)
		return PDType1Font.TIMES_BOLD;
	return PDType1Font.TIMES_ROMAN;
}
 
Example 7
Project: pdfbox-graphics2d   File: PdfBoxGraphics2DFontTextDrawerDefaultFonts.java   View source code 6 votes vote down vote up
/**
 * Get a PDType1Font.COURIER-variant, which matches the given font
 * 
 * @param font
 *            Font to get the styles from
 * @return a PDFont Courier variant which matches the style in the given Font
 *         object.
 */
public static PDFont chooseMatchingCourier(Font font) {
	if ((font.getStyle() & (Font.ITALIC | Font.BOLD)) == (Font.ITALIC | Font.BOLD))
		return PDType1Font.COURIER_BOLD_OBLIQUE;
	if ((font.getStyle() & Font.ITALIC) == Font.ITALIC)
		return PDType1Font.COURIER_OBLIQUE;
	if ((font.getStyle() & Font.BOLD) == Font.BOLD)
		return PDType1Font.COURIER_BOLD;
	return PDType1Font.COURIER;
}
 
Example 8
Project: pdfbox-graphics2d   File: PdfBoxGraphics2DFontTextDrawerDefaultFonts.java   View source code 6 votes vote down vote up
/**
 * Get a PDType1Font.HELVETICA-variant, which matches the given font
 * 
 * @param font
 *            Font to get the styles from
 * @return a PDFont Helvetica variant which matches the style in the given Font
 *         object.
 */
public static PDFont chooseMatchingHelvetica(Font font) {
	if ((font.getStyle() & (Font.ITALIC | Font.BOLD)) == (Font.ITALIC | Font.BOLD))
		return PDType1Font.HELVETICA_BOLD_OBLIQUE;
	if ((font.getStyle() & Font.ITALIC) == Font.ITALIC)
		return PDType1Font.HELVETICA_OBLIQUE;
	if ((font.getStyle() & Font.BOLD) == Font.BOLD)
		return PDType1Font.HELVETICA_BOLD;
	return PDType1Font.HELVETICA;
}
 
Example 9
Project: pdfbox-graphics2d   File: PdfBoxGraphics2DTestBase.java   View source code 6 votes vote down vote up
@SuppressWarnings("SpellCheckingInspection")
void exportGraphic(String dir, String name, GraphicsExporter exporter) {
	try {
		PDDocument document = new PDDocument();

		PDFont pdArial = PDFontFactory.createDefaultFont();

		File parentDir = new File("target/test/" + dir);
		// noinspection ResultOfMethodCallIgnored
		parentDir.mkdirs();

		BufferedImage image = new BufferedImage(400, 400, BufferedImage.TYPE_4BYTE_ABGR);
		Graphics2D imageGraphics = image.createGraphics();
		exporter.draw(imageGraphics);
		imageGraphics.dispose();
		ImageIO.write(image, "PNG", new File(parentDir, name + ".png"));

		for (Mode m : Mode.values()) {
			PDPage page = new PDPage(PDRectangle.A4);
			document.addPage(page);

			PDPageContentStream contentStream = new PDPageContentStream(document, page);
			PdfBoxGraphics2D pdfBoxGraphics2D = new PdfBoxGraphics2D(document, 400, 400);
			PdfBoxGraphics2DFontTextDrawer fontTextDrawer = null;
			contentStream.beginText();
			contentStream.setStrokingColor(0, 0, 0);
			contentStream.setNonStrokingColor(0, 0, 0);
			contentStream.setFont(PDType1Font.HELVETICA_BOLD, 15);
			contentStream.setTextMatrix(Matrix.getTranslateInstance(10, 800));
			contentStream.showText("Mode " + m);
			contentStream.endText();
			switch (m) {
			case FontTextIfPossible:
				fontTextDrawer = new PdfBoxGraphics2DFontTextDrawer();
				fontTextDrawer.registerFont(
						new File("src/test/resources/de/rototor/pdfbox/graphics2d/DejaVuSerifCondensed.ttf"));
				break;
			case DefaultFontText: {
				fontTextDrawer = new PdfBoxGraphics2DFontTextDrawerDefaultFonts();
				fontTextDrawer.registerFont(
						new File("src/test/resources/de/rototor/pdfbox/graphics2d/DejaVuSerifCondensed.ttf"));
				break;
			}
			case ForceFontText:
				fontTextDrawer = new PdfBoxGraphics2DFontTextForcedDrawer();
				fontTextDrawer.registerFont(
						PdfBoxGraphics2DTestBase.class.getResourceAsStream("DejaVuSerifCondensed.ttf"));
				fontTextDrawer.registerFont("Arial", pdArial);
				break;
			case DefaultVectorized:
			default:
				break;
			}

			if (fontTextDrawer != null) {
				pdfBoxGraphics2D.setFontTextDrawer(fontTextDrawer);
			}

			exporter.draw(pdfBoxGraphics2D);
			pdfBoxGraphics2D.dispose();

			PDFormXObject appearanceStream = pdfBoxGraphics2D.getXFormObject();
			Matrix matrix = new Matrix();
			matrix.translate(0, 20);
			contentStream.transform(matrix);
			contentStream.drawForm(appearanceStream);

			matrix.scale(1.5f, 1.5f);
			matrix.translate(0, 100);
			contentStream.transform(matrix);
			contentStream.drawForm(appearanceStream);
			contentStream.close();
		}

		document.save(new File(parentDir, name + ".pdf"));
		document.close();
	} catch (Exception e) {
		throw new RuntimeException(e);
	}
}
 
Example 10
Project: scim2-compliance-test-suite   File: PDFGenerator.java   View source code 6 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 11
Project: scim2-compliance-test-suite   File: PDFGenerator.java   View source code 6 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 12
Project: ctsms   File: PDFUtil.java   View source code 6 votes vote down vote up
public static PDFont loadFont(String fontFileName, PDDocument doc, PDFont defaultBaseFont) throws IOException {
	// public static PDFont loadFont(String fontFileName, PDDocument doc, PDFont defaultBaseFont, PDStream pdStream) 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;
	}
	// if (font != null && pdStream != null) {
	// if (font instanceof PDType1Font) {
	// ((PDType1Font) font).setToUnicode(pdStream.getCOSObject());
	// } else if (font instanceof PDTrueTypeFont) {
	// ((PDTrueTypeFont) font).setToUnicode(pdStream.getCOSObject());
	// }
	// }
	return font;
}
 
Example 13
Project: pdf-unstamper   File: TextStampRecognizer.java   View source code 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
Project: pdfbox-graphics2d   File: PdfBoxGraphics2DFontTextDrawerDefaultFonts.java   View source code 5 votes vote down vote up
@Override
protected PDFont mapFont(Font font, IFontTextDrawerEnv env) throws IOException, FontFormatException {
	PDFont pdFont = mapDefaultFonts(font);
	if (pdFont != null)
		return pdFont;

	/*
	 * Do we have a manual registered mapping with a font file?
	 */
	pdFont = super.mapFont(font, env);
	if (pdFont != null)
		return pdFont;
	return chooseMatchingHelvetica(font);
}
 
Example 15
Project: pdfbox-graphics2d   File: PdfBoxGraphics2DFontTextDrawer.java   View source code 5 votes vote down vote up
private PDFont findFallbackFont(IFontTextDrawerEnv env) throws IOException {
	/*
	 * We search for the right font in the system folders... We try to use
	 * LucidaSansRegular and if not found Arial, because this fonts often exists. We
	 * use the Java default font as fallback.
	 * 
	 * Normally this method is only used and called if a default font misses some
	 * special characters, e.g. Hebrew or Arabic characters.
	 */
	String javaHome = System.getProperty("java.home", ".");
	String javaFontDir = javaHome + "/lib/fonts";
	String windir = System.getenv("WINDIR");
	if (windir == null)
		windir = javaFontDir;
	File[] paths = new File[] { new File(new File(windir), "fonts"), new File(System.getProperty("user.dir", ".")),
			new File("/Library/Fonts"), new File("/usr/share/fonts/truetype"), new File(javaFontDir) };
	File foundFontFile = null;
	for (String fontFileName : new String[] { "LucidaSansRegular.ttf", "arial.ttf", "Arial.ttf" }) {
		for (File path : paths) {
			File arialFile = new File(path, fontFileName);
			if (arialFile.exists()) {
				foundFontFile = arialFile;
				break;
			}
		}
		if (foundFontFile != null)
			break;
	}
	return PDType0Font.load(env.getDocument(), foundFontFile);
}
 
Example 16
Project: pdfbox-graphics2d   File: PdfBoxGraphics2DFontTextDrawer.java   View source code 5 votes vote down vote up
private PDFont applyFont(Font font, IFontTextDrawerEnv env) throws IOException, FontFormatException {
	PDFont fontToUse = mapFont(font, env);
	if (fontToUse == null) {
		/*
		 * If we have no font but are forced to apply a font, we just use the default
		 * builtin PDF font...
		 */
		fontToUse = PdfBoxGraphics2DFontTextDrawerDefaultFonts.chooseMatchingHelvetica(font);
	}
	env.getContentStream().setFont(fontToUse, font.getSize2D());
	return fontToUse;
}
 
Example 17
Project: git-rekt   File: BillPdfGenerator.java   View source code 5 votes vote down vote up
private float getStringWidth(String text, PDFont font, int fontSize) throws IOException {
    return font.getStringWidth(text) * fontSize / 1000F;
}
 
Example 18
Project: 484_P7_1-Java   File: TextElement.java   View source code 5 votes vote down vote up
public TextElement(float y, float x, float width, float height,
                   PDFont font, float fontSize, String c, float widthOfSpace, float dir) {
    super();
    this.setRect(x, y, width, height);
    this.text = c;
    this.widthOfSpace = widthOfSpace;
    this.fontSize = fontSize;
    this.font = font;
    this.dir = dir;
}
 
Example 19
Project: ctsms   File: ReimbursementsPDFBlockCursor.java   View source code 5 votes vote down vote up
public PDFont getFontD() {
	return painter.getFontD();
}
 
Example 20
Project: ctsms   File: ReimbursementsPDFBlockCursor.java   View source code 5 votes vote down vote up
public PDFont getFontF() {
	return painter.getFontF();
}
 
Example 21
Project: easytable   File: Table.java   View source code 4 votes vote down vote up
private void setFont(final PDFont font) {
    this.font = font;
}
 
Example 22
Project: easytable   File: Table.java   View source code 4 votes vote down vote up
public PDFont getFont() {
    return font;
}
 
Example 23
Project: easytable   File: Table.java   View source code 4 votes vote down vote up
public TableBuilder setFont(final PDFont font) {
    this.table.setFont(font);
    return this;
}
 
Example 24
Project: ctsms   File: CourseParticipantListPDFBlockCursor.java   View source code 4 votes vote down vote up
public PDFont getFontB() {
	return painter.getFontB();
}
 
Example 25
Project: ctsms   File: CourseParticipantListPDFBlockCursor.java   View source code 4 votes vote down vote up
public PDFont getFontA() {
	return painter.getFontA();
}
 
Example 26
Project: ctsms   File: CourseParticipantListPDFBlockCursor.java   View source code 4 votes vote down vote up
public PDFont getFontC() {
	return painter.getFontC();
}
 
Example 27
Project: 484_P7_1-Java   File: TextElement.java   View source code 4 votes vote down vote up
public TextElement(float y, float x, float width, float height,
                   PDFont font, float fontSize, String c, float widthOfSpace) {
    this(y, x, width, height, font, fontSize, c, widthOfSpace, 0f);
}
 
Example 28
Project: 484_P7_1-Java   File: TextElement.java   View source code 4 votes vote down vote up
public PDFont getFont() {
    return font;
}
 
Example 29
Project: ctsms   File: ReimbursementsPDFBlockCursor.java   View source code 4 votes vote down vote up
public PDFont getFontA() {
	return painter.getFontA();
}
 
Example 30
Project: ctsms   File: ReimbursementsPDFBlockCursor.java   View source code 4 votes vote down vote up
public PDFont getFontB() {
	return painter.getFontB();
}
 
Example 31
Project: ctsms   File: ReimbursementsPDFBlockCursor.java   View source code 4 votes vote down vote up
public PDFont getFontC() {
	return painter.getFontC();
}
 
Example 32
Project: ctsms   File: ReimbursementsPDFBlockCursor.java   View source code 4 votes vote down vote up
public PDFont getFontE() {
	return painter.getFontE();
}
 
Example 33
Project: scim2-compliance-test-suite   File: PDFGenerator.java   View source code 4 votes vote down vote up
/**
 * Print the results to PDF.
 * @param contentStream
 * @param fontSize
 * @param pdfFont
 * @param leading
 * @param startX
 * @param startY
 * @param lines
 * @throws IOException
 */
public static void printResult(PDPageContentStream contentStream, float fontSize,
                               PDFont pdfFont, float leading, float startX, float startY, List<String> lines)
        throws IOException {
    for (String line : lines) {
        contentStream.showText(line);
        contentStream.newLineAtOffset(0, -leading);
    }
}
 
Example 34
Project: ctsms   File: InquiriesPDFBlockCursor.java   View source code 4 votes vote down vote up
public PDFont getFontB() {
	return painter.getFontB();
}
 
Example 35
Project: ctsms   File: InquiriesPDFBlockCursor.java   View source code 4 votes vote down vote up
public PDFont getFontC() {
	return painter.getFontC();
}
 
Example 36
Project: ctsms   File: InquiriesPDFBlockCursor.java   View source code 4 votes vote down vote up
public PDFont getFontD() {
	return painter.getFontD();
}
 
Example 37
Project: ctsms   File: EcrfPDFBlockCursor.java   View source code 4 votes vote down vote up
public PDFont getFontA() {
	return painter.getFontA();
}
 
Example 38
Project: ctsms   File: EcrfPDFBlockCursor.java   View source code 4 votes vote down vote up
public PDFont getFontB() {
	return painter.getFontB();
}
 
Example 39
Project: ctsms   File: EcrfPDFBlockCursor.java   View source code 4 votes vote down vote up
public PDFont getFontC() {
	return painter.getFontC();
}
 
Example 40
Project: ctsms   File: EcrfPDFBlockCursor.java   View source code 4 votes vote down vote up
public PDFont getFontD() {
	return painter.getFontD();
}