Java Code Examples for org.apache.pdfbox.pdmodel.PDPageContentStream

The following are top voted examples for showing how to use org.apache.pdfbox.pdmodel.PDPageContentStream. 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: easytable   File: TableDrawerIntegrationTest.java   Source Code and License 12 votes vote down vote up
@Test
public void createAlternateRowsDocument() throws Exception {
    final PDDocument document = new PDDocument();
    final PDPage page = new PDPage(PDRectangle.A4);
    page.setRotation(90);
    document.addPage(page);
    final PDPageContentStream contentStream = new PDPageContentStream(document, page);
    // TODO replace deprecated method call
    contentStream.concatenate2CTM(0, 1, -1, 0, page.getMediaBox().getWidth(), 0);
    final float startY = page.getMediaBox().getWidth() - 30;

    (new TableDrawer(contentStream, createAndGetTableWithAlternatingColors(), 30, startY)).draw();
    contentStream.close();

    document.save("target/alternateRows.pdf");
    document.close();
}
 
Example 2
Project: easytable   File: TableDrawerIntegrationTest.java   Source Code and License 11 votes vote down vote up
@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 3
Project: esup-ecandidat   File: CandidatureController.java   Source Code and License 10 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 4
Project: pdfbox-graphics2d   File: PdfBoxGraphics2DFontTextDrawer.java   Source Code and License 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 5
Project: kumoreg   File: ReportPrintFormatter.java   Source Code and License 9 votes vote down vote up
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 6
Project: testarea-pdfbox2   File: RotatePageContent.java   Source Code and License 9 votes vote down vote up
/**
 * <a href="http://stackoverflow.com/questions/40611736/rotate-pdf-around-its-center-using-pdfbox-in-java">
 * Rotate PDF around its center using PDFBox in java
 * </a>
 * <p>
 * This test shows how to rotate the page content and then move its crop box and
 * media box accordingly to make it appear as if the content was rotated around
 * the center of the crop box.
 * </p>
 */
@Test
public void testRotateMoveBox() throws IOException
{
    try (   InputStream resource = getClass().getResourceAsStream("IRJET_Copy_Right_form.pdf")  )
    {
        PDDocument document = PDDocument.load(resource);
        PDPage page = document.getDocumentCatalog().getPages().get(0);
        PDPageContentStream cs = new PDPageContentStream(document, page, PDPageContentStream.AppendMode.PREPEND, false, false);
        Matrix matrix = Matrix.getRotateInstance(Math.toRadians(45), 0, 0);
        cs.transform(matrix);
        cs.close();

        PDRectangle cropBox = page.getCropBox();
        float cx = (cropBox.getLowerLeftX() + cropBox.getUpperRightX()) / 2;
        float cy = (cropBox.getLowerLeftY() + cropBox.getUpperRightY()) / 2;
        Point2D.Float newC = matrix.transformPoint(cx, cy);
        float tx = (float)newC.getX() - cx;
        float ty = (float)newC.getY() - cy;
        page.setCropBox(new PDRectangle(cropBox.getLowerLeftX() + tx, cropBox.getLowerLeftY() + ty, cropBox.getWidth(), cropBox.getHeight()));
        PDRectangle mediaBox = page.getMediaBox();
        page.setMediaBox(new PDRectangle(mediaBox.getLowerLeftX() + tx, mediaBox.getLowerLeftY() + ty, mediaBox.getWidth(), mediaBox.getHeight()));

        document.save(new File(RESULT_FOLDER, "IRJET_Copy_Right_form-rotated-move-box.pdf"));
    }
}
 
Example 7
Project: testarea-pdfbox2   File: RenderType3Character.java   Source Code and License 9 votes vote down vote up
/**
 * <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 8
Project: easytable   File: TableDrawerIntegrationTest.java   Source Code and License 8 votes vote down vote up
@Test
public void createSampleDocument() throws Exception {
    // Define the table structure first
    TableBuilder tableBuilder = new TableBuilder()
            .addColumnOfWidth(300)
            .addColumnOfWidth(120)
            .addColumnOfWidth(70)
            .setFontSize(8)
            .setFont(PDType1Font.HELVETICA);

    // Header ...
    tableBuilder.addRow(new RowBuilder()
            .add(Cell.withText("This is right aligned without a border").setHorizontalAlignment(RIGHT))
            .add(Cell.withText("And this is another cell"))
            .add(Cell.withText("Sum").setBackgroundColor(Color.ORANGE))
            .setBackgroundColor(Color.BLUE)
            .build());

    // ... and some cells
    for (int i = 0; i < 10; i++) {
        tableBuilder.addRow(new RowBuilder()
                .add(Cell.withText(i).withAllBorders())
                .add(Cell.withText(i * i).withAllBorders())
                .add(Cell.withText(i + (i * i)).withAllBorders())
                .setBackgroundColor(i % 2 == 0 ? Color.LIGHT_GRAY : Color.WHITE)
                .build());
    }

    final PDDocument document = new PDDocument();
    final PDPage page = new PDPage(PDRectangle.A4);
    document.addPage(page);

    final PDPageContentStream contentStream = new PDPageContentStream(document, page);

    // Define the starting point
    final float startY = page.getMediaBox().getHeight() - 50;
    final int startX = 50;

    // Draw!
    (new TableDrawer(contentStream, tableBuilder.build(), startX, startY)).draw();
    contentStream.close();

    document.save("target/sampleWithColorsAndBorders.pdf");
    document.close();
}
 
Example 9
Project: BoxTable   File: Table.java   Source Code and License 8 votes vote down vote up
/**
 * Renders this table to a document
 * 
 * @param document
 *            The document this table will be rendered to
 * @param width
 *            The width of the table
 * @param left
 *            The left edge of the table
 * @param top
 *            The top edge of the table
 * @param paddingTop
 *            The amount of free space at the top of a new page (if a page break is necessary)
 * @param paddingBottom
 *            The minimal amount of free space at the bottom of the page before inserting a page break
 * @return The bottom edge of the last rendered table part
 * @throws IOException
 *             If writing to the document fails
 */
@SuppressWarnings("resource")
public float render(final PDDocument document, final float width, final float left, float top, final float paddingTop, final float paddingBottom)
		throws IOException {
	float yPos = top;
	final PDPage page = document.getPage(document.getNumberOfPages() - 1);
	final PDRectangle pageSize = page.getMediaBox();
	PDPageContentStream stream = new PDPageContentStream(document, page, AppendMode.APPEND, true);
	float height = getHeight(width);
	if (height > pageSize.getHeight() - paddingTop - paddingBottom) {
		final float[] colWidths = getColumnWidths(width);
		for (int i = 0; i < rows.size(); ++i) {
			if (rows.get(i).getHeight(colWidths) > yPos - paddingBottom) {
				drawBorder(stream, left, top, width, top - yPos);
				stream = newPage(document, stream);
				top = pageSize.getHeight() - paddingTop;
				yPos = top;
				yPos = renderRows(document, stream, 0, getNumHeaderRows(), width, left, yPos);
				i = Math.max(i, getNumHeaderRows());
			}
			yPos = renderRows(document, stream, i, i + 1, width, left, yPos);
		}
		drawBorder(stream, left, top, width, top - yPos);

		handleEvent(EventType.AFTER_TABLE, document, stream, left, top, width, top - yPos);
	} else {
		if (height > top - paddingBottom) {
			stream = newPage(document, stream);
			top = pageSize.getHeight() - paddingTop;
			yPos = top;
		}
		yPos = renderRows(document, stream, 0, -1, width, left, yPos);
		drawBorder(stream, left, top, width, top - yPos);
		handleEvent(EventType.AFTER_TABLE, document, stream, left, top, width, top - yPos);
	}
	stream.close();

	return yPos;
}
 
