Java Code Examples for org.apache.pdfbox.pdmodel.common.PDRectangle

The following are top voted examples for showing how to use org.apache.pdfbox.pdmodel.common.PDRectangle. 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: 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 5
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 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: 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 8
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 9
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 10
Project: ctsms   File: PDFImprinter.java   Source Code and License 8 votes vote down vote up
private PDPageContentStream openContentStream(PDPage page, boolean setPageSize, boolean applyPageOrientation) throws IOException {
	contentStream = new PDPageContentStream(doc, page, true, false);
	if (painter != null) {
		PDRectangle pageSize = page.findMediaBox();
		if (PageOrientation.LANDSCAPE.equals(painter.getPageOrientation())) {
			if (setPageSize) {
				painter.setPageHeight(pageSize.getWidth());
				painter.setPageWidth(pageSize.getHeight());
			}
			if (applyPageOrientation) {
				contentStream.concatenate2CTM(0, 1, -1, 0, pageSize.getWidth(), 0); // cos(theta) sin(theta) -sin(theta) cos(theta) 0 0 cm
			}
		} else {
			if (setPageSize) {
				painter.setPageHeight(pageSize.getHeight());
				painter.setPageWidth(pageSize.getWidth());
			}
		}
	}
	return contentStream;
}
 
Example 11
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 12
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 13
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 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
 * 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 15
Project: dss   File: SignatureImageAndPositionProcessor.java   Source Code and License 8 votes vote down vote up
private static float processY(int rotate, ImageAndResolution ires, BufferedImage visualImageSignature, PDPage pdPage, SignatureImageParameters signatureImageParameters) {
    float y;

    PDRectangle mediaBox = pdPage.getMediaBox();

    switch (rotate) {
        case ANGLE_90:
            y = processYAngle90(mediaBox, ires, signatureImageParameters, visualImageSignature);
            break;
        case ANGLE_180:
            y = processYAngle180(mediaBox, ires, signatureImageParameters, visualImageSignature);
            break;
        case ANGLE_270:
            y = processYAngle270(mediaBox, ires, signatureImageParameters, visualImageSignature);
            break;
        case ANGLE_360:
            y = processYAngle360(mediaBox, ires, signatureImageParameters, visualImageSignature);
            break;
        default:
            throw new IllegalStateException(SUPPORTED_ANGLES_ERROR_MESSAGE);
    }

    return y;
}
 
Example 16
Project: estatio   File: PdfManipulator.java   Source Code and License 8 votes vote down vote up
private void addHyperlink(
        final float x, final float y,
        final String hyperlink,
        final PDPage pdPage) throws IOException {

    PDAnnotationLink txtLink = new PDAnnotationLink();

    PDRectangle position = new PDRectangle();
    PDBorderStyleDictionary underline = new PDBorderStyleDictionary();
    underline.setStyle(PDBorderStyleDictionary.STYLE_UNDERLINE);
    txtLink.setBorderStyle(underline);

    position.setLowerLeftX(x);
    position.setLowerLeftY(y);
    position.setUpperRightX(X_MARGIN_LEFT + BOX_WIDTH);
    position.setUpperRightY(y + TEXT_LINE_HEIGHT);
    txtLink.setRectangle(position);

    PDActionURI action = new PDActionURI();
    action.setURI(hyperlink);
    txtLink.setAction(action);
    pdPage.getAnnotations().add(txtLink);
}
 
Example 17
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 18
Project: git-rekt   File: BillPdfGenerator.java   Source Code and License 7 votes vote down vote up
private float getCenteredTextXPos(PDPage page, String text, PDFont font, int fontSize)
        throws IOException {
    float textWidth = getStringWidth(text, font, fontSize);
    PDRectangle pageSize = page.getMediaBox();
    float pageCenterX = pageSize.getWidth() / 2F;
    float textX = pageCenterX - textWidth/2F;
    return textX;
}
 
Example 19
Project: kumoreg   File: BadgeLib.java   Source Code and License 7 votes vote down vote up
/**
 * Calculates the maximum font size that can be used to fit in to a given bounding box.
 * Assumes that landscape (wider than taller) boxes are using horizontal text and
 * portrait (taller than wider) boxes are using text rotated 90 degrees
 * @param font Font text will be drawn in
 * @param text Lines of text to be drawn. Must contain at least one line
 * @param boundingBox Bounds to fit text in
 * @return font size
 * @throws IOException Error working with font bubbled up from PDFBox
 */
