Java Code Examples for org.apache.pdfbox.pdmodel.PDPageContentStream.setFont()

The following are Jave code examples for showing how to use setFont() of the org.apache.pdfbox.pdmodel.PDPageContentStream class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
Example 1
Project: easytable   File: TableDrawerIntegrationTest.java   Source Code and License Vote up 11 votes
@Test
public void createRingManagerDocument() throws Exception {
    final PDDocument document = new PDDocument();
    final PDPage page = new PDPage(PDRectangle.A4);
    document.addPage(page);

    final float startY = page.getMediaBox().getHeight() - 150;
    final int startX = 56;

    final PDPageContentStream contentStream = new PDPageContentStream(document, page);
    Table table = getRingManagerTable();

    (new TableDrawer(contentStream, table, startX, startY)).draw();

    contentStream.setFont(PDType1Font.HELVETICA, 8.0f);
    contentStream.beginText();

    contentStream.newLineAtOffset(startX, startY - (table.getHeight() + 22));
    contentStream.showText("Dieser Kampf muss der WB nicht entsprechen, da als Sparringskampf angesetzt.");
    contentStream.endText();

    contentStream.close();

    document.save("target/ringmanager.pdf");
    document.close();
}
 
Example 2
Project: esup-ecandidat   File: CandidatureController.java   Source Code and License Vote up 10 votes
/**
 * @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 3
Project: kumoreg   File: ReportPrintFormatter.java   Source Code and License Vote up 9 votes
private PDPage generatePage(String[] lines, int startAt, PDDocument document) throws IOException {
    PDPage page = new PDPage(new PDRectangle(612f, 396f));
    PDPageContentStream contentStream = new PDPageContentStream(document, page);

    // Positions are measured from the bottom left corner of the page at 72 DPI

    // Add report text to page
    contentStream.beginText();
    contentStream.moveTextPositionByAmount(36+xOffset, 360+yOffset);
    contentStream.setFont(font, fontSize);
    int lineNumber = startAt;
    while (lineNumber < startAt + linesPerPage && lineNumber < lines.length) {
        contentStream.drawString(lines[lineNumber]);
        contentStream.moveTextPositionByAmount(0, (-1*fontSize));
        lineNumber += 1;
    }
    contentStream.endText();

    contentStream.close();

    return page;

}
 
Example 4
Project: testarea-pdfbox2   File: RenderType3Character.java   Source Code and License Vote up 9 votes
/**
 * <a href="http://stackoverflow.com/questions/42032729/render-type3-font-character-as-image-using-pdfbox">
 * Render Type3 font character as image using PDFBox
 * </a>
 * <br/>
 * <a href="https://drive.google.com/file/d/0B0f6X4SAMh2KRDJTbm4tb3E1a1U/view">
 * 4700198773.pdf
 * </a>
 * from
 * <a href="http://stackoverflow.com/questions/37754112/extract-text-with-custom-font-result-non-readble">
 * extract text with custom font result non readble
 * </a>
 * <p>
 * This test shows how one can render individual Type 3 font glyphs as bitmaps.
 * Unfortunately PDFBox out-of-the-box does not provide a class to render contents
 * of arbitrary XObjects, merely for rendering pages; thus, we simply create a page
 * with the glyph in question and render that page.   
 * </p>
 * <p>
 * As the OP did not provide a sample PDF, we simply use one from another
 * stackoverflow question. There obviously might remain issues with the
 * OP's files.
 * </p>
 */
@Test
public void testRenderSdnList() throws IOException
{
    try (   InputStream resource = getClass().getResourceAsStream("sdnlist.pdf"))
    {
        PDDocument document = PDDocument.load(resource);

        PDPage page = document.getPage(1);
        PDResources pageResources = page.getResources();
        COSName f1Name = COSName.getPDFName("R144");
        PDType3Font fontF1 = (PDType3Font) pageResources.getFont(f1Name);
        Map<String, Integer> f1NameToCode = fontF1.getEncoding().getNameToCodeMap();

        COSDictionary charProcsDictionary = fontF1.getCharProcs();
        for (COSName key : charProcsDictionary.keySet())
        {
            COSStream stream = (COSStream) charProcsDictionary.getDictionaryObject(key);
            PDType3CharProc charProc = new PDType3CharProc(fontF1, stream);
            PDRectangle bbox = charProc.getGlyphBBox();
            if (bbox == null)
                bbox = charProc.getBBox();
            Integer code = f1NameToCode.get(key.getName());

            if (code != null)
            {
                PDDocument charDocument = new PDDocument();
                PDPage charPage = new PDPage(bbox);
                charDocument.addPage(charPage);
                charPage.setResources(pageResources);
                PDPageContentStream charContentStream = new PDPageContentStream(charDocument, charPage);
                charContentStream.beginText();
                charContentStream.setFont(fontF1, bbox.getHeight());
                charContentStream.getOutput().write(String.format("<%2X> Tj\n", code).getBytes());
                charContentStream.endText();
                charContentStream.close();

                File result = new File(RESULT_FOLDER, String.format("sdnlist-%s-%s.png", key.getName(), code));
                PDFRenderer renderer = new PDFRenderer(charDocument);
                BufferedImage image = renderer.renderImageWithDPI(0, 96);
                ImageIO.write(image, "PNG", result);
                charDocument.save(new File(RESULT_FOLDER, String.format("sdnlist-%s-%s.pdf", key.getName(), code)));
                charDocument.close();
            }
        }
    }
}
 