Example 10
Project: pdfbox-graphics2d   File: MultiPageTest.java   Source Code and License 8 votes vote down vote up
@Test
public void testMultiPageJFreeChart() throws IOException {
	File parentDir = new File("target/test/multipage");
	// noinspection ResultOfMethodCallIgnored
	parentDir.mkdirs();
	File targetPDF = new File(parentDir, "multipage.pdf");
	PDDocument document = new PDDocument();
	for (int i = 0; i < 4; i++) {
		PDPage page = new PDPage(PDRectangle.A4);
		document.addPage(page);

		PDPageContentStream contentStream = new PDPageContentStream(document, page);
		PdfBoxGraphics2D pdfBoxGraphics2D = new PdfBoxGraphics2D(document, 800, 400);
		drawOnGraphics(pdfBoxGraphics2D, i);
		pdfBoxGraphics2D.dispose();

		PDFormXObject appearanceStream = pdfBoxGraphics2D.getXFormObject();
		Matrix matrix = new Matrix();
		matrix.translate(0, 30);
		matrix.scale(0.7f, 1f);

		contentStream.saveGraphicsState();
		contentStream.transform(matrix);
		contentStream.drawForm(appearanceStream);
		contentStream.restoreGraphicsState();

		contentStream.close();
	}
	document.save(targetPDF);
	document.close();
}
 
Example 11
Project: git-rekt   File: BillPdfGenerator.java   Source Code and License 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 12
Project: melon   File: PdfDemo.java   Source Code and License 8 votes vote down vote up
@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 13
Project: pcm-api   File: PdfBoxServiceImpl.java   Source Code and License 8 votes vote down vote up
@Override
public void addWrappedParagraph(String text, PDFont font, float fontSize, Color textColor, TextAlignment align, float xCoordinate, float topYCoordinate, float width, PDPage page, PDPageContentStream contentStream) throws IOException {
    Paragraph paragraph = new Paragraph(text, width, font, fontSize);

    final float lineSpacing = 1.2f * fontSize;
    PDRectangle region = page.getMediaBox();

    contentStream.beginText();
    contentStream.setFont(font, fontSize);
    contentStream.setNonStrokingColor(textColor);
    for (String line : paragraph.getLines()) {
        if (align == TextAlignment.CENTER) {
            float stringWidth = PdfBoxHandler.targetedStringWidth(line, font, fontSize);
            float centerXPos = (region.getWidth() - stringWidth) / 2f;
            contentStream.setTextTranslation(centerXPos, region.getHeight() - topYCoordinate);
        } else {
            contentStream.setTextTranslation(xCoordinate, region.getHeight() - topYCoordinate);
        }
        contentStream.showText(line);
        topYCoordinate += lineSpacing;
    }
    contentStream.endText();
    resetChangedColorToDefault(contentStream);
}
 
Example 14
Project: testarea-pdfbox2   File: RotatePageContent.java   Source Code and License 8 votes vote down vote up
/**
 * <a href="http://stackoverflow.com/questions/40611736/rotate-pdf-around-its-center-using-pdfbox-in-java">
 * Rotate PDF around its center using PDFBox in java
 * </a>
 * <p>
 * This test shows how to rotate the page content around the center of its crop box.
 * </p>
 */
@Test
public void testRotateCenter() throws IOException
{
    try (   InputStream resource = getClass().getResourceAsStream("IRJET_Copy_Right_form.pdf")  )
    {
        PDDocument document = PDDocument.load(resource);
        PDPage page = document.getDocumentCatalog().getPages().get(0);
        PDPageContentStream cs = new PDPageContentStream(document, page, PDPageContentStream.AppendMode.PREPEND, false, false); 
        PDRectangle cropBox = page.getCropBox();
        float tx = (cropBox.getLowerLeftX() + cropBox.getUpperRightX()) / 2;
        float ty = (cropBox.getLowerLeftY() + cropBox.getUpperRightY()) / 2;
        cs.transform(Matrix.getTranslateInstance(tx, ty));
        cs.transform(Matrix.getRotateInstance(Math.toRadians(45), 0, 0));
        cs.transform(Matrix.getTranslateInstance(-tx, -ty));
        cs.close();
        document.save(new File(RESULT_FOLDER, "IRJET_Copy_Right_form-rotated-center.pdf"));
    }
}
 
Example 15
Project: testarea-pdfbox2   File: RotatePageContent.java   Source Code and License 8 votes vote down vote up
/**
 * <a href="http://stackoverflow.com/questions/40611736/rotate-pdf-around-its-center-using-pdfbox-in-java">
 * Rotate PDF around its center using PDFBox in java
 * </a>
 * <p>
 * This test shows how to rotate the page content around the center of its crop box
 * and then crop it to make all previously visible content fit.
 * </p>
 */
@Test
public void testRotateCenterScale() throws IOException
{
    try (   InputStream resource = getClass().getResourceAsStream("IRJET_Copy_Right_form.pdf")  )
    {
        PDDocument document = PDDocument.load(resource);
        PDPage page = document.getDocumentCatalog().getPages().get(0);
        PDPageContentStream cs = new PDPageContentStream(document, page, PDPageContentStream.AppendMode.PREPEND, false, false);

        Matrix matrix = Matrix.getRotateInstance(Math.toRadians(45), 0, 0);
        PDRectangle cropBox = page.getCropBox();
        float tx = (cropBox.getLowerLeftX() + cropBox.getUpperRightX()) / 2;
        float ty = (cropBox.getLowerLeftY() + cropBox.getUpperRightY()) / 2;

        Rectangle rectangle = cropBox.transform(matrix).getBounds();
        float scale = Math.min(cropBox.getWidth() / (float)rectangle.getWidth(), cropBox.getHeight() / (float)rectangle.getHeight());

        cs.transform(Matrix.getTranslateInstance(tx, ty));
        cs.transform(matrix);
        cs.transform(Matrix.getScaleInstance(scale, scale));
        cs.transform(Matrix.getTranslateInstance(-tx, -ty));
        cs.close();
        document.save(new File(RESULT_FOLDER, "IRJET_Copy_Right_form-rotated-center-scale.pdf"));
    }
}
 
Example 16
Project: testarea-pdfbox2   File: RenderType3Character.java   Source Code and License 8 votes vote down vote up
/**
 * <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 testRender4700198773() throws IOException
{
    try (   InputStream resource = getClass().getResourceAsStream("4700198773.pdf"))
    {
        PDDocument document = PDDocument.load(resource);

        PDPage page = document.getPage(0);
        PDResources pageResources = page.getResources();
        COSName f1Name = COSName.getPDFName("F1");
        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("4700198773-%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("4700198773-%s-%s.pdf", key.getName(), code)));
                charDocument.close();
            }
        }
    }
}
 
Example 17
Project: pdfbox-graphics2d   File: PdfBoxGraphics2DPaintApplier.java   Source Code and License 7 votes vote down vote up
@Override
public PDShading applyPaint(Paint paint, PDPageContentStream contentStream, AffineTransform tf, IPaintEnv env)
		throws IOException {
	this.document = env.getDocument();
	this.resources = env.getResources();
	this.contentStream = contentStream;
	this.colorMapper = env.getColorMapper();
	this.imageEncoder = env.getImageEncoder();
	this.composite = env.getComposite();
	this.pdExtendedGraphicsState = null;
	PDShading shading = applyPaint(paint, tf);
	if (pdExtendedGraphicsState != null)
		contentStream.setGraphicsStateParameters(extGStateCache.makeUnqiue(pdExtendedGraphicsState));
	return shading;
}
 
Example 18
Project: PrintDF   File: BookletMaker.java   Source Code and License 7 votes vote down vote up
/**
 * Creates a pdf page from two pages from another 'original' pdf document
 * @param doc original pdf from which the pages will be taken
 * @param leftPage page number of the page to go on the left side 
 * @param rightPage page number of the page to go on the right side
 * @return generated page containing the left and right pages from the original document side-by-side.
 */