static int findMaxFontSize(PDFont font, List<String> text, PDRectangle boundingBox) throws IOException {
    if (text.size() == 0) {
        throw new RuntimeException("findMaxFontSize called with empty text argument");
    }
    float maxTextWidth;
    float maxTextHeight;
    if (boundingBox.getWidth() > boundingBox.getHeight()) {
        maxTextWidth = boundingBox.getWidth();
        maxTextHeight = boundingBox.getHeight();
    } else {
        maxTextWidth = boundingBox.getHeight();
        maxTextHeight = boundingBox.getWidth();
    }

    Float maxLineSize = Float.MAX_VALUE;
    for (String line : text) {
        float lineSize = findMaxLineSize(font, line, maxTextWidth, maxTextHeight);
        if (lineSize < maxLineSize) {
            maxLineSize = lineSize;
        }
    }
    if (maxLineSize * text.size() > maxTextHeight ) {
        maxLineSize = maxLineSize / text.size();
    }
    return  maxLineSize.intValue();
}
 
Example 20
Project: testarea-pdfbox2   File: SetCropBox.java   Source Code and License 7 votes vote down vote up
/**
 * <a href="http://stackoverflow.com/questions/39689004/pdfbox-2-0-3-set-cropbox-using-textposition-coordinates">
 * PDFBox 2.0.3 Set cropBox using TextPosition coordinates
 * </a>
 * <br/>
 * <a href="http://downloadcenter.samsung.com/content/UM/201504/20150407095631744/ENG-US_NMATSCJ-1.103-0330.pdf">
 * ENG-US_NMATSCJ-1.103-0330.pdf
 * </a>
 * <p>
 * This test shows how to set the crop box on page twelve and render the cropped page as image.
 * </p>
 */
@Test
public void testSetCropBoxImgENG_US_NMATSCJ_1_103_0330() throws IOException
{
    try (   InputStream resource = getClass().getResourceAsStream("ENG-US_NMATSCJ-1.103-0330.pdf"))
    {
        PDDocument pdDocument = PDDocument.load(resource);
        PDPage page = pdDocument.getPage(12-1);
        page.setCropBox(new PDRectangle(40f, 680f, 510f, 100f));

        PDFRenderer renderer = new PDFRenderer(pdDocument);
        BufferedImage img = renderer.renderImage(12 - 1, 4f);
        ImageIOUtil.writeImage(img, new File(RESULT_FOLDER, "ENG-US_NMATSCJ-1.103-0330-page12cropped.jpg").getAbsolutePath(), 300);
        pdDocument.close();
    }
}
 
Example 21
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 22
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 23
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 24
Project: pdfbox-layout   File: CompatibilityHelper.java   Source Code and License 7 votes vote down vote up
/**
    * Transform the rectangle in order to match the page rotation
    * @param rect the rectangle.
    * @param page the page.
    * @return the transformed rectangle.
    */
   public static PDRectangle transformToPageRotation(
    final PDRectangle rect, final PDPage page) {
AffineTransform transform = transformToPageRotation(page);
if (transform == null) {
    return rect;
}
float[] points = new float[] {rect.getLowerLeftX(), rect.getLowerLeftY(), rect.getUpperRightX(), rect.getUpperRightY()};
float[] rotatedPoints = new float[4]; 
transform.transform(points, 0, rotatedPoints, 0, 2);
PDRectangle rotated = new PDRectangle();
rotated.setLowerLeftX(rotatedPoints[0]);
rotated.setLowerLeftY(rotatedPoints[1]);
rotated.setUpperRightX(rotatedPoints[2]);
rotated.setUpperRightY(rotatedPoints[3]);
return rotated;
   }
 
Example 25
Project: pdfbox-layout   File: HyperlinkAnnotationProcessor.java   Source Code and License 7 votes vote down vote up
protected void handleHyperlinkAnnotations(
    AnnotatedStyledText annotatedText, DrawContext drawContext,
    Position upperLeft, float width, float height) {
Iterable<HyperlinkAnnotation> hyperlinkAnnotations = annotatedText
	.getAnnotationsOfType(HyperlinkAnnotation.class);
for (HyperlinkAnnotation hyperlinkAnnotation : hyperlinkAnnotations) {
    List<Hyperlink> links = linkMap.get(drawContext.getCurrentPage());
    if (links == null) {
	links = new ArrayList<Hyperlink>();
	linkMap.put(drawContext.getCurrentPage(), links);
    }
    PDRectangle bounds = new PDRectangle();
    bounds.setLowerLeftX(upperLeft.getX());
    bounds.setLowerLeftY(upperLeft.getY() - height);
    bounds.setUpperRightX(upperLeft.getX() + width);
    bounds.setUpperRightY(upperLeft.getY());

    links.add(new Hyperlink(bounds, annotatedText.getColor(),
	    hyperlinkAnnotation.getLinkStyle(), hyperlinkAnnotation
		    .getHyperlinkURI()));
}
   }
 
