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

The following are Jave code examples for showing how to use addRect() of the org.apache.pdfbox.pdmodel.PDPageContentStream class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
Example 1
Project: testarea-pdfbox2   File: RectanglesOverText.java   Source Code and License Vote up 7 votes
/**
 * <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 2
Project: testarea-pdfbox2   File: JoinPages.java   Source Code and License Vote up 7 votes
/**
 * @see #testJoinSmallAndBig()
 */
PDDocument prepareSmallPdf() throws IOException {
    PDDocument document = new PDDocument();
    PDPage page = new PDPage(new PDRectangle(72, 72));
    document.addPage(page);
    PDPageContentStream contentStream = new PDPageContentStream(document, page);
    contentStream.setNonStrokingColor(Color.YELLOW);
    contentStream.addRect(0, 0, 72, 72);
    contentStream.fill();
    contentStream.setNonStrokingColor(Color.BLACK);
    PDFont font = PDFontFactory.createDefaultFont();
    contentStream.beginText();
    contentStream.setFont(font, 18);
    contentStream.newLineAtOffset(2, 54);
    contentStream.showText("small");
    contentStream.newLineAtOffset(0, -48);
    contentStream.showText("page");
    contentStream.endText();
    contentStream.close();
    return document;
}
 
Example 3
Project: testarea-pdfbox2   File: JoinPages.java   Source Code and License Vote up 7 votes
/**
 * @see #testJoinSmallAndBig()
 */
PDDocument prepareBiggerPdf() throws IOException {
    PDDocument document = new PDDocument();
    PDPage page = new PDPage(PDRectangle.A5);
    document.addPage(page);
    PDPageContentStream contentStream = new PDPageContentStream(document, page);
    contentStream.setNonStrokingColor(Color.GREEN);
    contentStream.addRect(0, 0, PDRectangle.A5.getWidth(), PDRectangle.A5.getHeight());
    contentStream.fill();
    contentStream.setNonStrokingColor(Color.BLACK);
    PDFont font = PDFontFactory.createDefaultFont();
    contentStream.beginText();
    contentStream.setFont(font, 18);
    contentStream.newLineAtOffset(2, PDRectangle.A5.getHeight() - 24);
    contentStream.showText("This is the Bigger page");
    contentStream.newLineAtOffset(0, -48);
    contentStream.showText("BIGGER!");
    contentStream.endText();
    contentStream.close();
    return document;
}
 
Example 4
Project: kumoreg   File: StaffBadge2017.java   Source Code and License Vote up 6 votes
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 5
Project: kumoreg   File: StaffBadge2017.java   Source Code and License Vote up 6 votes
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 6
Project: kumoreg   File: AttendeeBadge2017.java   Source Code and License Vote up 6 votes
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 7
Project: pcm-api   File: PdfBoxServiceImpl.java   Source Code and License Vote up 6 votes
@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 8
Project: testarea-pdfbox2   File: TestEmptySignatureField.java   Source Code and License Vote up 6 votes
/**
 * <a href="http://stackoverflow.com/questions/37601092/pdfbox-identify-specific-pages-and-functionalities-recommendations">
 * PDFBox identify specific pages and functionalities recommendations
 * </a>
 * 
 * <p>
 * This test shows how to add an empty signature field with a custom appearance
 * to an existing PDF.
 * </p>
 */
@Test
public void testAddEmptySignatureField() throws IOException
{
    try (   InputStream sourceStream = getClass().getResourceAsStream("test.pdf");
            OutputStream output = new FileOutputStream(new File(RESULT_FOLDER, "test-with-empty-sig-field.pdf")))
    {
        PDFont font = PDType1Font.HELVETICA;
        PDResources resources = new PDResources();
        resources.put(COSName.getPDFName("Helv"), font);

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

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

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

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

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

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

        document.save(output);
        document.close();
    }
}
 