Example 5
Project: git-rekt   File: BillPdfGenerator.java   Source Code and License Vote up 8 votes
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 6
Project: melon   File: PdfDemo.java   Source Code and License Vote up 8 votes
@Test
public void test001() throws IOException {
    //E:\Repository\Git\melon\melon-sample-pdf\src\main\resources\HTTP权威指南.pdf
    System.out.println("Hello World!");

    PDDocument pdDocument = new PDDocument();
    PDPage pdPage = new PDPage();
    pdDocument.addPage(pdPage);

    PDFont pdFont = PDType1Font.HELVETICA_BOLD;

    PDPageContentStream contentStream = new PDPageContentStream(pdDocument, pdPage);
    contentStream.beginText();
    contentStream.setFont(pdFont, 14);
    contentStream.newLineAtOffset(100, 700);
    contentStream.showText("Hello World");
    contentStream.endText();
    contentStream.close();

    String directory = PdfDemo.class.getClassLoader().getResource("").getPath();
    String fileName = "text.pdf";

    pdDocument.save(directory + fileName);
    pdDocument.close();
}
 
Example 7
Project: FYS_T3   File: statisticsController.java   Source Code and License Vote up 7 votes
@FXML
public void printPDFFile(ActionEvent event) throws IOException {
    try {
        String fileName = "PDFoutput.pdf";

        PDDocument doc = new PDDocument();
        PDPage page = new PDPage();
        doc.addPage(page);

        PDPageContentStream content = new PDPageContentStream(doc, page);

        content.beginText();
        content.setFont(PDType1Font.TIMES_ROMAN, 26);
        content.moveTextPositionByAmount(220, 750);
        content.drawString("Titel");
        content.endText();

        content.beginText();
        content.setFont(PDType1Font.TIMES_ROMAN, 16);
        content.moveTextPositionByAmount(80, 700);
        content.drawString("Inhoud");
        content.endText();

        content.close();
        doc.save(fileName);
        doc.close();

        System.out.println("your file was saved in: " + System.getProperty("user.dir"));

    } catch (Exception e) {
        System.err.println(e.getMessage());
    }
}
 
Example 8
Project: kumoreg   File: FullBadgePrintFormatter.java   Source Code and License Vote up 7 votes
private void drawAgeColorStripe(PDPageContentStream contentStream, PDFont font, Attendee attendee) throws IOException {
    // Draw age color stripe
    String stripeText = "VOID";
    if (attendee.getCurrentAgeRange() != null) {
        contentStream.setNonStrokingColor(Color.decode(attendee.getCurrentAgeRange().getStripeColor()));
        stripeText = attendee.getCurrentAgeRange().getStripeText();
    } else {
        contentStream.setNonStrokingColor(Color.black);
    }
    contentStream.fillRect(155, 92, 300, 45);

    contentStream.setLineWidth(0.5f);

    // Draw age range text in color stripe
    contentStream.beginText();
    contentStream.setFont(font, 32);
    contentStream.setNonStrokingColor(Color.white);
    contentStream.setStrokingColor(Color.black);
    contentStream.moveTextPositionByAmount(438, 105);
    contentStream.appendRawCommands("2 Tr ");       // Set text rendering mode
    Float ageRangeWidth = ((font.getStringWidth(stripeText) / 1000.0f) * 32);
    contentStream.moveTextPositionByAmount(-ageRangeWidth, 0);
    contentStream.drawString(stripeText);
    contentStream.endText();
}
 