Example 26
Project: pdfbox-layout   File: CompatibilityHelper.java   Source Code and License 7 votes vote down vote up
/**
    * Transform the rectangle in order to match the page rotation
    * @param rect the rectangle.
    * @param page the page.
    * @return the transformed rectangle.
    */
   public static PDRectangle transformToPageRotation(
    final PDRectangle rect, final PDPage page) {
AffineTransform transform = transformToPageRotation(page);
if (transform == null) {
    return rect;
}
float[] points = new float[] {rect.getLowerLeftX(), rect.getLowerLeftY(), rect.getUpperRightX(), rect.getUpperRightY()};
float[] rotatedPoints = new float[4]; 
transform.transform(points, 0, rotatedPoints, 0, 2);
PDRectangle rotated = new PDRectangle();
rotated.setLowerLeftX(rotatedPoints[0]);
rotated.setLowerLeftY(rotatedPoints[1]);
rotated.setUpperRightX(rotatedPoints[2]);
rotated.setUpperRightY(rotatedPoints[3]);
return rotated;
   }
 
Example 27
Project: my-cv-site   File: FormattedReader.java   Source Code and License 7 votes vote down vote up
private void fillBeadRectangles(PDPage page)
{
    beadRectangles = new ArrayList<PDRectangle>();
    for (PDThreadBead bead : page.getThreadBeads())
    {
        if (bead == null)
        {
            // can't skip, because of null entry handling in processTextPosition()
            beadRectangles.add(null);
            continue;
        }
        
        PDRectangle rect = bead.getRectangle();
        
        // bead rectangle is in PDF coordinates (y=0 is bottom),
        // glyphs are in image coordinates (y=0 is top),
        // so we must flip
        PDRectangle mediaBox = page.findMediaBox();
        float upperRightY = mediaBox.getUpperRightY() - rect.getLowerLeftY();
        float lowerLeftY = mediaBox.getUpperRightY() - rect.getUpperRightY();
        rect.setLowerLeftY(lowerLeftY);
        rect.setUpperRightY(upperRightY);
        
        // adjust for cropbox
        PDRectangle cropBox = page.findCropBox();
        if (cropBox.getLowerLeftX() != 0 || cropBox.getLowerLeftY() != 0)
        {
            rect.setLowerLeftX(rect.getLowerLeftX() - cropBox.getLowerLeftX());
            rect.setLowerLeftY(rect.getLowerLeftY() - cropBox.getLowerLeftY());
            rect.setUpperRightX(rect.getUpperRightX() - cropBox.getLowerLeftX());
            rect.setUpperRightY(rect.getUpperRightY() - cropBox.getLowerLeftY());
        }
        
        beadRectangles.add(rect);
    }
}
 
Example 28
Project: kumoreg   File: BadgeLib.java   Source Code and License 7 votes vote down vote up
/**
 * Calculates the maximum font size that can be used to fit in to a given bounding box.
 * Assumes that landscape (wider than taller) boxes are using horizontal text and
 * portrait (taller than wider) boxes are using text rotated 90 degrees
 * @param font Font text will be drawn in
 * @param text Lines of text to be drawn. Must contain at least one line
 * @param boundingBox Bounds to fit text in
 * @return font size
 * @throws IOException Error working with font bubbled up from PDFBox
 */
static int findMaxFontSize(PDFont font, List<String> text, PDRectangle boundingBox) throws IOException {
    if (text.size() == 0) {
        throw new RuntimeException("findMaxFontSize called with empty text argument");
    }
    float maxTextWidth;
    float maxTextHeight;
    if (boundingBox.getWidth() > boundingBox.getHeight()) {
        maxTextWidth = boundingBox.getWidth();
        maxTextHeight = boundingBox.getHeight();
    } else {
        maxTextWidth = boundingBox.getHeight();
        maxTextHeight = boundingBox.getWidth();
    }

    Float maxLineSize = Float.MAX_VALUE;
    for (String line : text) {
        float lineSize = findMaxLineSize(font, line, maxTextWidth, maxTextHeight);
        if (lineSize < maxLineSize) {
            maxLineSize = lineSize;
        }
    }
    if (maxLineSize * text.size() > maxTextHeight ) {
        maxLineSize = maxLineSize / text.size();
    }
    return  maxLineSize.intValue();
}
 
Example 29
Project: dss   File: SignatureImageAndPositionProcessor.java   Source Code and License 7 votes vote down vote up
private static float processYAngle90(PDRectangle mediaBox, ImageAndResolution ires, SignatureImageParameters signatureImageParameters, BufferedImage visualImageSignature) {
    float y;

    SignatureImageParameters.VisualSignatureAlignmentHorizontal alignmentHorizontal = getVisualSignatureAlignmentHorizontal(signatureImageParameters);

    switch (alignmentHorizontal) {
        case LEFT:
        case NONE:
            y = signatureImageParameters.getxAxis();
            break;
        case CENTER:
            y = (mediaBox.getHeight() - ires.toXPoint(visualImageSignature.getHeight())) / 2;
            break;
        case RIGHT:
            y = mediaBox.getHeight() - ires.toYPoint(visualImageSignature.getHeight()) - signatureImageParameters.getxAxis();
            break;
        default:
            throw new IllegalStateException(SUPPORTED_HORIZONTAL_ALIGNMENT_ERROR_MESSAGE + alignmentHorizontal.name());
    }

    return y;
}
 
