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

The following are Jave code examples for showing how to use setNonStrokingColor() 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: pcm-api   File: PdfBoxServiceImpl.java   Source Code and License Vote up 8 votes
@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 2
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 3
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 4
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 5
Project: kumoreg   File: FullBadgePrintFormatter.java   Source Code and License Vote up 7 votes
private void drawAgeColorStripe(PDPageContentStream contentStream, PDFont font, Attendee attendee) throws IOException {
    // Draw age color stripe
    String stripeText = "VOID";
    if (attendee.getCurrentAgeRange() != null) {
        contentStream.setNonStrokingColor(Color.decode(attendee.getCurrentAgeRange().getStripeColor()));
        stripeText = attendee.getCurrentAgeRange().getStripeText();
    } else {
        contentStream.setNonStrokingColor(Color.black);
    }
    contentStream.fillRect(155, 92, 300, 45);

    contentStream.setLineWidth(0.5f);

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

    // Reset changed color
    resetChangedColorToDefault(contentStream);
}
 
Example 7
Project: pcm-api   File: PdfBoxServiceImpl.java   Source Code and License Vote up 7 votes
@Override
public void addWrappedParagraphByLineBreaks(String content, PDFont font, float fontSize, Color textColor, float yCoordinate, float leftRightMargin, PDPage page, PDPageContentStream contentStream) throws IOException {
    final float lineSpacing = 1.4f * fontSize;
    float width = page.getMediaBox().getWidth() - 2 * leftRightMargin;
    float startX = page.getMediaBox().getLowerLeftX() + leftRightMargin;

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

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

    // Reset changed color
    resetChangedColorToDefault(contentStream);
}
 
Example 8
Project: pdfbox-graphics2d   File: PdfBoxGraphics2DTestBase.java   Source Code and License Vote up 6 votes
@SuppressWarnings("SpellCheckingInspection")
void exportGraphic(String dir, String name, GraphicsExporter exporter) {
	try {
		PDDocument document = new PDDocument();

		PDFont pdArial = PDFontFactory.createDefaultFont();

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

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

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

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

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

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

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

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

		document.save(new File(parentDir, name + ".pdf"));
		document.close();
	} catch (Exception e) {
		throw new RuntimeException(e);
	}
}
 
Example 9
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 10
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 11
Project: kumoreg   File: FormatterBase.java   Source Code and License Vote up 6 votes
/**
 * Draws the given string, optionally supports scaling to fit.
 * @param x Left side of text, or center point of text if centered (1/72 inch)
 * @param y Bottom of text, in points (1/72 inch)
 * @param text Text to draw
 * @param optOrig Resize Options
 * @throws IOException Error generating PDF
 */
void drawStringWithResizing(PDPageContentStream stream, float x, float y, String text, ResizeOptions optOrig) throws IOException {
    ResizeOptions opt = new ResizeOptions(optOrig);
    float textSize = opt.font.getStringWidth(text); // in thousandths of font pt size.
    float size = opt.size;

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

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

    // Actually draw the text
    stream.beginText();
    stream.setStrokingColor(Color.black);
    stream.setNonStrokingColor(Color.black);
    stream.moveTextPositionByAmount(x, y);
    stream.setFont(opt.font, size);
    stream.drawString(text);
    stream.endText();
}
 
Example 12
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 13
Project: AwesomeJavaLibraryExamples   File: ExampleAddImage.java   Source Code and License Vote up 6 votes
private static void createOverlayDocument(File overlayPdf) throws IOException
{
   PDDocument overlayDoc = new PDDocument();

   try
   {
      PDPage page=new PDPage();

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

      PDPageContentStream contentStream=new PDPageContentStream(overlayDoc, page);
      contentStream.setFont(font, 50);
      contentStream.setNonStrokingColor(0);
      contentStream.beginText();
      contentStream.newLineAtOffset(100, 500);
      contentStream.setNonStrokingColor(255, 0, 0);
      contentStream.showText("CLASSIFIED");
      contentStream.endText();
      contentStream.close();
      overlayDoc.save(overlayPdf);
   }
   finally
   {
      overlayDoc.close();
   }
}
 