Example 9
Project: testarea-pdfbox2   File: JoinPages.java   Source Code and License Vote up 7 votes
/**
 * @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 = PDFontFactory.createDefaultFont();
    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 10
Project: pcm-api   File: PdfBoxServiceImpl.java   Source Code and License Vote up 7 votes
@Override
public void addTextAtOffset(String text, PDFont font, float fontSize, Color textColor, float xCoordinate, float yCoordinate, PDPageContentStream contentStream) throws IOException {
    if (text.isEmpty()) {
        log.warn("The inputs are empty string start from the position: ".concat(xCoordinate + ", " + yCoordinate));
    }
    if (textColor == null) {
        textColor = Color.BLACK;
    }
    contentStream.setNonStrokingColor(textColor);
    contentStream.setFont(font, fontSize);
    contentStream.beginText();
    contentStream.newLineAtOffset(xCoordinate, yCoordinate);
    contentStream.showText(text);
    contentStream.endText();

    // Reset changed color
    resetChangedColorToDefault(contentStream);
}
 
Example 11
Project: testarea-pdfbox2   File: JoinPages.java   Source Code and License Vote up 7 votes
/**
 * @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 = PDFontFactory.createDefaultFont();
    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 12
Project: pdfbox-graphics2d   File: PdfBoxGraphics2DTestBase.java   Source Code and License Vote up 6 votes
@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 13
Project: git-rekt   File: BillPdfGenerator.java   Source Code and License Vote up 6 votes
public PDDocument getBillAsPdf() throws IOException {
    // Add blank page to document
    PDPage firstPage = new PDPage();
    document.addPage(firstPage);
    PDPageContentStream contentStream = new PDPageContentStream(document, firstPage);
    generateBillHeader(firstPage, contentStream);
    generateBillInfoText(firstPage, contentStream);
    contentStream.beginText();
    contentStream.newLineAtOffset(60f, 640f);

    // Add the column line item header line
    contentStream.setFont(PDType1Font.COURIER_BOLD, NORMAL_FONT_SIZE);
    contentStream.newLine();
    contentStream.showText(lineItemHeader);

    // Add bill line items
    contentStream.setFont(NORMAL_FONT, NORMAL_FONT_SIZE);
    for(String lineItem : lineItems) {
        contentStream.newLine();
        contentStream.showText(lineItem);
    }

    // Display the bill total at the end
    contentStream.newLine();
    String billTotalLine = getBillTotalLine();
    contentStream.setFont(PDType1Font.COURIER_BOLD, NORMAL_FONT_SIZE);
    contentStream.newLine();
    contentStream.showText(billTotalLine);

    // Display important bill information
    contentStream.newLine();
    contentStream.newLine();
    contentStream.showText("WARNING: Failure to pay bill may result in broken legs.");

    contentStream.endText();
    contentStream.close();

    return document;
}
 
Example 14
Project: kumoreg   File: FormatterBase.java   Source Code and License Vote up 6 votes
/**
 * Draws the given string, optionally supports scaling to fit.
 * @param x Left side of text, or center point of text if centered (1/72 inch)
 * @param y Bottom of text, in points (1/72 inch)
 * @param text Text to draw
 * @param optOrig Resize Options
 * @throws IOException Error generating PDF
 */
void drawStringWithResizing(PDPageContentStream stream, float x, float y, String text, ResizeOptions optOrig) throws IOException {
    ResizeOptions opt = new ResizeOptions(optOrig);
    float textSize = opt.font.getStringWidth(text); // in thousandths of font pt size.
    float size = opt.size;

    // If text size is greater than maximum width, recalculate the correct font size, based on our restrictions
    if (textSize * (size/1000.0f) > opt.maxTextWidth) {
        size = opt.maxTextWidth * 1000.0f / textSize;
        if (size < opt.minFontSize) {
            // We have utterly failed to fit the text with the minimum font size,
            // So we're forced to use that.
            size = opt.minFontSize;
        }
    }

    if (opt.centered) {
        x -= textSize * (size/(2*1000.0f));
    }

    // Actually draw the text
    stream.beginText();
    stream.setStrokingColor(Color.black);
    stream.setNonStrokingColor(Color.black);
    stream.moveTextPositionByAmount(x, y);
    stream.setFont(opt.font, size);
    stream.drawString(text);
    stream.endText();
}
 