Example 30
Project: dss   File: SignatureImageAndPositionProcessor.java   Source Code and License 7 votes vote down vote up
private static float processYAngle180(PDRectangle mediaBox, ImageAndResolution ires, SignatureImageParameters signatureImageParameters, BufferedImage visualImageSignature) {
    float y;

    SignatureImageParameters.VisualSignatureAlignmentVertical alignmentVertical = getVisualSignatureAlignmentVertical(signatureImageParameters);

    switch (alignmentVertical) {
        case TOP:
        case NONE:
            y = mediaBox.getHeight() - ires.toYPoint(visualImageSignature.getHeight()) - signatureImageParameters.getyAxis();
            break;
        case MIDDLE:
            y = (mediaBox.getHeight() - ires.toYPoint(visualImageSignature.getHeight())) / 2;
            break;
        case BOTTON:
            y = signatureImageParameters.getyAxis();
            break;
        default:
            throw new IllegalStateException(SUPPORTED_VERTICAL_ALIGNMENT_ERROR_MESSAGE + alignmentVertical.name());
    }

    return y;
}
 
Example 31
Project: dss   File: SignatureImageAndPositionProcessor.java   Source Code and License 7 votes vote down vote up
private static float processYAngle270(PDRectangle mediaBox, ImageAndResolution ires, SignatureImageParameters signatureImageParameters, BufferedImage visualImageSignature) {
    float y;

    SignatureImageParameters.VisualSignatureAlignmentHorizontal alignmentHorizontal = getVisualSignatureAlignmentHorizontal(signatureImageParameters);

    switch (alignmentHorizontal) {
        case LEFT:
        case NONE:
            y = mediaBox.getHeight() - ires.toYPoint(visualImageSignature.getHeight()) - signatureImageParameters.getxAxis();
            break;
        case CENTER:
            y = (mediaBox.getHeight() - ires.toXPoint(visualImageSignature.getHeight())) / 2;
            break;
        case RIGHT:
            y = signatureImageParameters.getxAxis();
            break;
        default:
            throw new IllegalStateException(SUPPORTED_HORIZONTAL_ALIGNMENT_ERROR_MESSAGE + alignmentHorizontal.name());
    }

    return y;
}
 
Example 32
Project: dss   File: SignatureImageAndPositionProcessor.java   Source Code and License 7 votes vote down vote up
private static float processYAngle360(PDRectangle mediaBox, ImageAndResolution ires, SignatureImageParameters signatureImageParameters, BufferedImage visualImageSignature) {
    float y;

    SignatureImageParameters.VisualSignatureAlignmentVertical alignmentVertical = getVisualSignatureAlignmentVertical(signatureImageParameters);

    switch (alignmentVertical) {
        case TOP:
        case NONE:
            y = signatureImageParameters.getyAxis();
            break;
        case MIDDLE:
            y = (mediaBox.getHeight() - ires.toYPoint(visualImageSignature.getHeight())) / 2;
            break;
        case BOTTON:
            y = mediaBox.getHeight() - ires.toYPoint(visualImageSignature.getHeight()) - signatureImageParameters.getyAxis();
            break;
        default:
            throw new IllegalStateException(SUPPORTED_VERTICAL_ALIGNMENT_ERROR_MESSAGE + alignmentVertical.name());
    }

    return y;
}
 
Example 33
Project: testarea-pdfbox1   File: RolloverAnnotation.java   Source Code and License 7 votes vote down vote up
void createRollover(PDAnnotation annotation, String filename) throws IOException, COSVisitorException
{
    PDDocument document = new PDDocument();
    PDPage page = new PDPage();
    document.addPage(page);
    List<PDAnnotation> annotations = page.getAnnotations();

    float x = 100;
    float y = 500;
    String text = "PDFBox";
    PDFont font = PDType1Font.HELVETICA_BOLD;
    float textWidth = font.getStringWidth(text) / 1000 * 18;

    PDPageContentStream contents = new PDPageContentStream(document, page);
    contents.beginText();
    contents.setFont(font, 18);
    contents.moveTextPositionByAmount(x, y);
    contents.drawString(text);
    contents.endText();
    contents.close();

    PDAppearanceDictionary appearanceDictionary = new PDAppearanceDictionary();
    PDAppearanceStream normal = createAppearanceStream(document, textWidth, font, "0.5 0.5 0.5 rg");
    PDAppearanceStream rollover = createAppearanceStream(document, textWidth, font, "1 0.7 0.5 rg");
    PDAppearanceStream down = createAppearanceStream(document, textWidth, font, "0 0 0 rg");
    appearanceDictionary.setNormalAppearance(normal);
    appearanceDictionary.setRolloverAppearance(rollover);
    appearanceDictionary.setDownAppearance(down);
    annotation.setAppearance(appearanceDictionary);

    PDRectangle position = new PDRectangle();
    position.setLowerLeftX(x);
    position.setLowerLeftY(y - 5);
    position.setUpperRightX(x + textWidth);
    position.setUpperRightY(y + 20);
    annotation.setRectangle(position);

    annotations.add(annotation);
    document.save(new File(RESULT_FOLDER, filename));
    document.close();
}
 