Example 9
Project: testarea-pdfbox2   File: RectanglesOverText.java   Source Code and License Vote up 6 votes
/**
 * <a href="https://stackoverflow.com/questions/46080131/text-coordinates-when-stripping-from-pdfbox">
 * Text coordinates when stripping from PDFBox
 * </a>
 * <p>
 * This test applies the OP's code to an arbitrary PDF file and it did work properly
 * (well, it did only cover the text from the baseline upwards but that is to be expected).
 * </p>
 */
@Test
public void testCoverTextByRectanglesInput() throws IOException {
    try (   InputStream resource = getClass().getResourceAsStream("input.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);

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

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

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

        File fileout = new File(RESULT_FOLDER, "input-withRectangles.pdf");
        doc.save(fileout);
        doc.close();
    }
}
 
Example 10
Project: BoxTable   File: CellFiller.java   Source Code and License Vote up 5 votes
@Override
public void fill(final PDPageContentStream stream, final int row, final int column, final float left, final float top, final float width,
		final float height) throws IOException {
	if (column % 2 == (inverted ? 1 : 0)) {
		stream.setNonStrokingColor(color);
		stream.addRect(left, top - height, width, height);
		stream.fill();
	}
}
 
Example 11
Project: BoxTable   File: CellFiller.java   Source Code and License Vote up 5 votes
@Override
public void fill(final PDPageContentStream stream, final int row, final int column, final float left, final float top, final float width,
		final float height) throws IOException {
	if (row % 2 == (inverted ? 1 : 0)) {
		stream.setNonStrokingColor(color);
		stream.addRect(left, top - height, width, height);
		stream.fill();
	}
}
 
Example 12
Project: pdfbox-graphics2d   File: PdfBoxGraphics2D.java   Source Code and License Vote up 5 votes
private void applyShadingAsColor(PDShading shading) throws IOException {
	/*
	 * If the paint has a shading we must create a tiling pattern and set
	 * that as stroke color...
	 */
	PDTilingPattern pattern = new PDTilingPattern();
	pattern.setPaintType(PDTilingPattern.PAINT_COLORED);
	pattern.setTilingType(PDTilingPattern.TILING_CONSTANT_SPACING_FASTER_TILING);
	PDRectangle anchorRect = bbox;
	pattern.setBBox(anchorRect);
	pattern.setXStep(anchorRect.getWidth());
	pattern.setYStep(anchorRect.getHeight());

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

	PDPageContentStream imageContentStream = new PDPageContentStream(document, appearance,
			((COSStream) pattern.getCOSObject()).createOutputStream());
	imageContentStream.addRect(0, 0, anchorRect.getWidth(), anchorRect.getHeight());
	imageContentStream.clip();
	imageContentStream.shadingFill(shading);
	imageContentStream.close();

	PDColorSpace patternCS1 = new PDPattern(null);
	COSName tilingPatternName = xFormObject.getResources().add(pattern);
	PDColor patternColor = new PDColor(tilingPatternName, patternCS1);

	contentStream.setNonStrokingColor(patternColor);
	contentStream.setStrokingColor(patternColor);
}
 
Example 13
Project: BoxTable   File: Cell.java   Source Code and License Vote up 4 votes
/**
 * Renders this cell at the specified position
 * 
 * @param document
 *            The document this cell is rendered to
 * @param stream
 *            The PDPageContentStream used to render this cell
 * @param left
 *            The coordinate of the left edge of the cell
 * @param top
 *            The coordinate of the top edge of the cell
 * @param width
 *            The width the cell will be rendered
 * @param height
 *            The height the cell will be rendered
 * @throws IOException
 *             If writing to the stream fails
 */
public void render(final PDDocument document, final PDPageContentStream stream, final float left, final float top, final float width, final float height)
		throws IOException {

	if (background != null) {
		stream.setNonStrokingColor(background);
		stream.addRect(left, top - height, width, height);
		stream.fill();
	}

	drawBorder(stream, left, top, width, height);
}