private static PDPage createBookPage(PDDocument doc, int leftPage, int rightPage) {
	// double the width of a normal page to create the booklet
	PDRectangle baseSize = doc.getPage(0).getMediaBox();		
	PDRectangle box = new PDRectangle(baseSize.getWidth()*2, baseSize.getHeight());
	

	if(sizeOverride != null) {
		box = sizeOverride.asPDRectangle();
	}
	
	PDPage page = new PDPage(box);
	
	try {
		PDImageXObject leftImg = PrintDF.pageToImage(doc, leftPage, scale);
		PDImageXObject rightImg = PrintDF.pageToImage(doc, rightPage, scale);
		
		
		
		PDPageContentStream contentStream = new PDPageContentStream(doc, page);
		if(leftImg != null)
			contentStream.drawImage(leftImg, 0, 0, box.getWidth()/2, box.getHeight());
		if(rightImg != null)
			contentStream.drawImage(rightImg, box.getWidth()/2, 0, box.getWidth()/2, box.getHeight());
		contentStream.close();
	} catch (IOException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
	
	return page;
}
 
Example 19
Project: FYS_T3   File: statisticsController.java   Source Code and License 7 votes vote down vote up
@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 20
Project: kumoreg   File: StaffBadge2017.java   Source Code and License 7 votes vote down vote up
private void drawAgeImageFront(PDPage page, Attendee attendee) throws IOException {

        String imageFilename = BadgeLib.getStaffAgeImageFilename(attendee, currentDateForAgeCalculation);
        if (imageFilename == null) { return; }

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

        PDImageXObject xImage = PDImageXObject.createFromFile(imageFilename, document);
        Dimension scaledDim = getScaledDimension(
                new Dimension(xImage.getWidth(),  xImage.getHeight()),
                new Dimension(149, 130));
        stream.drawImage(xImage,
                45 + ((149-scaledDim.width)/2),
                335 + ((158-scaledDim.height)/2),
                scaledDim.width, scaledDim.height);
        stream.close();
    }
 
Example 21
Project: kumoreg   File: StaffBadge2017.java   Source Code and License 7 votes vote down vote up
private void drawAgeImageBack(PDPage page, Attendee attendee) throws IOException {
    String imageFilename = BadgeLib.getStaffAgeImageFilename(attendee, currentDateForAgeCalculation);
    if (imageFilename == null) { return; }

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

    PDImageXObject xImage = PDImageXObject.createFromFile(imageFilename, document);
    Dimension scaledDim = getScaledDimension(
            new Dimension(xImage.getWidth(),  xImage.getHeight()),
            new Dimension(149, 115));
    stream.drawImage(xImage,
            201 + ((149-scaledDim.width)/2),
            344 + ((158-scaledDim.height)/2),
            scaledDim.width, scaledDim.height);
    stream.close();
}
 
Example 22
Project: kumoreg   File: FullBadgePrintFormatter.java   Source Code and License 7 votes vote down vote up
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 23
Project: testarea-pdfbox2   File: JoinPages.java   Source Code and License 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 = 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 24
Project: pcm-api   File: PdfBoxServiceImpl.java   Source Code and License 7 votes vote down vote up
@Override
public void addWrappedParagraphByLineBreaks(String content, PDFont font, float fontSize, Color textColor, float yCoordinate, float leftRightMargin, PDPage page, PDPageContentStream contentStream) throws IOException {
    final float lineSpacing = 1.4f * fontSize;
    float width = page.getMediaBox().getWidth() - 2 * leftRightMargin;
    float startX = page.getMediaBox().getLowerLeftX() + leftRightMargin;

    List<String> lines = calculateLinesToWrap(content, font, fontSize, width);

    contentStream.beginText();
    contentStream.setFont(font, fontSize);
    contentStream.setNonStrokingColor(textColor);
    contentStream.newLineAtOffset(startX, yCoordinate);
    for (String line : lines) {
        contentStream.showText(line.replaceAll(PdfBoxHandler.TAB_REGEX, PdfBoxHandler.SPACE_STRING));
        contentStream.newLineAtOffset(0, -lineSpacing);
    }
    contentStream.endText();

    // Reset changed color
    resetChangedColorToDefault(contentStream);
}
 
Example 25
Project: pcm-api   File: PdfBoxServiceImpl.java   Source Code and License 7 votes vote down vote up
private void fillTextToTable(PDPageContentStream contentStream, TableAttribute tableAttribute, String[][] tableContent) throws IOException {
    //Set text font and font size
    contentStream.setFont(tableAttribute.getContentFont(), tableAttribute.getContentFontSize());

    final float cellMargin = tableAttribute.getCellMargin();
    // Define to start drawing content at horizontal position
    float nextTextX = tableAttribute.getXCoordinate() + cellMargin;
    // Define to start drawing content at vertical position
    float nextTextY = calculateDrawPositionInVertical(tableAttribute);

    for (String[] aContent : tableContent) {
        int index = 0;
        for (String text : aContent) {
            contentStream.beginText();
            contentStream.newLineAtOffset(nextTextX, nextTextY);
            contentStream.showText(text != null ? text : "");
            contentStream.endText();
            nextTextX += tableAttribute.getColumns().get(index).getCellWidth();
            index++;
        }
        // Update new position cursor after writing the content for one row
        nextTextY -= tableAttribute.getRowHeight();
        nextTextX = tableAttribute.getXCoordinate() + cellMargin;
    }
}
 
Example 26
Project: testarea-pdfbox2   File: JoinPages.java   Source Code and License 7 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 = 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 27
Project: pcm-api   File: ConsentPdfGeneratorImpl.java   Source Code and License 7 votes vote down vote up
private void addProviderDisclosureIsMadeTo(Consent consent, List<Column> tableColumns, float startYCoordinate, PDFont font, PDPage page, PDPageContentStream contentStream) throws IOException {
    String label = getI18nMessage("CONSENT.PDF.SECTION1.CONTENT2");
    addAuthorizationTableHeader(label, startYCoordinate, tableColumns, font, contentStream);

    // To providers details
    final float toProviderDetailsYCoordinate = 342f;
    Set<OrganizationalProvider> fromOrganizations = consent.getOrganizationalProvidersDisclosureIsMadeTo().stream()
            .map(ConsentOrganizationalProviderDisclosureIsMadeTo::getOrganizationalProvider)
            .collect(Collectors.toSet());

    Set<IndividualProvider> fromPractitioners = consent.getProvidersDisclosureIsMadeTo().stream()
            .map(ConsentIndividualProviderDisclosureIsMadeTo::getIndividualProvider)
            .collect(Collectors.toSet());

    addConsentProvidersDetails(fromOrganizations, fromPractitioners, tableColumns, toProviderDetailsYCoordinate, page, contentStream);
}
 
Example 28
Project: pcm-api   File: ConsentPdfGeneratorImpl.java   Source Code and License 7 votes vote down vote up
private void drawSectionHeader(String title, float cardXCoordinate, float cardYCoordinate, PDPage page, PDPageContentStream contentStream) throws IOException {
    // Set background color
    Color color = new Color(73, 89, 105);
    float colorBoxWidth = page.getMediaBox().getWidth() - 2 * PdfBoxStyle.LEFT_RIGHT_MARGINS_OF_LETTER;
    float colorBoxHeight = PdfBoxStyle.DEFAULT_TABLE_ROW_HEIGHT;
    PDFont titleFont = PDType1Font.TIMES_BOLD;
    float titleFontSize = PdfBoxStyle.TEXT_MEDIUM_SIZE;
    Color titleColor = Color.WHITE;

    pdfBoxService.addColorBox(color, cardXCoordinate, cardYCoordinate, colorBoxWidth, colorBoxHeight, page, contentStream);

    float titleYCoordinate = cardYCoordinate + (colorBoxHeight / 2)
            - ((titleFont.getFontDescriptor().getFontBoundingBox().getHeight() / 1000 * titleFontSize) / 4);

    pdfBoxService.addTextAtOffset(title, titleFont, titleFontSize, titleColor, cardXCoordinate + 4f, titleYCoordinate, contentStream);
}
 
Example 29
Project: testarea-pdfbox2   File: RectanglesOverText.java   Source Code and License 7 votes vote down vote up
/**
 * <a href="https://stackoverflow.com/questions/46080131/text-coordinates-when-stripping-from-pdfbox">
 * Text coordinates when stripping from PDFBox
 * </a>
 * <br/>
 * <a href="https://download-a.akamaihd.net/files/media_mwb/b7/mwb_I_201711.pdf">
 * mwb_I_201711.pdf
 * </a>
 * <p>
 * This test applies the OP's code to his example PDF file and indeed, there is an offset!
 * This is due to the <code>LegacyPDFStreamEngine</code> method <code>showGlyph</code>
 * which manipulates the text rendering matrix to make the lower left corner of the
 * crop box the origin. In the current version of this test, that offset is corrected,
 * see below. 
 * </p>
 */
@Test
public void testCoverTextByRectanglesMwbI201711() throws IOException {
    try (   InputStream resource = getClass().getResourceAsStream("mwb_I_201711.pdf")  ) {
        PDDocument doc = PDDocument.load(resource);

        myStripper stripper = new myStripper();

        stripper.setStartPage(1); // fix it to first page just to test it
        stripper.setEndPage(1);
        stripper.getText(doc);

        TextLine line = stripper.lines.get(1); // the line i want to paint on

        float minx = -1;
        float maxx = -1;

        for (TextPosition pos: line.textPositions)
        {
            if (pos == null)
                continue;

            if (minx == -1 || pos.getTextMatrix().getTranslateX() < minx) {
                minx = pos.getTextMatrix().getTranslateX();
            }
            if (maxx == -1 || pos.getTextMatrix().getTranslateX() > maxx) {
                maxx = pos.getTextMatrix().getTranslateX();
            }
        }

        TextPosition firstPosition = line.textPositions.get(0);
        TextPosition lastPosition = line.textPositions.get(line.textPositions.size() - 1);

        // corrected x and y
        PDRectangle cropBox = doc.getPage(0).getCropBox();

        float x = minx + cropBox.getLowerLeftX();
        float y = firstPosition.getTextMatrix().getTranslateY() + cropBox.getLowerLeftY();
        float w = (maxx - minx) + lastPosition.getWidth();
        float h = lastPosition.getHeightDir();

        PDPageContentStream contentStream = new PDPageContentStream(doc, doc.getPage(0), PDPageContentStream.AppendMode.APPEND, false, true);

        contentStream.setNonStrokingColor(Color.RED);
        contentStream.addRect(x, y, w, h);
        contentStream.fill();
        contentStream.close();

        File fileout = new File(RESULT_FOLDER, "mwb_I_201711-withRectangles.pdf");
        doc.save(fileout);
        doc.close();
    }
}
 
Example 30
Project: pdfbox-graphics2d   File: PdfBoxGraphics2D.java   Source Code and License 6 votes vote down vote up
/**
 * @param document
 *            The document the graphics should be used to create a XForm in.
 * @param bbox
 *            Bounding Box of the graphics
 * @throws IOException
 *             when something goes wrong with writing into the content
 *             stream of the {@link PDDocument}.
 */
public PdfBoxGraphics2D(PDDocument document, PDRectangle bbox) throws IOException {
	this.document = document;
	this.bbox = bbox;

	PDAppearanceStream appearance = new PDAppearanceStream(document);
	xFormObject = appearance;
	xFormObject.setResources(new PDResources());
	xFormObject.setBBox(bbox);
	contentStream = new PDPageContentStream(document, appearance, xFormObject.getStream().createOutputStream(COSName.FLATE_DECODE));
	contentStreamSaveState();

	baseTransform = new AffineTransform();
	baseTransform.translate(0, bbox.getHeight());
	baseTransform.scale(1, -1);

	calcImage = new BufferedImage(100, 100, BufferedImage.TYPE_4BYTE_ABGR);
	calcGfx = calcImage.createGraphics();
	font = calcGfx.getFont();
	cloneInfo = null;
}
 
Example 31
Project: pdfbox-graphics2d   File: PdfBoxGraphics2DFontTextDrawer.java   Source Code and License 6 votes vote down vote up
@Override
public void drawText(AttributedCharacterIterator iterator, IFontTextDrawerEnv env)
		throws IOException, FontFormatException {
	PDPageContentStream contentStream = env.getContentStream();

	contentStream.beginText();

	Matrix textMatrix = new Matrix();
	textMatrix.scale(1, -1);
	contentStream.setTextMatrix(textMatrix);

	StringBuilder sb = new StringBuilder();
	boolean run = true;
	while (run) {

		Font attributeFont = (Font) iterator.getAttribute(TextAttribute.FONT);
		if (attributeFont == null)
			attributeFont = env.getFont();

		Number fontSize = ((Number) iterator.getAttribute(TextAttribute.SIZE));
		if (fontSize != null)
			attributeFont = attributeFont.deriveFont(fontSize.floatValue());
		PDFont font = applyFont(attributeFont, env);

		Paint paint = (Paint) iterator.getAttribute(TextAttribute.FOREGROUND);
		if (paint == null)
			paint = env.getPaint();

		/*
		 * Apply the paint
		 */
		env.applyPaint(paint);

		boolean isStrikeThrough = TextAttribute.STRIKETHROUGH_ON
				.equals(iterator.getAttribute(TextAttribute.STRIKETHROUGH));
		boolean isUnderline = TextAttribute.UNDERLINE_ON.equals(iterator.getAttribute(TextAttribute.UNDERLINE));
		boolean isLigatures = TextAttribute.LIGATURES_ON.equals(iterator.getAttribute(TextAttribute.LIGATURES));

		run = iterateRun(iterator, sb);
		String text = sb.toString();

		/*
		 * If we force the text write we may encounter situations where the font can not
		 * display the characters. PDFBox will throw an exception in this case. We will
		 * just silently ignore the text and not display it instead.
		 */
		try {
			showTextOnStream(env, contentStream, attributeFont, font, isStrikeThrough, isUnderline, isLigatures,
					text);
		} catch (IllegalArgumentException e) {
			if (font instanceof PDType1Font && !font.isEmbedded()) {
				/*
				 * We tried to use a builtin default font, but it does not have the needed
				 * characters. So we use a embedded font as fallback.
				 */
				try {
					if (fallbackFontUnknownEncodings == null)
						fallbackFontUnknownEncodings = findFallbackFont(env);
					if (fallbackFontUnknownEncodings != null) {
						env.getContentStream().setFont(fallbackFontUnknownEncodings, attributeFont.getSize2D());
						showTextOnStream(env, contentStream, attributeFont, fallbackFontUnknownEncodings,
								isStrikeThrough, isUnderline, isLigatures, text);
						e = null;
					}
				} catch (IllegalArgumentException ignored) {
					e = ignored;
				}
			}

			if (e != null)
				System.err.println("PDFBoxGraphics: Can not map text " + text + " with font "
						+ attributeFont.getFontName() + ": " + e.getMessage());
		}
	}
	contentStream.endText();
}
 
Example 32
Project: pdfbox-graphics2d   File: PdfBoxGraphics2DPaintApplier.java   Source Code and License 6 votes vote down vote up
private void applyTexturePaint(TexturePaint texturePaint) throws IOException {
	Rectangle2D anchorRect = texturePaint.getAnchorRect();
	PDTilingPattern pattern = new PDTilingPattern();
	pattern.setPaintType(PDTilingPattern.PAINT_COLORED);
	pattern.setTilingType(PDTilingPattern.TILING_CONSTANT_SPACING_FASTER_TILING);

	pattern.setBBox(new PDRectangle((float) anchorRect.getX(), (float) anchorRect.getY(),
			(float) anchorRect.getWidth(), (float) anchorRect.getHeight()));
	pattern.setXStep((float) anchorRect.getWidth());
	pattern.setYStep((float) anchorRect.getHeight());

	AffineTransform patternTransform = new AffineTransform();
	patternTransform.translate(0, anchorRect.getHeight());
	patternTransform.scale(1f, -1f);
	pattern.setMatrix(patternTransform);

	PDAppearanceStream appearance = new PDAppearanceStream(document);
	appearance.setResources(pattern.getResources());
	appearance.setBBox(pattern.getBBox());

	PDPageContentStream imageContentStream = new PDPageContentStream(document, appearance,
			((COSStream) pattern.getCOSObject()).createOutputStream());
	BufferedImage texturePaintImage = texturePaint.getImage();
	PDImageXObject imageXObject = imageEncoder.encodeImage(document, imageContentStream, texturePaintImage);

	float ratioW = (float) ((anchorRect.getWidth()) / texturePaintImage.getWidth());
	float ratioH = (float) ((anchorRect.getHeight()) / texturePaintImage.getHeight());
	float paintHeight = (texturePaintImage.getHeight()) * ratioH;
	imageContentStream.drawImage(imageXObject, (float) anchorRect.getX(), (float) (paintHeight + anchorRect.getY()),
			texturePaintImage.getWidth() * ratioW, -paintHeight);
	imageContentStream.close();

	PDColorSpace patternCS1 = new PDPattern(null, imageXObject.getColorSpace());
	COSName tilingPatternName = resources.add(pattern);
	PDColor patternColor = new PDColor(tilingPatternName, patternCS1);

	contentStream.setNonStrokingColor(patternColor);
	contentStream.setStrokingColor(patternColor);
}
 
Example 33
Project: pdfbox-graphics2d   File: PdfBoxGraphics2DTestBase.java   Source Code and License 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 34
Project: git-rekt   File: BillPdfGenerator.java   Source Code and License 6 votes vote down vote up
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 35
Project: oma-riista-web   File: HunterPaymentPdfFeature.java   Source Code and License 6 votes vote down vote up
public PaymentPdfBuilder barCode(final String barCodeMessage,
                                 final float x,
                                 final float y) throws IOException {
    final float scale = 100f / BAR_CODE_DPI;
    final Code128Bean code128Bean = new Code128Bean();
    code128Bean.setCodeset(Code128Constants.CODESET_C);
    code128Bean.setMsgPosition(HumanReadablePlacement.HRP_NONE);
    code128Bean.setBarHeight(scale * BAR_CODE_HEIGHT_MM);

    final BitmapCanvasProvider canvas = new BitmapCanvasProvider(
            BAR_CODE_DPI, BufferedImage.TYPE_BYTE_BINARY, false, 0);
    code128Bean.generateBarcode(canvas, barCodeMessage);
    canvas.finish();

    final PDImageXObject pdImage = LosslessFactory.createFromImage(pdfDocument, canvas.getBufferedImage());

    try (final PDPageContentStream contentStream = new PDPageContentStream(
            pdfDocument, pdfDocument.getPage(0), PDPageContentStream.AppendMode.APPEND, true)) {
        contentStream.drawImage(pdImage, x, y, scale * pdImage.getWidth(), scale * pdImage.getHeight());
    }

    return this;
}
 
Example 36
Project: kumoreg   File: StaffBadge2017.java   Source Code and License 6 votes vote down vote up
private void drawDepartmentBackgroundColorFront(PDPage page, Attendee attendee) throws IOException {
    PDPageContentStream stream = new PDPageContentStream(document, page, PDPageContentStream.AppendMode.APPEND, true, false);
    stream.setNonStrokingColor(Color.decode(attendee.getStaffDepartmentColor()));
    stream.setStrokingColor(Color.decode(attendee.getStaffDepartmentColor()));
    stream.addRect(306, 144, 45, 387);  // Left hand vertical
    stream.fill();
    stream.close();
}
 
Example 37
Project: kumoreg   File: StaffBadge2017.java   Source Code and License 6 votes vote down vote up
private void drawDepartmentBackgroundColorBack(PDPage page, Attendee attendee) throws IOException {
    PDPageContentStream stream = new PDPageContentStream(document, page, PDPageContentStream.AppendMode.APPEND, true, false);
    stream.setStrokingColor(Color.decode(attendee.getStaffDepartmentColor()));
    stream.setNonStrokingColor(Color.decode(attendee.getStaffDepartmentColor()));
    stream.addRect(45, 144, 45, 387);  // Left hand vertical
    stream.fill();
    stream.close();
}
 
Example 38
Project: kumoreg   File: StaffBadge2017.java   Source Code and License 6 votes vote down vote up
private void drawName(PDPage page, Attendee attendee) throws IOException {
    // Name bounding box:
    //         stream.fillRect(105, 152, 190, 63);

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

    ResizeOptions opts = new ResizeOptions();
    opts.centered = true;
    opts.font = bankGothic;
    opts.lines = 2;
    opts.maxTextWidth = 190;
    opts.minFontSize = 8;
    opts.size = 36;

    drawStringWithResizing(stream, 200, 190, attendee.getFirstName(), opts);
    drawStringWithResizing(stream, 200, 160, attendee.getLastName(), opts);
    stream.close();
}
 
Example 39
Project: kumoreg   File: StaffBadge2017.java   Source Code and License 6 votes vote down vote up
private void drawNameBack(PDPage page, Attendee attendee) throws IOException {
    // Name bounding box:
    //         stream.fillRect(105, 152, 190, 63);

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

    ResizeOptions opts = new ResizeOptions();
    opts.centered = true;
    opts.font = bankGothic;
    opts.lines = 2;
    opts.maxTextWidth = 190;
    opts.minFontSize = 8;
    opts.size = 36;

    drawStringWithResizing(stream, 195, 190, attendee.getFirstName(), opts);
    drawStringWithResizing(stream, 195, 160, attendee.getLastName(), opts);
    stream.close();
}
 
Example 40
Project: kumoreg   File: StaffBadge2017.java   Source Code and License 6 votes vote down vote up
private void drawImage(PDPage page, Attendee attendee) throws IOException {
        String imageFilename = BadgeLib.getStaffImageFilename(attendee);
        if (imageFilename == null) {
            imageFilename = BadgeLib.getMascotImageFilename();
        }

        PDImageXObject xImage;
        try (PDPageContentStream stream = new PDPageContentStream(document, page, PDPageContentStream.AppendMode.APPEND, true, false)) {
            xImage = PDImageXObject.createFromFile(imageFilename, document);
            Dimension scaledDim = getScaledDimension(
                    new Dimension(xImage.getWidth(),  xImage.getHeight()),
                    new Dimension(149, 158));
            stream.drawImage(xImage,
                    150 + ((149-scaledDim.width)/2),
                    334 + ((158-scaledDim.height)/2),
                    scaledDim.width, scaledDim.height);
//            stream.fillRect(150, 334, 149, 158);
            stream.close();
        } catch (IIOException ex) {
            System.out.println("Error opening " + imageFilename);
        }
    }
 
Example 41
Project: kumoreg   File: FormatterBase.java   Source Code and License 6 votes vote down vote up
/**
     * 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 42
Project: kumoreg   File: AttendeeBadge2017.java   Source Code and License 6 votes vote down vote up
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 43
Project: kumoreg   File: AttendeeBadge2017.java   Source Code and License 6 votes vote down vote up
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 44
Project: kumoreg   File: AttendeeBadge2017.java   Source Code and License 6 votes vote down vote up
private void drawAgeColorStripe(PDPage page, Attendee attendee) throws IOException {
    PDPageContentStream stream = new PDPageContentStream(document, page, PDPageContentStream.AppendMode.APPEND, true, false);
    // This only needs to be set once in the page to set the global offset.
    stream.concatenate2CTM(1, 0, 0, 1, xOffset, yOffset);

    if (attendee.getCurrentAgeRange() != null) {
        stream.setNonStrokingColor(Color.decode(attendee.getCurrentAgeRange().getStripeColor()));
    } else {
        stream.setNonStrokingColor(Color.black);
    }
    stream.addRect(160, 85, 46, 230);
    stream.fill();
    stream.close();
}
 
Example 45
Project: kumoreg   File: FullBadgePrintFormatter.java   Source Code and License 6 votes vote down vote up
/**
 * 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 46
Project: kumoreg   File: FullBadgePrintFormatter.java   Source Code and License 6 votes vote down vote up
private PDPage generateAttendeePage(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

    // Set up global transformation matrix according to xOffset, yOffset.
    // NOTE: if we want to support per-printer/per-client scaling, we would replace the 1's
    // below, with xScale and yScale.
    contentStream.concatenate2CTM(1, 0, 0, 1, xOffset, yOffset);

    // Draw fields on badge depending on badge type
    drawStaffNames(contentStream, attendee);
    drawBadgeNumber(contentStream, attendee);
    drawAgeColorStripe(contentStream, font, attendee);
    drawBadgeType(contentStream, attendee);
    contentStream.close();

    return page;
}
 
Example 47
Project: kumoreg   File: FullBadgePrintFormatter.java   Source Code and License 6 votes vote down vote up
private void drawBadgeType(PDPageContentStream contentStream, Attendee attendee) throws IOException {
    // Draw badge type in color stripe
    contentStream.beginText();
    contentStream.moveTextPositionByAmount(167, 105);
    contentStream.drawString(attendee.getBadge().getBadgeTypeText());
    contentStream.endText();
}
 
Example 48
Project: testarea-pdfbox2   File: RotatePageContent.java   Source Code and License 6 votes vote down vote up
/**
 * <a href="http://stackoverflow.com/questions/40611736/rotate-pdf-around-its-center-using-pdfbox-in-java">
 * Rotate PDF around its center using PDFBox in java
 * </a>
 * <p>
 * This test shows how to rotate the page content and then set the crop
 * box and media box to the bounding rectangle of the rotated page area.
 * </p>
 */
@Test
public void testRotateExpandBox() throws IOException
{
    try (   InputStream resource = getClass().getResourceAsStream("IRJET_Copy_Right_form.pdf")  )
    {
        PDDocument document = PDDocument.load(resource);
        PDPage page = document.getDocumentCatalog().getPages().get(0);
        PDPageContentStream cs = new PDPageContentStream(document, page, PDPageContentStream.AppendMode.PREPEND, false, false);
        Matrix matrix = Matrix.getRotateInstance(Math.toRadians(45), 0, 0);
        cs.transform(matrix);
        cs.close();

        PDRectangle cropBox = page.getCropBox();
        Rectangle rectangle = cropBox.transform(matrix).getBounds();
        PDRectangle newBox = new PDRectangle((float)rectangle.getX(), (float)rectangle.getY(), (float)rectangle.getWidth(), (float)rectangle.getHeight());
        page.setCropBox(newBox);
        page.setMediaBox(newBox);

        document.save(new File(RESULT_FOLDER, "IRJET_Copy_Right_form-rotated-expand-box.pdf"));
    }
}
 
Example 49
Project: testarea-pdfbox2   File: PlaceRotatedImage.java   Source Code and License 6 votes vote down vote up
/**
 * <a href="https://stackoverflow.com/questions/47383506/pdfbox-obtain-bounding-box-of-rotated-image">
 * PDFBox - obtain bounding box of rotated image
 * </a>
 * <p>
 * This test demonstrates how to position images given their dimensions,
 * rotation angle, and the coordinates of the lower left corner of their
 * bounding box. The work horse is {@link #placeImage(PDDocument, PDPage,
 * PDImageXObject, float, float, float, float, float)}. 
 * </p>
 */
@Test
public void testPlaceByBoundingBox() throws IOException {
    try (   InputStream resource = getClass().getResourceAsStream("Willi-1.jpg");
            PDDocument document = new PDDocument()  ) {
        PDPage page = new PDPage();
        document.addPage(page);

        PDRectangle mediaBox = page.getMediaBox();
        float bbLowerLeftX = 50;
        float bbLowerLeftY = 100;

        try (   PDPageContentStream contentStream = new PDPageContentStream(document, page)   ) {
            contentStream.moveTo(bbLowerLeftX, mediaBox.getLowerLeftY());
            contentStream.lineTo(bbLowerLeftX, mediaBox.getUpperRightY());
            contentStream.moveTo(mediaBox.getLowerLeftX(), bbLowerLeftY);
            contentStream.lineTo(mediaBox.getUpperRightX(), bbLowerLeftY);
            contentStream.stroke();
        }

        PDImageXObject image = PDImageXObject.createFromByteArray(document, IOUtils.toByteArray(resource), "Image");
        placeImage(document, page, image, bbLowerLeftX, bbLowerLeftY, image.getWidth(), image.getHeight(), (float)(Math.PI/4));
        placeImage(document, page, image, bbLowerLeftX, bbLowerLeftY, .5f*image.getWidth(), .5f*image.getHeight(), 0);
        placeImage(document, page, image, bbLowerLeftX, bbLowerLeftY, .25f*image.getWidth(), .25f*image.getHeight(), (float)(9*Math.PI/8));

        document.save(new File(RESULT_FOLDER, "rotatedImagesByBoundingBox.pdf"));
    }
}
 
Example 50
Project: AwesomeJavaLibraryExamples   File: ExampleHelloPdf.java   Source Code and License 6 votes vote down vote up
public static void main(String[] args) throws IOException
{
   PDDocument doc = new PDDocument();
   File pdfFile = File.createTempFile("devict-example", ".pdf");

   try
   {
      PDPage page = new PDPage();
      doc.addPage(page);

      PDFont font = PDType1Font.HELVETICA_BOLD;

      PDPageContentStream contents = new PDPageContentStream(doc, page);
      contents.beginText();
      contents.setFont(font, 12);
      contents.newLineAtOffset(100, 700);
      contents.showText("Hello DevICT PDFBox the time is " + LocalDateTime.now().format(DateTimeFormatter.ISO_DATE_TIME));
      contents.endText();
      contents.close();

      doc.save(pdfFile);
   }
   finally
   {
      System.out.printf("PDF created and saved at %s\n", pdfFile.getAbsolutePath());
      doc.close();
   }

   Desktop.getDesktop().open(pdfFile);
}
 
Example 51
Project: testarea-pdfbox2   File: TextAndGraphics.java   Source Code and License 6 votes vote down vote up
/**
 * <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 52
Project: pcm-api   File: PdfBoxServiceImpl.java   Source Code and License 6 votes vote down vote up
@Override
public void addColorBox(Color color, float xCoordinate, float yCoordinate, float width, float height, PDPage page, PDPageContentStream contents) throws IOException {
    contents.setNonStrokingColor(color);
    contents.addRect(page.getMediaBox().getLowerLeftX() + xCoordinate, page.getMediaBox().getLowerLeftY() + yCoordinate, width, height);
    contents.fill();

    // Reset changed color
    resetChangedColorToDefault(contents);
}
 
Example 53
Project: pcm-api   File: PdfBoxServiceImpl.java   Source Code and License 6 votes vote down vote up
@Override
public void addUnorderedListContent(List<String> content, String itemMarkerSymbol, float xCoordinate, float yCoordinate, float cellWidth, PDFont font, float fontSize, PDPageContentStream contentStream) throws IOException {
    final float rowHeight = 20f;
    final float cellMargin = 1f;
    List<List<String>> tableContent = new ArrayList<>();

    for (String itemText : content) {
        tableContent.add(Collections.singletonList(itemMarkerSymbol.concat(" " + itemText)));
    }

    TableAttribute tableAttribute = TableAttribute.builder()
            .xCoordinate(xCoordinate)
            .yCoordinate(yCoordinate)
            .rowHeight(rowHeight)
            .cellMargin(cellMargin)
            .contentFont(font)
            .contentFontSize(fontSize)
            .borderColor(Color.WHITE)
            .columns(Collections.singletonList(new Column(cellWidth)))
            .build();

    addTableContent(contentStream, tableAttribute, tableContent);
}
 
Example 54
Project: pcm-api   File: PdfBoxServiceImpl.java   Source Code and License 6 votes vote down vote up
private void drawTableLine(PDPageContentStream contentStream, TableAttribute tableAttribute, String[][] tableContent) throws IOException {
    final int rows = tableContent.length;
    final int cols = tableContent[0].length;
    final float rowHeight = Optional.of(tableAttribute.getRowHeight())
            .orElse(PdfBoxStyle.DEFAULT_TABLE_ROW_HEIGHT);
    log.debug("The row height of the table is: " + rowHeight);

    //set border color
    contentStream.setStrokingColor(tableAttribute.getBorderColor());

    //draw the rows
    final float tableWidth = calculateTableWidth(tableAttribute.getColumns());
    log.debug("The number of the table rows is: " + tableAttribute.getColumns().size());
    float nextLineY = tableAttribute.getYCoordinate();
    for (int i = 0; i <= rows; i++) {
        contentStream.moveTo(tableAttribute.getXCoordinate(), nextLineY);
        contentStream.lineTo(tableAttribute.getXCoordinate() + tableWidth, nextLineY);
        contentStream.stroke();
        nextLineY -= rowHeight;
    }

    //draw the columns
    final float tableHeight = rowHeight * rows;
    float nextLineX = tableAttribute.getXCoordinate();
    for (int i = 0; i < cols; i++) {
        contentStream.moveTo(nextLineX, tableAttribute.getYCoordinate());
        contentStream.lineTo(nextLineX, tableAttribute.getYCoordinate() - tableHeight);
        contentStream.stroke();
        nextLineX += tableAttribute.getColumns().get(i).getCellWidth();
    }
    //draw the right border
    contentStream.moveTo(nextLineX, tableAttribute.getYCoordinate());
    contentStream.lineTo(nextLineX, tableAttribute.getYCoordinate() - tableHeight);
    contentStream.stroke();
}
 
Example 55
Project: pcm-api   File: ConsentPdfGeneratorImpl.java   Source Code and License 6 votes vote down vote up
@Override
public void addConsentReferenceNumberAndPatientInfo(Consent consent, Patient patient, float startYCoordinate, PDFont defaultFont, PDPageContentStream contentStream) throws IOException {
    String consentCreatedOn = PdfBoxHandler.formatDate(consent.getCreatedDateTime(), DATE_FORMAT_PATTERN);
    String consentReferenceNumber = consent.getConsentReferenceId();
    String patientFullName = patient.getFirstName().concat(SPACE_PATTERN + patient.getLastName());
    String patientBirthDate = PdfBoxHandler.formatDate(patient.getBirthDay(), DATE_FORMAT_PATTERN);

    final Color textColor = Color.BLACK;
    final float fontSize = PdfBoxStyle.TEXT_SMALL_SIZE;
    final PDFont contentFont = PDType1Font.TIMES_BOLD;

    // Add Consent Created On
    final String createdOnLabel = getI18nMessage("REVOCATION.PDF.DATE");
    pdfBoxService.addTextAtOffset(createdOnLabel, defaultFont, fontSize, textColor, PdfBoxStyle.LEFT_RIGHT_MARGINS_OF_LETTER, startYCoordinate, contentStream);
    final float createdOnXCoordinate = PdfBoxStyle.LEFT_RIGHT_MARGINS_OF_LETTER + PdfBoxHandler.targetedStringWidth(createdOnLabel, defaultFont, fontSize);
    pdfBoxService.addTextAtOffset(consentCreatedOn, contentFont, fontSize, textColor, createdOnXCoordinate, startYCoordinate, contentStream);

    // Add Consent Reference Number
    final float crnLabelYCoordinate = startYCoordinate - PdfBoxStyle.XLARGE_LINE_SPACE;
    final String crnLabel = getI18nMessage("CONSENT.REFERENCE.NUMBER");
    pdfBoxService.addTextAtOffset(crnLabel, defaultFont, fontSize, textColor, PdfBoxStyle.LEFT_RIGHT_MARGINS_OF_LETTER, crnLabelYCoordinate, contentStream);
    final float crnYCoordinate = crnLabelYCoordinate - PdfBoxStyle.XLARGE_LINE_SPACE;
    pdfBoxService.addTextAtOffset(consentReferenceNumber, contentFont, fontSize, textColor, PdfBoxStyle.LEFT_RIGHT_MARGINS_OF_LETTER, crnYCoordinate, contentStream);

    // Add patient name
    final float nameYCoordinate = crnYCoordinate - PdfBoxStyle.XLARGE_LINE_SPACE;
    final String nameLabel = getI18nMessage("PATIENT.NAME");
    pdfBoxService.addTextAtOffset(nameLabel, defaultFont, fontSize, textColor, PdfBoxStyle.LEFT_RIGHT_MARGINS_OF_LETTER, nameYCoordinate, contentStream);
    final float nameXCoordinate = PdfBoxStyle.LEFT_RIGHT_MARGINS_OF_LETTER + PdfBoxHandler.targetedStringWidth(nameLabel, defaultFont, fontSize);
    pdfBoxService.addTextAtOffset(patientFullName, contentFont, fontSize, textColor, nameXCoordinate, nameYCoordinate, contentStream);

    // Add patient DOB
    final String dobLabel = getI18nMessage("PATIENT.DOB");
    final float dobLabelXCoordinate = 310f;
    pdfBoxService.addTextAtOffset(dobLabel, defaultFont, fontSize, textColor, dobLabelXCoordinate, nameYCoordinate, contentStream);
    final float dobXCoordinate = dobLabelXCoordinate + PdfBoxHandler.targetedStringWidth(dobLabel, defaultFont, fontSize);
    pdfBoxService.addTextAtOffset(patientBirthDate, contentFont, fontSize, textColor, dobXCoordinate, nameYCoordinate, contentStream);
}
 
Example 56
Project: testarea-pdfbox2   File: RotatePageContent.java   Source Code and License 6 votes vote down vote up
/**
 * <a href="http://stackoverflow.com/questions/40611736/rotate-pdf-around-its-center-using-pdfbox-in-java">
 * Rotate PDF around its center using PDFBox in java
 * </a>
 * <p>
 * Indeed, using the code of the OP the image mostly is rotated out of the page area.
 * </p>
 */
@Test
public void testRotateLikeSagar() throws IOException
{
    try (   InputStream resource = getClass().getResourceAsStream("IRJET_Copy_Right_form.pdf")  )
    {
        PDDocument document = PDDocument.load(resource);
        PDPage page = document.getDocumentCatalog().getPages().get(0);
        PDPageContentStream cs = new PDPageContentStream(document, page, PDPageContentStream.AppendMode.PREPEND, false, false); 
        cs.transform(Matrix.getRotateInstance(Math.toRadians(45), 0, 0));
        cs.close();
        document.save(new File(RESULT_FOLDER, "IRJET_Copy_Right_form-rotated-like-sagar.pdf"));
    }
}
 
Example 57
Project: pcm-api   File: ConsentPdfGeneratorImpl.java   Source Code and License 6 votes vote down vote up
private void addAuthorizationToDisclose(Consent consent, float startYCoordinate, PDFont font, PDPage page, PDPageContentStream contentStream) throws IOException {
    final float cardXCoordinate = PdfBoxStyle.LEFT_RIGHT_MARGINS_OF_LETTER;
    final float colAWidth = 180f;
    final float colBWidth = 90f;
    final float colCWidth = 200f;
    final float colDWidth = 90f;
    String title = getI18nMessage("CONSENT.PDF.SECTION1.TITLE");
    drawSectionHeader(title, cardXCoordinate, startYCoordinate, page, contentStream);

    List<Column> tableColumns = Arrays.asList(new Column(colAWidth), new Column(colBWidth), new Column(colCWidth), new Column(colDWidth));

    // Provider permitted to disclose
    float providerPermittedStartYCoordinate = startYCoordinate - PdfBoxStyle.XLARGE_LINE_SPACE;
    addProviderPermittedToDisclose(consent, tableColumns, providerPermittedStartYCoordinate, font, page, contentStream);

    // Provider disclosure is made to
    float providerDisclosureIsMadeToStartYCoordinate = 485f;
    addProviderDisclosureIsMadeTo(consent, tableColumns, providerDisclosureIsMadeToStartYCoordinate, font, page, contentStream);
}
 
Example 58
Project: pcm-api   File: ConsentPdfGeneratorImpl.java   Source Code and License 6 votes vote down vote up
private void addProviderPermittedToDisclose(Consent consent, List<Column> tableColumns, float startYCoordinate, PDFont font, PDPage page, PDPageContentStream contentStream) throws IOException {
    String label = getI18nMessage("CONSENT.PDF.SECTION1.CONTENT1");
    addAuthorizationTableHeader(label, startYCoordinate, tableColumns, font, contentStream);

    // From providers details
    final float fromProviderDetailsYCoordinate = 257f;
    Set<OrganizationalProvider> fromOrganizations = consent.getOrganizationalProvidersPermittedToDisclose().stream()
            .map(ConsentOrganizationalProviderPermittedToDisclose::getOrganizationalProvider)
            .collect(Collectors.toSet());

    Set<IndividualProvider> fromPractitioners = consent.getProvidersPermittedToDisclose().stream()
            .map(ConsentIndividualProviderPermittedToDisclose::getIndividualProvider)
            .collect(Collectors.toSet());

    addConsentProvidersDetails(fromOrganizations, fromPractitioners, tableColumns, fromProviderDetailsYCoordinate, page, contentStream);
}
 
Example 59
Project: testarea-pdfbox2   File: JoinPages.java   Source Code and License 6 votes vote down vote up
/**
 * @see #testJoinSmallAndBig()
 */
void join(PDDocument target, PDDocument topSource, PDDocument bottomSource) throws IOException {
    LayerUtility layerUtility = new LayerUtility(target);
    PDFormXObject topForm = layerUtility.importPageAsForm(topSource, 0);
    PDFormXObject bottomForm = layerUtility.importPageAsForm(bottomSource, 0);

    float height = topForm.getBBox().getHeight() + bottomForm.getBBox().getHeight();
    float width, topMargin, bottomMargin;
    if (topForm.getBBox().getWidth() > bottomForm.getBBox().getWidth()) {
        width = topForm.getBBox().getWidth();
        topMargin = 0;
        bottomMargin = (topForm.getBBox().getWidth() - bottomForm.getBBox().getWidth()) / 2;
    } else {
        width = bottomForm.getBBox().getWidth();
        topMargin = (bottomForm.getBBox().getWidth() - topForm.getBBox().getWidth()) / 2;
        bottomMargin = 0;
    }

    PDPage targetPage = new PDPage(new PDRectangle(width, height));
    target.addPage(targetPage);


    PDPageContentStream contentStream = new PDPageContentStream(target, targetPage);
    if (bottomMargin != 0)
        contentStream.transform(Matrix.getTranslateInstance(bottomMargin, 0));
    contentStream.drawForm(bottomForm);
    contentStream.transform(Matrix.getTranslateInstance(topMargin - bottomMargin, bottomForm.getBBox().getHeight()));
    contentStream.drawForm(topForm);
    contentStream.close();
}
 
Example 60
Project: pcm-api   File: ConsentPdfGeneratorImpl.java   Source Code and License 6 votes vote down vote up
private void addMedicalInformation(Consent consent, float labelYCoordinate, PDFont font, PDPageContentStream contentStream) throws IOException {
    final float xCoordinate = PdfBoxStyle.LEFT_RIGHT_MARGINS_OF_LETTER;
    final float listWidth = 286f;
    final String itemMarkerSymbol = "-";
    float subLabelYCoordinate = labelYCoordinate - 15f;
    float listYCoordinate = labelYCoordinate - 20f;
    String label = getI18nMessage("CONSENT.PDF.CATEGORY.TITLE");
    String subLabel = getI18nMessage("SENSITIVE.CATEGORY");

    pdfBoxService.addTextAtOffset(label, PDType1Font.TIMES_BOLD, PdfBoxStyle.TEXT_SMALL_SIZE, Color.BLACK, xCoordinate, labelYCoordinate, contentStream);
    pdfBoxService.addTextAtOffset(subLabel, font, PdfBoxStyle.TEXT_SMALL_SIZE, Color.BLACK, xCoordinate, subLabelYCoordinate, contentStream);

    List<String> sensitivityCategories = getMedicalInformation(consent);

    pdfBoxService.addUnorderedListContent(sensitivityCategories, itemMarkerSymbol, xCoordinate, listYCoordinate, listWidth, font, PdfBoxStyle.TEXT_SMALL_SIZE, contentStream);
}