Example 34
Project: testarea-pdfbox1   File: RolloverAnnotation.java   Source Code and License 7 votes vote down vote up
PDAppearanceStream createAppearanceStream(PDDocument document, float width, PDFont font, String backColorSettingOperation) throws IOException
{
    PDResources pdResources = new PDResources();
    String fontName = pdResources.addFont(font);
    PDStream pdStream = new PDStream(document);
    OutputStream os = pdStream.createOutputStream();
    String streamToBe = backColorSettingOperation + " 0 -5 " + width + " 25 re f /" + fontName + " 18 Tf 0 g BT (PDFBox) Tj ET";
    os.write(streamToBe.getBytes());
    os.close();
    
    PDXObjectForm xobject = new PDXObjectForm(pdStream);
    xobject.setResources(pdResources);
    xobject.setBBox(new PDRectangle(new BoundingBox(0, -5, width, 20)));
    xobject.setFormType(1);
    PDAppearanceStream normal = new PDAppearanceStream(xobject.getCOSStream());
    return normal;
}
 
Example 35
Project: testarea-pdfbox1   File: ExtractWithoutExtraSpaces.java   Source Code and License 7 votes vote down vote up
byte[] createTestDocument() throws IOException, COSVisitorException
{
    try (   ByteArrayOutputStream baos = new ByteArrayOutputStream();
            PDDocument doc = new PDDocument()   )
    {
        PDPage page = new PDPage(new PDRectangle(792, 612));
        doc.addPage(page);
        
        PDFont font = PDType1Font.COURIER;

        PDPageContentStream contents = new PDPageContentStream(doc, page);
        contents.beginText();
        contents.setFont(font, 9);
        contents.moveTextPositionByAmount(100, 500);
        contents.drawString("             2                                                                  Netto        5,00 EUR 3,00");
        contents.moveTextPositionByAmount(0, 0);
        contents.drawString("                2882892  ENERGIZE LR6 Industrial                     2,50 EUR 1");
        contents.endText();
        contents.close();
        
        doc.save(baos);
        
        return baos.toByteArray();
    }
}
 
Example 36
Project: Pdf2Dom   File: CSSBoxTree.java   Source Code and License 7 votes vote down vote up
/**
   * Creates a style definition used for pages.
   * @return The page style definition.
   */
  protected NodeData createPageStyle()
  {
      NodeData ret = createBlockStyle();
      TermFactory tf = CSSFactory.getTermFactory();
      ret.push(createDeclaration("position", tf.createIdent("relative")));
ret.push(createDeclaration("border-width", tf.createLength(1f, Unit.px)));
ret.push(createDeclaration("border-style", tf.createIdent("solid")));
ret.push(createDeclaration("border-color", tf.createColor(0, 0, 255)));
ret.push(createDeclaration("margin", tf.createLength(0.5f, Unit.em)));

      PDRectangle layout = getCurrentMediaBox();
      if (layout != null)
      {
          float w = layout.getWidth();
          float h = layout.getHeight();
          final int rot = pdpage.getRotation();
          if (rot == 90 || rot == 270)
          {
              float x = w; w = h; h = x;
          }
          
          ret.push(createDeclaration("width", tf.createLength(w, unit)));
          ret.push(createDeclaration("height", tf.createLength(h, unit)));
      }
      else
          log.warn("No media box found");
      
      return ret;
  }
 
Example 37
Project: jabref   File: TextExtractor.java   Source Code and License 7 votes vote down vote up
private Rectangle2D calculateSegmentBoundingBox(COSArray quadsArray, int segmentPointer) {
    // Extract coordinate values
    float upperLeftX = toFloat(quadsArray.get(segmentPointer));
    float upperLeftY = toFloat(quadsArray.get(segmentPointer + 1));
    float upperRightX = toFloat(quadsArray.get(segmentPointer + 2));
    float upperRightY = toFloat(quadsArray.get(segmentPointer + 3));
    float lowerLeftX = toFloat(quadsArray.get(segmentPointer + 4));
    float lowerLeftY = toFloat(quadsArray.get(segmentPointer + 5));

    // Post-processing of the raw coordinates.
    PDRectangle pageSize = page.getMediaBox();
    float ulx = upperLeftX - 1; // It is magic.
    float uly = pageSize.getHeight() - upperLeftY;
    float width = upperRightX - lowerLeftX;
    float height = upperRightY - lowerLeftY;

    return new Rectangle2D.Float(ulx, uly, width, height);
}
 