Example 14
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 15
Project: zest-writer   File: PdfUtilExport.java   Source Code and License Vote up 6 votes
private void addCoverpage() throws IOException {
    float leading = 1.5f * FONT_SIZE_TITLE;
    PDDocument document = new PDDocument();
    PDPage page = new PDPage();
    document.addPage(page);
    FONT_STYLE_COVER = PDTrueTypeFont.loadTTF(document, MainApp.class.getResourceAsStream(FONT_MERRIWEATHER_BOLD));
    PDPageContentStream contentStream = new PDPageContentStream(document, page);
    contentStream.setNonStrokingColor(25, 81, 107);
    contentStream.fillRect(0, 0, page.getMediaBox().getWidth(), (page.getMediaBox().getHeight() / 2) - 10);
    contentStream.fillRect(0, (page.getMediaBox().getHeight() / 2) + 10, page.getMediaBox().getWidth(), (page.getMediaBox().getHeight() / 2) - 10);
    contentStream.setNonStrokingColor(248, 173, 50);
    contentStream.fillRect(0, (page.getMediaBox().getHeight() / 2) - 10, page.getMediaBox().getWidth(), 20);

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

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

    PDFMergerUtility mergerUtility = new PDFMergerUtility();
    mergerUtility.addSource(temp);
    mergerUtility.addSource(destPdfPath);
    mergerUtility.setDestinationFileName(destPdfPath);
    mergerUtility.mergeDocuments();
}
 
Example 16
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 17
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 18
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 19
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 20
Project: kumoreg   File: LiteBadgePrintFormatter.java   Source Code and License Vote up 5 votes
private PDPage generatePage(Attendee attendee, PDDocument document) throws IOException {
    PDPage page = new PDPage(new PDRectangle(612f, 396f));
    PDFont font = PDType1Font.HELVETICA_BOLD;
    PDPageContentStream contentStream = new PDPageContentStream(document, page);

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

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

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

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

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

    contentStream.close();

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

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

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

    String ageString = BadgeLib.getAgeRangeAtCon(attendee, currentDateForAgeCalculation);
    if (ageString.toLowerCase().equals("adult")) {
        stream.showText("A");
        stream.newLineAtOffset(-1, -32);
        stream.showText("D");
        stream.newLineAtOffset(0, -32);
        stream.showText("U");
        stream.newLineAtOffset(2, -32);
        stream.showText("L");
        stream.newLineAtOffset(2, -32);
        stream.showText("T");
    } else if (ageString.toLowerCase().equals("youth")) {
        stream.showText("Y");
        stream.newLineAtOffset(-2, -32);
        stream.showText("O");
        stream.newLineAtOffset(0, -32);
        stream.showText("U");
        stream.newLineAtOffset(4, -32);
        stream.showText("T");
        stream.newLineAtOffset(-3, -32);
        stream.showText("H");
    } else if (ageString.toLowerCase().equals("child")) {
        stream.showText("C");
        stream.newLineAtOffset(0, -32);
        stream.showText("H");
        stream.newLineAtOffset(5, -32);
        stream.showText("I");
        stream.newLineAtOffset(-3, -32);
        stream.showText("L");
        stream.newLineAtOffset(-2, -32);
        stream.showText("D");
    } else {
        stream.showText("V");
        stream.newLineAtOffset(0, -32);
        stream.showText("O");
        stream.newLineAtOffset(5, -32);
        stream.showText("I");
        stream.newLineAtOffset(-5, -32);
        stream.showText("D");
    }
    stream.close();
}
 
Example 22
Project: pcm-api   File: PdfBoxServiceImpl.java   Source Code and License Vote up 5 votes
private void resetChangedColorToDefault(PDPageContentStream contentStream) throws IOException {
    contentStream.setNonStrokingColor(Color.BLACK);
}
 
Example 23
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);
}