Example 15
Project: kumoreg   File: FormatterBase.java   Source Code and License Vote up 6 votes
/**
     * Draws the given string, optionally supports scaling to fit.
     * @param x Left side of text, or center point of text if centered (1/72 inch)
     * @param y Bottom of text, in points (1/72 inch)
     * @param text Text to draw
     * @param optOrig Resize Options
     * @throws IOException Error generating PDF
     */
    void drawStringRotatedWithResizing(PDPageContentStream stream, float x, float y, int width, int height, String text, ResizeOptions optOrig) throws IOException {
        stream.setNonStrokingColor(Color.gray);
        PDRectangle boundingBox = new PDRectangle(x, y, width, height);
        stream.fillRect(x, y, width, height);

        ResizeOptions opt = new ResizeOptions(optOrig);
        float textSize = opt.font.getStringWidth(text); // in thousandths of font pt size.
        float size = opt.size;

        float centeredXPosition = x + (boundingBox.getWidth()/2f);
        float stringWidth = opt.font.getStringWidth( text );
        float centeredYPosition = y + (boundingBox.getHeight() /2f);

        stream.setNonStrokingColor(Color.GREEN);
        stream.fillRect(centeredXPosition, centeredYPosition, 3, 3);

        Matrix offset = Matrix.getRotateInstance(90 * Math.PI * 0.25,
                centeredXPosition, centeredYPosition-(stringWidth/1000/2));
        stream.beginText();
        stream.setTextMatrix(offset);

        stream.setStrokingColor(Color.black);
        stream.setNonStrokingColor(Color.black);
        stream.setFont(opt.font, size);
        stream.showText(text);
        stream.endText();

//
//        // If text size is greater than maximum width, recalculate the correct font size, based on our restrictions
//        if (textSize * (size/1000.0f) > opt.maxTextWidth) {
//            size = opt.maxTextWidth * 1000.0f / textSize;
//            if (size < opt.minFontSize) {
//                // We have utterly failed to fit the text with the minimum font size,
//                // So we're forced to use that.
//                size = opt.minFontSize;
//            }
//        }
//
//        if (opt.centered) {
//            y -= textSize * (size/(2*1000.0f));
//        }
////
////        Matrix offset = Matrix.getRotateInstance(i * Math.PI * 0.25,
////                centered XPosition, pageSize.getHeight() - centeredYPosition)
//        Matrix offset = new Matrix();
//        offset.rotate(Math.toRadians(5));
//        offset.translate(100, 100);
//        // Actually draw the text
    }
 
Example 16
Project: kumoreg   File: AttendeeBadge2017.java   Source Code and License Vote up 6 votes
private void drawBadgeNumber(PDPage page, PDFont font, Attendee attendee) throws IOException {
        String badgeNumber = attendee.getBadgeNumber();
        if (badgeNumber == null) {
            return;     // no text, don't draw anything
        }

        List<String> badgeNumberParts = BadgeLib.splitBadgeNumber(badgeNumber);

        PDPageContentStream stream = new PDPageContentStream(document, page, PDPageContentStream.AppendMode.APPEND, true, false);

        String stripeColor = attendee.getCurrentAgeRange().getStripeColor();
        stream.setNonStrokingColor(BadgeLib.getForegroundColor(stripeColor));
        // Bounding box:
//         stream.fillRect(163, 95, 40, 30);

        PDRectangle boundingBox = new PDRectangle(163, 95, 40, 30);
        stream.setLineWidth(0.25f);
        stream.beginText();
        int fontSize = BadgeLib.findMaxFontSize(font, badgeNumberParts,boundingBox);
        stream.setFont(font, fontSize);

        float textWidth = font.getStringWidth(badgeNumberParts.get(0));
        Float offset = textWidth * (fontSize/(2*1000.0f));
        stream.newLineAtOffset(185-offset, 105+fontSize);   // First character position
        stream.showText(badgeNumberParts.get(0));

        if (badgeNumberParts.size() > 1) {
            textWidth = font.getStringWidth(badgeNumberParts.get(1));
            Float newOffset = textWidth * (fontSize/(2*1000.0f));
            stream.newLineAtOffset(offset-newOffset, -1*fontSize);   // First character position
            stream.showText(badgeNumberParts.get(1));
        }
        stream.close();
    }
 