Example 38
Project: java-image-processing-survival-guide   File: PdfBoxPreviewTest.java   Source Code and License 7 votes vote down vote up
@SuppressWarnings("unchecked")
public List<BufferedImage> toImages(PDDocument pdDocument, int startPage, int endPage, int resolution, int imageType) throws Exception {
    final List<BufferedImage> result = new ArrayList<BufferedImage>();
    final List<PDPage> pages = pdDocument.getDocumentCatalog().getAllPages();
    final int pagesSize = pages.size();

    for (int i = startPage - 1; i < endPage && i < pagesSize; i++) {
        PDPage page = pages.get(i);
        PDRectangle cropBox = page.findCropBox();
        float width = cropBox.getWidth();
        float height = cropBox.getHeight();
        int currResolution = calculateResolution(resolution, width, height);
        BufferedImage image = page.convertToImage(imageType, currResolution);

        if (image != null) {
            result.add(image);
        }
    }

    return result;
}
 
Example 39
Project: pdfwriter   File: PDFContentPage.java   Source Code and License 7 votes vote down vote up
@SuppressWarnings({ "unchecked", "rawtypes" })
private void addLinkToPage(float x, float y, float width, PDFPage trgPage) throws IOException {
	  List annotations = page.getAnnotations();
         

         PDAnnotationLink txtLink = new PDAnnotationLink();
         
         PDRectangle position = new PDRectangle();
         position.setLowerLeftX(x);
         position.setLowerLeftY(y);  // down a couple of points
         position.setUpperRightX(x+width);
         position.setUpperRightY(y+10);
         txtLink.setRectangle(position);

         // add an action
         PDActionGoTo action = new PDActionGoTo();
         PDPageDestination destination = new PDPageFitDestination();
         destination.setPage(trgPage);
         action.setDestination(destination);
         txtLink.setAction(action);

         annotations.add(txtLink);
}
 
Example 40
Project: pdfwriter   File: PageHeader.java   Source Code and License 7 votes vote down vote up
public void create(PDDocument document, PDFPage page) throws IOException {

	PDPageContentStream cs = new PDPageContentStream(document, page, true, false);
       
	PDRectangle pageSize = page.getBleedBox();
       float pageWidth = pageSize.getWidth();
       page.translateAndRotateIfNecessary(cs, pageWidth, 0);
       
	cs.beginText();
	PDFont font = PDType1Font.HELVETICA_BOLD;
	cs.setFont(font, 20);
	cs.moveTextPositionByAmount(page.getLeftX(), page.getTopY());
	cs.drawString(title);
	cs.endText();
	cs.drawLine(page.getLeftX(), page.getTopY()-height, page.getRightX(), page.getTopY()-height);
		cs.close();
}
 
Example 41
Project: brigen-base   File: TextPageAppender.java   Source Code and License 7 votes vote down vote up
@Override
protected void appendContent(int start, int pages, int page, PDPageContentStream contentStream,
        PDRectangle rect) throws IOException {
    float fontSize = getFontSize();
    contentStream.beginText();
    contentStream.setFont(font, fontSize);
    contentStream.setNonStrokingColor(getColor());
    String str = getText(start, pages, page);
    float contentWidth;
    float contentHeight;
    {
        contentWidth = (font.getStringWidth(str) / 1000) * fontSize;
        contentHeight = (font.getFontDescriptor().getFontBoundingBox().getHeight() / 1000)
                * fontSize;
    }
    double angle = (getRotate() * Math.PI) / 180.0;
    float[] point = getRotatePoint(angle, rect.getWidth(), rect.getHeight(), contentWidth,
            contentHeight);
    contentStream.setTextRotation(angle, point[0], point[1]);
    contentStream.drawString(str);
    contentStream.endText();
}
 
Example 42
Project: Harmonia-1.5   File: PDFFormView.java   Source Code and License 7 votes vote down vote up
public PDField getAcroFormComponentAt(Point2D point, CoordinateSpace sourceSpace){
    Point2D pdfPoint = sourceSpace.convertPointTo(point, this.getBounds(), CoordinateSpace.PDF);
    if(_document == null) return null;
    PDDocumentCatalog cat = _document.getDocumentCatalog();
    if(cat == null) return null;
    PDAcroForm acroForm = cat.getAcroForm();
    if(acroForm == null) return null;
    try {
        List<PDField> fields = acroForm.getFields();
        for(PDField field : fields){
            PDRectangle rect = PDFields.getPDRectangleForField(field);
            if(rect.contains((float)pdfPoint.getX(), (float)pdfPoint.getY())){
                return field;
            }
        }
    } catch (IOException e) {
        e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
    }

    return null;
}
 