Example 17
Project: kumoreg   File: AttendeeBadge2017.java   Source Code and License Vote up 6 votes
private void drawBadgeTypeText(PDPage page, PDFont font, Attendee attendee) throws IOException {
        if (attendee.getBadge() == null || attendee.getBadge().getBadgeTypeText() == null) {
            return;     // no text, don't draw anything
        }
        String badgeTypeText = attendee.getBadge().getBadgeTypeText();
        PDPageContentStream stream = new PDPageContentStream(document, page, PDPageContentStream.AppendMode.APPEND, true, false);

//        PDRectangle boundingBox = new PDRectangle(206, 85, 253, 44);

        stream.setLineWidth(0.5f);
        stream.beginText();
        int fontSize = BadgeLib.findMaxLineSize(font, badgeTypeText,240, 40);
        stream.setFont(font, fontSize);
        if (attendee.getBadge() != null &&
                (attendee.getBadge().getBadgeTypeText().equals("Friday") ||
                        attendee.getBadge().getBadgeTypeText().equals("Saturday") ||
                        attendee.getBadge().getBadgeTypeText().equals("Sunday"))) {
            if (attendee.getBadge() != null && attendee.getBadge().getBadgeTypeBackgroundColor() != null) {
                stream.setNonStrokingColor(BadgeLib.getForegroundColor(attendee.getCurrentAgeRange().getStripeColor()));
            } else {
                stream.setNonStrokingColor(Color.WHITE);
                stream.setStrokingColor(Color.black);
            }

        } else {
            if (attendee.getBadge() != null && attendee.getBadge().getBadgeTypeBackgroundColor() != null) {
                stream.setNonStrokingColor(BadgeLib.getForegroundColor(attendee.getBadge().getBadgeTypeBackgroundColor()));
            } else {
                stream.setNonStrokingColor(Color.WHITE);
                stream.setStrokingColor(Color.black);
            }

        }

        float textWidth = font.getStringWidth(badgeTypeText);
        Float offset = textWidth * (fontSize/(2*1000.0f));
        stream.newLineAtOffset(330-offset, 100);   // First character position
        stream.showText(badgeTypeText);
        stream.close();
    }
 
Example 18
Project: kumoreg   File: FullBadgePrintFormatter.java   Source Code and License Vote up 6 votes
/**
 * Draws the given string, optionally supports scaling to fit.
 * @param contentStream Open stream to draw in to
 * @param x Left side of text, or center point of text if centered (1/72 inch)
 * @param y Bottom of text, in points (1/72 inch)
 * @param text Text to draw
 * @param optOrig Resize Options
 * @throws IOException Error generating PDF
 */
private void drawStringWithResizing(PDPageContentStream contentStream, float x, float y, String text, ResizeOptions optOrig) throws IOException {
    ResizeOptions opt = new ResizeOptions(optOrig);
    float textSize = opt.font.getStringWidth(text); // in thousandths of font pt size.
    float size = opt.size;

    // If text size is greater than maximum width, recalculate the correct font size, based on our restrictions
    if (textSize * (size/1000.0f) > opt.maxTextWidth) {
        size = opt.maxTextWidth * 1000.0f / textSize;
        if (size < opt.minFontSize) {
            // We have utterly failed to fit the text with the minimum font size,
            // So we're forced to use that.
            size = opt.minFontSize;
        }
    }

    if (opt.centered) {
        x -= textSize * (size/(2*1000.0f));
    }

    // Actually draw the text
    contentStream.beginText();
    contentStream.moveTextPositionByAmount(x, y);
    contentStream.setFont(opt.font, size);
    contentStream.drawString(text);
    contentStream.endText();
}
 
Example 19
Project: AwesomeJavaLibraryExamples   File: ExampleAddImage.java   Source Code and License Vote up 6 votes
private static void createOverlayDocument(File overlayPdf) throws IOException
{
   PDDocument overlayDoc = new PDDocument();

   try
   {
      PDPage page=new PDPage();

      overlayDoc.addPage(page);
      PDFont font=PDType1Font.COURIER_OBLIQUE;

      PDPageContentStream contentStream=new PDPageContentStream(overlayDoc, page);
      contentStream.setFont(font, 50);
      contentStream.setNonStrokingColor(0);
      contentStream.beginText();
      contentStream.newLineAtOffset(100, 500);
      contentStream.setNonStrokingColor(255, 0, 0);
      contentStream.showText("CLASSIFIED");
      contentStream.endText();
      contentStream.close();
      overlayDoc.save(overlayPdf);
   }
   finally
   {
      overlayDoc.close();
   }
}
 
Example 20
Project: testarea-pdfbox2   File: TextAndGraphics.java   Source Code and License Vote up 6 votes
/**
 * <a href="https://stackoverflow.com/questions/44503236/how-to-write-text-draw-a-line-and-then-again-write-text-in-a-pdf-file-using-pdf">
 * How to write text, draw a line and then again write text in a pdf file using PDFBox
 * </a>
 * <p>
 * This test shows how to draw tetx, then graphics, then again text.
 * </p>
 */
@Test
public void testDrawTextLineText() throws IOException
{
    PDFont font = PDType1Font.HELVETICA;
    float fontSize = 14;
    float fontHeight = fontSize;
    float leading = 20;
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy.MM.dd");
    Date date = new Date();

    PDDocument doc = new PDDocument();
    PDPage page = new PDPage();
    doc.addPage(page);

    PDPageContentStream contentStream = new PDPageContentStream(doc, page);
    contentStream.setFont(font, fontSize);

    float yCordinate = page.getCropBox().getUpperRightY() - 30;
    float startX = page.getCropBox().getLowerLeftX() + 30;
    float endX = page.getCropBox().getUpperRightX() - 30;

    contentStream.beginText();
    contentStream.newLineAtOffset(startX, yCordinate);
    contentStream.showText("Entry Form � Header");
    yCordinate -= fontHeight;  //This line is to track the yCordinate
    contentStream.newLineAtOffset(0, -leading);
    yCordinate -= leading;
    contentStream.showText("Date Generated: " + dateFormat.format(date));
    yCordinate -= fontHeight;
    contentStream.endText(); // End of text mode

    contentStream.moveTo(startX, yCordinate);
    contentStream.lineTo(endX, yCordinate);
    contentStream.stroke();
    yCordinate -= leading;

    contentStream.beginText();
    contentStream.newLineAtOffset(startX, yCordinate);
    contentStream.showText("Name: XXXXX");
    contentStream.endText();

    contentStream.close();
    doc.save(new File(RESULT_FOLDER, "textLineText.pdf"));
}
 
Example 21
Project: zest-writer   File: PdfUtilExport.java   Source Code and License Vote up 6 votes
private void addCoverpage() throws IOException {
    float leading = 1.5f * FONT_SIZE_TITLE;
    PDDocument document = new PDDocument();
    PDPage page = new PDPage();
    document.addPage(page);
    FONT_STYLE_COVER = PDTrueTypeFont.loadTTF(document, MainApp.class.getResourceAsStream(FONT_MERRIWEATHER_BOLD));
    PDPageContentStream contentStream = new PDPageContentStream(document, page);
    contentStream.setNonStrokingColor(25, 81, 107);
    contentStream.fillRect(0, 0, page.getMediaBox().getWidth(), (page.getMediaBox().getHeight() / 2) - 10);
    contentStream.fillRect(0, (page.getMediaBox().getHeight() / 2) + 10, page.getMediaBox().getWidth(), (page.getMediaBox().getHeight() / 2) - 10);
    contentStream.setNonStrokingColor(248, 173, 50);
    contentStream.fillRect(0, (page.getMediaBox().getHeight() / 2) - 10, page.getMediaBox().getWidth(), 20);

    contentStream.beginText();
    contentStream.setNonStrokingColor(Color.WHITE);
    contentStream.setFont(FONT_STYLE_COVER, FONT_SIZE_AUTHOR);
    contentStream.newLineAtOffset(20, 20);
    contentStream.showText(authorContent);
    contentStream.setFont(FONT_STYLE_COVER, FONT_SIZE_TITLE);
    contentStream.newLineAtOffset((page.getMediaBox().getWidth() / 2) - 20, 600);
    List<String> lines = wrapText((page.getMediaBox().getWidth() / 2) - 20);
    for (String line : lines) {
        contentStream.showText(line);
        contentStream.newLineAtOffset(0, -leading);
    }
    contentStream.endText();

    contentStream.close();
    File temp = File.createTempFile("coverpage-zds", ".pdf");
    document.save(temp);
    document.close();

    PDFMergerUtility mergerUtility = new PDFMergerUtility();
    mergerUtility.addSource(temp);
    mergerUtility.addSource(destPdfPath);
    mergerUtility.setDestinationFileName(destPdfPath);
    mergerUtility.mergeDocuments();
}
 
Example 22
Project: testarea-pdfbox2   File: TestEmptySignatureField.java   Source Code and License Vote up 6 votes
/**
 * <a href="http://stackoverflow.com/questions/37601092/pdfbox-identify-specific-pages-and-functionalities-recommendations">
 * PDFBox identify specific pages and functionalities recommendations
 * </a>
 * 
 * <p>
 * This test shows how to add an empty signature field with a custom appearance
 * to an existing PDF.
 * </p>
 */