Example 43
Project: Lernkartei_2017   File: Printer.java   Source Code and License 6 votes vote down vote up
static void createPage(PDDocument temp,int count)
{
	for(int i = 0; i < count;i++)
	{
		PDPage page = new PDPage(new PDRectangle(297 * POINTS_PER_MM, 210 * POINTS_PER_MM));
		temp.addPage(page);
	}
}
 
Example 44
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 45
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 46
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 47
Project: 484_P7_1-Java   File: ObjectExtractorStreamEngine.java   Source Code and License 6 votes vote down vote up
protected ObjectExtractorStreamEngine(PDPage page) {
    super(page);

    this.log = LoggerFactory.getLogger(ObjectExtractorStreamEngine.class);

    this.rulings = new ArrayList<>();
    this.pageTransform = null;

    // calculate page transform
    PDRectangle cb = this.getPage().getCropBox();
    int rotation = this.getPage().getRotation();

    this.pageTransform = new AffineTransform();

    if (Math.abs(rotation) == 90 || Math.abs(rotation) == 270) {
        this.pageTransform = AffineTransform.getRotateInstance(rotation * (Math.PI / 180.0), 0, 0);
        this.pageTransform.concatenate(AffineTransform.getScaleInstance(1, -1));
    } else {
        this.pageTransform.concatenate(AffineTransform.getTranslateInstance(0, cb.getHeight()));
        this.pageTransform.concatenate(AffineTransform.getScaleInstance(1, -1));
    }

    this.pageTransform.translate(-cb.getLowerLeftX(), -cb.getLowerLeftY());
}
 
Example 48
Project: gcs   File: PdfPanel.java   Source Code and License 6 votes vote down vote up
private void markPageForLoading() {
    int numberOfPages = mPdf.getNumberOfPages();
    if (mPageIndex >= 0 && mPageIndex == numberOfPages) {
        mPageIndex = numberOfPages - 1;
    }
    if (mPageIndex >= 0 && mPageIndex < numberOfPages) {
        PDPage page = mPdf.getPage(mPageIndex);
        PDRectangle cropBox = page.getCropBox();
        float scale = SCALES[mScaleIndex] * Toolkit.getDefaultToolkit().getScreenResolution();
        mWidth = (int) Math.ceil(cropBox.getWidth() / 72 * scale);
        mHeight = (int) Math.ceil(cropBox.getHeight() / 72 * scale);
        mImg = null;
        mNeedLoad = true;
        Dimension size = new Dimension(mWidth, mHeight);
        UIUtilities.setOnlySize(this, size);
        setSize(size);
        repaint();
        mIgnorePageChange = true;
        mOwner.updateStatus(mPageIndex, numberOfPages, SCALES[mScaleIndex]);
        mIgnorePageChange = false;
    }
}
 
Example 49
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 50
Project: kumoreg   File: AttendeeBadge2017.java   Source Code and License 6 votes vote down vote up
void addBadge(Attendee attendee, Integer xOffset, Integer yOffset) throws IOException {
//        PDPage templatePage = frontBackground.getDocumentCatalog().getPages().get(0);
//        COSDictionary pageDict = templatePage.getCOSObject();
//        COSDictionary newPageDict = new COSDictionary(pageDict);
//        newPageDict.removeItem(COSName.ANNOTS);
//        newPageDict.removeItem(COSName.ACTUAL_TEXT);
//
//        PDPage page = document.importPage(new PDPage(newPageDict));
        this.xOffset = xOffset; // Todo: don't store this in the class
        this.yOffset = yOffset;
        PDPage page = document.importPage(new PDPage(new PDRectangle(612f, 396f)));

        // Positions are measured from the bottom left corner of the page at 72 DPI
        drawAgeColorStripe(page, attendee);
        drawVerticalAgeRangeText(page, bankGothic, attendee);
        drawName(page, attendee);
        drawBadgeTypeStripe(page, attendee);
        drawBadgeTypeText(page, bankGothic, attendee);
        drawBadgeNumber(page, bankGothic, attendee);
    }
 
Example 51
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 52
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 53
Project: cat-boot   File: ReportLink.java   Source Code and License 6 votes vote down vote up
private float addLink(PDDocument document, int pageNumber, float startX, float startY, PdfTextStyle textConfig) {
    PDAnnotationLink txtLink = new PDAnnotationLink();
    txtLink.setColor(textConfig.getColor());

    PDBorderStyleDictionary underline = getLinkUnderline();
    txtLink.setBorderStyle(underline);

    try {
        float textWidth = (textConfig.getFont().getStyle(textConfig.getStyle()).getStringWidth(text) / 1000) * textConfig.getFontSize();

        float startLinkY = startY + textConfig.getFontSize();
        float endLinkY = startY - underline.getWidth();

        PDRectangle position = new PDRectangle();
        position.setLowerLeftX(startX);
        position.setLowerLeftY(startLinkY);
        position.setUpperRightX(startX + textWidth);
        position.setUpperRightY(endLinkY);
        txtLink.setRectangle(position);

        PDActionURI action = new PDActionURI();
        action.setURI(link);
        txtLink.setAction(action);

        PDPage page = document.getDocumentCatalog().getPages().get(pageNumber);
        page.getAnnotations().add(txtLink);

        return endLinkY;
    } catch (IOException e) {
        LOG.warn("Could not add link: " + e.getClass() + " - " + e.getMessage());
        return startY;
    }
}
 