@Test
public void testAddEmptySignatureField() throws IOException
{
    try (   InputStream sourceStream = getClass().getResourceAsStream("test.pdf");
            OutputStream output = new FileOutputStream(new File(RESULT_FOLDER, "test-with-empty-sig-field.pdf")))
    {
        PDFont font = PDType1Font.HELVETICA;
        PDResources resources = new PDResources();
        resources.put(COSName.getPDFName("Helv"), font);

        PDDocument document = PDDocument.load(sourceStream);
        PDAcroForm acroForm = new PDAcroForm(document);
        acroForm.setDefaultResources(resources);
        document.getDocumentCatalog().setAcroForm(acroForm);

        PDRectangle rect = new PDRectangle(50, 750, 200, 50);

        PDAppearanceDictionary appearanceDictionary = new PDAppearanceDictionary();
        PDAppearanceStream appearanceStream = new PDAppearanceStream(document);
        appearanceStream.setBBox(rect.createRetranslatedRectangle());
        appearanceStream.setResources(resources);
        appearanceDictionary.setNormalAppearance(appearanceStream);
        PDPageContentStream contentStream = new PDPageContentStream(document, appearanceStream);
        contentStream.setStrokingColor(Color.BLACK);
        contentStream.setNonStrokingColor(Color.LIGHT_GRAY);
        contentStream.setLineWidth(2);
        contentStream.addRect(0, 0, rect.getWidth(), rect.getHeight());
        contentStream.fill();
        contentStream.moveTo(1 * rect.getHeight() / 4, 1 * rect.getHeight() / 4);
        contentStream.lineTo(2 * rect.getHeight() / 4, 3 * rect.getHeight() / 4);
        contentStream.moveTo(1 * rect.getHeight() / 4, 3 * rect.getHeight() / 4);
        contentStream.lineTo(2 * rect.getHeight() / 4, 1 * rect.getHeight() / 4);
        contentStream.moveTo(3 * rect.getHeight() / 4, 1 * rect.getHeight() / 4);
        contentStream.lineTo(rect.getWidth() - rect.getHeight() / 4, 1 * rect.getHeight() / 4);
        contentStream.stroke();
        contentStream.setNonStrokingColor(Color.DARK_GRAY);
        contentStream.beginText();
        contentStream.setFont(font, rect.getHeight() / 5);
        contentStream.newLineAtOffset(3 * rect.getHeight() / 4, -font.getBoundingBox().getLowerLeftY() * rect.getHeight() / 5000);
        contentStream.showText("Customer");
        contentStream.endText();
        contentStream.close();

        PDSignatureField signatureField = new PDSignatureField(acroForm);
        signatureField.setPartialName("SignatureField");
        PDPage page = document.getPage(0);

        PDAnnotationWidget widget = signatureField.getWidgets().get(0);
        widget.setAppearance(appearanceDictionary);
        widget.setRectangle(rect);
        widget.setPage(page);

        page.getAnnotations().add(widget);
        acroForm.getFields().add(signatureField);

        document.save(output);
        document.close();
    }
}
 
Example 23
Project: git-rekt   File: BillPdfGenerator.java   Source Code and License Vote up 5 votes
private void generateBillInfoText(PDPage firstPage, PDPageContentStream contentStream)
        throws IOException {
    Guest guest = booking.getGuest();
    String guestName = guest.getLastName() + ", " + guest.getFirstName();
    MailingAddress address = guest.getMailingAddress();
    String country = address.getCountry();
    String city = address.getCity();
    UsState state = address.getState();
    String postalCode = address.getPostalCode();
    String addressLine1 = address.getAddressLine1();
    String addressLine2 = address.getAddressLine2();

    contentStream.beginText();

    // Print customer name line
    contentStream.newLineAtOffset(80f, 710f);
    contentStream.setLeading(10);
    contentStream.setFont(BOLD, NORMAL_FONT_SIZE);
    contentStream.showText("Customer name: ");
    contentStream.setFont(NORMAL_FONT, NORMAL_FONT_SIZE);
    contentStream.showText(guestName);

    // Print customer mailing address lines
    contentStream.newLine();
    contentStream.setFont(BOLD, NORMAL_FONT_SIZE);
    contentStream.showText("Billing Address: ");
    contentStream.setFont(NORMAL_FONT, NORMAL_FONT_SIZE);
    contentStream.newLine();
    contentStream.showText(addressLine1);
    if(!addressLine2.isEmpty()) {
        contentStream.showText(",");
        contentStream.showText(addressLine2);
    }
    contentStream.newLine();
    contentStream.showText(city);
    if(state != null) {
        contentStream.showText(", " + state.getAbbreviation());
    }
    contentStream.showText(" " + postalCode);
    contentStream.showText(" - ");
    contentStream.showText(country);

    // Print booking number line
    contentStream.newLine();
    contentStream.setFont(BOLD, NORMAL_FONT_SIZE);
    contentStream.showText("Booking Number: ");
    contentStream.setFont(NORMAL_FONT, NORMAL_FONT_SIZE);
    contentStream.showText(booking.getId().toString());

    // Print bill printed info line
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("EEE, MMMM d, u '-' H:m:s zz");
    String formattedDate = formatter.format(ZonedDateTime.now(ZoneId.systemDefault()));
    contentStream.newLine();
    contentStream.setFont(BOLD, NORMAL_FONT_SIZE);
    contentStream.showText("Bill Printed On: ");
    contentStream.setFont(NORMAL_FONT, NORMAL_FONT_SIZE);
    contentStream.showText(formattedDate);

    contentStream.endText();

}
 
Example 24
Project: kumoreg   File: LiteBadgePrintFormatter.java   Source Code and License Vote up 5 votes
private PDPage generatePage(Attendee attendee, PDDocument document) throws IOException {
    PDPage page = new PDPage(new PDRectangle(612f, 396f));
    PDFont font = PDType1Font.HELVETICA_BOLD;
    PDPageContentStream contentStream = new PDPageContentStream(document, page);

    // Positions are measured from the bottom left corner of the page at 72 DPI

    // Draw real name
    contentStream.beginText();
    contentStream.moveTextPositionByAmount(220+xOffset, 175+yOffset);
    contentStream.setFont( font, 24 );
    contentStream.drawString(attendee.getFirstName() + " " + attendee.getLastName());
    contentStream.endText();

    // Draw age color stripe
    String stripeText = "VOID";
    if (attendee.getCurrentAgeRange() != null) {
        contentStream.setNonStrokingColor(Color.decode(attendee.getCurrentAgeRange().getStripeColor()));
        stripeText = attendee.getCurrentAgeRange().getStripeText();
    } else {
        contentStream.setNonStrokingColor(Color.black);
    }
    contentStream.fillRect(150+xOffset, 90+yOffset, 310, 44);

    contentStream.setLineWidth(0.5f);
    contentStream.beginText();
    contentStream.setFont(font, 24);
    contentStream.setNonStrokingColor(Color.white);
    contentStream.setStrokingColor(Color.black);
    contentStream.moveTextPositionByAmount(297+xOffset, 102+yOffset);
    contentStream.appendRawCommands("2 Tr ");       // Set text rendering mode

    Float ageRangeWidth = ((font.getStringWidth(stripeText) / 1000.0f) * 18) / 2;
    contentStream.moveTextPositionByAmount(-ageRangeWidth, 0);
    contentStream.drawString(stripeText);
    contentStream.endText();

    contentStream.close();

    return page;
}
 
Example 25
Project: kumoreg   File: AttendeeBadge2017.java   Source Code and License Vote up 5 votes
private void drawVerticalAgeRangeText(PDPage page, PDFont font, Attendee attendee) throws IOException {
    PDPageContentStream stream = new PDPageContentStream(document, page, PDPageContentStream.AppendMode.APPEND, true, false);
    stream.setLineWidth(0.5f);
    stream.beginText();
    stream.setFont(font, 30);

    String stripeColor = attendee.getCurrentAgeRange().getStripeColor();
    stream.setNonStrokingColor(BadgeLib.getForegroundColor(stripeColor));

    stream.newLineAtOffset(172, 275);   // First character position

    String ageString = BadgeLib.getAgeRangeAtCon(attendee, currentDateForAgeCalculation);
    if (ageString.toLowerCase().equals("adult")) {
        stream.showText("A");
        stream.newLineAtOffset(-1, -32);
        stream.showText("D");
        stream.newLineAtOffset(0, -32);
        stream.showText("U");
        stream.newLineAtOffset(2, -32);
        stream.showText("L");
        stream.newLineAtOffset(2, -32);
        stream.showText("T");
    } else if (ageString.toLowerCase().equals("youth")) {
        stream.showText("Y");
        stream.newLineAtOffset(-2, -32);
        stream.showText("O");
        stream.newLineAtOffset(0, -32);
        stream.showText("U");
        stream.newLineAtOffset(4, -32);
        stream.showText("T");
        stream.newLineAtOffset(-3, -32);
        stream.showText("H");
    } else if (ageString.toLowerCase().equals("child")) {
        stream.showText("C");
        stream.newLineAtOffset(0, -32);
        stream.showText("H");
        stream.newLineAtOffset(5, -32);
        stream.showText("I");
        stream.newLineAtOffset(-3, -32);
        stream.showText("L");
        stream.newLineAtOffset(-2, -32);
        stream.showText("D");
    } else {
        stream.showText("V");
        stream.newLineAtOffset(0, -32);
        stream.showText("O");
        stream.newLineAtOffset(5, -32);
        stream.showText("I");
        stream.newLineAtOffset(-5, -32);
        stream.showText("D");
    }
    stream.close();
}