Example 54
Project: testarea-pdfbox2   File: PDFVisibleTextStripper.java   Source Code and License 6 votes vote down vote up
@Override
public void processPage(PDPage page) throws IOException {
    PDRectangle pageSize = page.getCropBox();

    lowerLeftX = pageSize.getLowerLeftX();
    lowerLeftY = pageSize.getLowerLeftY();

    super.processPage(page);
}
 
Example 55
Project: testarea-pdfbox2   File: NestedHtmlInCell.java   Source Code and License 6 votes vote down vote up
/**
     * <a href="http://stackoverflow.com/questions/43447829/apache-pdfbox-boxable-html-ordered-unordered-list-is-incorrectly-displayed">
     * Apache PDFBox, Boxable - HTML ordered/unordered list is incorrectly displayed
     * </a>
     * <p>
     * Using the 1.5-RC artifact like the OP did, one can indeed observe the incorrect nesting.
     * </p>
     * <p>
     * Compiling and using the current (2017-04-25) master branch (which contains numerous changes
     * added since the RC has been released but is still versioned 1.4!), though, the nested list
     * is properly displayed.
     * </p>
     */
    @Test
    public void testNestedHtmlListsInCell() throws IOException
    {
        PDDocument document = new PDDocument();
        PDPage myPage  = new PDPage(PDRectangle.A4);
        document.addPage(myPage);
        float yPosition = 777;
        float margin = 40;
        float bottomMargin = 40;
        float yStartNewPage = myPage.getMediaBox().getHeight() - (margin);
        float tableWidth = myPage.getMediaBox().getWidth() - (2 * margin);
        BaseTable table = new BaseTable(yPosition, yStartNewPage, bottomMargin, tableWidth, margin, document, myPage, true, true);
        Row<PDPage> row = table.createRow(10f);
        /*Cell cell = */row.createCell((100 / 3f),"<ul><li>hello</li><li>hello 2</li><ol><li>nested</li><li>nested 2</li></ol></ul>", be.quodlibet.boxable.HorizontalAlignment.get("left"), be.quodlibet.boxable.VerticalAlignment.get("top"));
//        /*Cell cell = */row.createCell((100 / 3f),"<ul><li>hello</li><li>hello 2<ol><li>nested</li><li>nested 2</li></ol></li></ul>", be.quodlibet.boxable.HorizontalAlignment.get("left"), be.quodlibet.boxable.VerticalAlignment.get("top"));
//        /*Cell cell = */row.createCell((100 / 3f),"<ul><li>hello</li><li>hello 2<ul><li>nested</li><li>nested 2</li></ul></li></ul>", be.quodlibet.boxable.HorizontalAlignment.get("left"), be.quodlibet.boxable.VerticalAlignment.get("top"));
//        /*Cell cell = */row.createCell((100 / 3f),"not bold <i>italic</i> <b>once bold <b>twice bold</b> once bold again <i>italic</i> </b> not bold", be.quodlibet.boxable.HorizontalAlignment.get("left"), be.quodlibet.boxable.VerticalAlignment.get("top"));
        table.draw();
        document.save(new File(RESULT_FOLDER, "NestedHtmlListsInCell.pdf"));
        document.close();
    }
 
Example 56
Project: testarea-pdfbox2   File: TestEmptySignatureField.java   Source Code and License 6 votes vote down vote up
/**
 * <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 57
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 58
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 59
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 60
Project: pdf-box-examples   File: PdfImagesHelper.java   Source Code and License 6 votes vote down vote up
/**
 * Quick method to validate position and size.
 */
private void assertPositionAndSize(float x, float y, PDImageXObject image, PDPage page) throws PdfProcessingException {
    PDRectangle pageArea = page.getCropBox();
    // Assert position is in page
    if (x < pageArea.getLowerLeftX() || x > pageArea.getUpperRightX())
        throw new PdfProcessingException("X position not valid. (" + x + "," + y + ") out of page");
    if (y < pageArea.getLowerLeftY() || y > pageArea.getUpperRightY())
        throw new PdfProcessingException("Y position not valid. (" + x + "," + y + ") out of page");

    // Assert image fits
    if (x + image.getWidth() > pageArea.getUpperRightX() ||
        y + image.getHeight() > pageArea.getUpperRightY())
        throw new PdfProcessingException("Image dos not fit in page");
}