Java Code Examples for org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject#createFromByteArray()

The following examples show how to use org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject#createFromByteArray() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: VerticalTextCellTest.java    From easytable with MIT License 6 votes vote down vote up
@Before
public void before() throws IOException {
    PDDocument document = new PDDocument();

    // Load a custom font
    final InputStream resourceAsStream = this.getClass()
                                            .getClassLoader()
                                            .getResourceAsStream("OpenSansCondensed-Light.ttf");

    ownFont = PDType0Font.load(document, resourceAsStream);

    // Load custom image
    final byte[] sampleBytes = IOUtils.toByteArray(Objects.requireNonNull(this.getClass().getClassLoader()
                                            .getResourceAsStream("check.png")));
    checkImage = PDImageXObject.createFromByteArray(document, sampleBytes, "check");
}
 
Example 2
Source File: ImageCellTest.java    From easytable with MIT License 5 votes vote down vote up
@Test
public void getHeight_shouldThrowExceptionIfTableNotYetBuilt() throws IOException {
    final byte[] bytes = IOUtils.toByteArray(getClass().getClassLoader().getResourceAsStream("pic1.jpg"));
    final PDImageXObject image = PDImageXObject.createFromByteArray(new PDDocument(), bytes, "test1");

    AbstractCell cell = ImageCell.builder().image(image).build();

    exception.expect(TableNotYetBuiltException.class);
    cell.getHeight();
}
 
Example 3
Source File: AddImage.java    From testarea-pdfbox2 with Apache License 2.0 5 votes vote down vote up
/**
 * <a href="https://stackoverflow.com/questions/49958604/draw-image-at-mid-position-using-pdfbox-java">
 * Draw image at mid position using pdfbox Java
 * </a>
 * <p>
 * This is the OP's original code. It mirrors the image.
 * This can be fixed as shown in {@link #testImageAppendNoMirror()}.
 * </p>
 */
@Test
public void testImageAppendLikeShanky() throws IOException {
    try (   InputStream resource = getClass().getResourceAsStream("/mkl/testarea/pdfbox2/sign/test.pdf");
            InputStream imageResource = getClass().getResourceAsStream("Willi-1.jpg")   )
    {
        PDDocument doc = Loader.loadPDF(resource);
        PDImageXObject pdImage = PDImageXObject.createFromByteArray(doc, ByteStreams.toByteArray(imageResource), "Willi");

        int w = pdImage.getWidth();
        int h = pdImage.getHeight();

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

        float x_pos = page.getCropBox().getWidth();
        float y_pos = page.getCropBox().getHeight();

        float x_adjusted = ( x_pos - w ) / 2;
        float y_adjusted = ( y_pos - h ) / 2;

        Matrix mt = new Matrix(1f, 0f, 0f, -1f, page.getCropBox().getLowerLeftX(), page.getCropBox().getUpperRightY());
        contentStream.transform(mt);
        contentStream.drawImage(pdImage, x_adjusted, y_adjusted, w, h);
        contentStream.close();

        doc.save(new File(RESULT_FOLDER, "test-with-image-shanky.pdf"));
        doc.close();

    }
}
 
Example 4
Source File: AddImage.java    From testarea-pdfbox2 with Apache License 2.0 5 votes vote down vote up
/**
 * <a href="https://stackoverflow.com/questions/49958604/draw-image-at-mid-position-using-pdfbox-java">
 * Draw image at mid position using pdfbox Java
 * </a>
 * <p>
 * This is a fixed version of the the OP's original code, cf.
 * {@link #testImageAppendLikeShanky()}. It does not mirrors the image.
 * </p>
 */
@Test
public void testImageAppendNoMirror() throws IOException {
    try (   InputStream resource = getClass().getResourceAsStream("/mkl/testarea/pdfbox2/sign/test.pdf");
            InputStream imageResource = getClass().getResourceAsStream("Willi-1.jpg")   )
    {
        PDDocument doc = Loader.loadPDF(resource);
        PDImageXObject pdImage = PDImageXObject.createFromByteArray(doc, ByteStreams.toByteArray(imageResource), "Willi");

        int w = pdImage.getWidth();
        int h = pdImage.getHeight();

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

        float x_pos = page.getCropBox().getWidth();
        float y_pos = page.getCropBox().getHeight();

        float x_adjusted = ( x_pos - w ) / 2 + page.getCropBox().getLowerLeftX();
        float y_adjusted = ( y_pos - h ) / 2 + page.getCropBox().getLowerLeftY();

        contentStream.drawImage(pdImage, x_adjusted, y_adjusted, w, h);
        contentStream.close();

        doc.save(new File(RESULT_FOLDER, "test-with-image-no-mirror.pdf"));
        doc.close();

    }
}
 
Example 5
Source File: AddImage.java    From testarea-pdfbox2 with Apache License 2.0 5 votes vote down vote up
/**
 * <a href="https://stackoverflow.com/questions/50988007/clip-an-image-with-pdfbox">
 * Clip an image with PDFBOX
 * </a>
 * <p>
 * This test demonstrates how to clip an image and frame the clipping area.
 * </p>
 */
@SuppressWarnings("deprecation")
@Test
public void testImageAddClipped() throws IOException {
    try (   InputStream imageResource = getClass().getResourceAsStream("Willi-1.jpg")   )
    {
        PDDocument doc = new PDDocument();
        PDImageXObject pdImage = PDImageXObject.createFromByteArray(doc, ByteStreams.toByteArray(imageResource), "Willi");

        int w = pdImage.getWidth();
        int h = pdImage.getHeight();

        PDPage page = new PDPage();
        doc.addPage(page);
        PDRectangle cropBox = page.getCropBox();
        PDPageContentStream contentStream = new PDPageContentStream(doc, page);

        contentStream.setStrokingColor(25, 200, 25);
        contentStream.setLineWidth(4);
        contentStream.moveTo(cropBox.getLowerLeftX(), cropBox.getLowerLeftY() + h/2);
        contentStream.lineTo(cropBox.getLowerLeftX() + w/3, cropBox.getLowerLeftY() + 2*h/3);
        contentStream.lineTo(cropBox.getLowerLeftX() + w, cropBox.getLowerLeftY() + h/2);
        contentStream.lineTo(cropBox.getLowerLeftX() + w/3, cropBox.getLowerLeftY() + h/3);
        contentStream.closePath();
        //contentStream.clip();
        contentStream.appendRawCommands("W ");
        contentStream.stroke();

        contentStream.drawImage(pdImage, cropBox.getLowerLeftX(), cropBox.getLowerLeftY(), w, h);

        contentStream.close();

        doc.save(new File(RESULT_FOLDER, "image-clipped.pdf"));
        doc.close();
    }
}
 
Example 6
Source File: PlaceRotatedImage.java    From testarea-pdfbox2 with Apache License 2.0 5 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 7
Source File: NativePdfBoxVisibleSignatureDrawer.java    From dss with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Draws the given image with specified dimension and position
 * @param cs
 *		{@link PDPageContentStream} current stream
 * @param doc
 *		{@link PDDocument} to draw the picture on
 * @param dimensionAndPosition
 *		{@link SignatureFieldDimensionAndPosition} size and position to place the picture to
 * @param image
 *		{@link DSSDocument} image to draw
 * @throws IOException
 *		in case of error
 */
private void setImage(PDPageContentStream cs, PDDocument doc, SignatureFieldDimensionAndPosition dimensionAndPosition, 
		DSSDocument image) throws IOException {
	if (image != null) {
		try (InputStream is = image.openStream()) {
            cs.saveGraphicsState();
    		byte[] bytes = IOUtils.toByteArray(is);
    		PDImageXObject imageXObject = PDImageXObject.createFromByteArray(doc, bytes, image.getName());

    		// divide to scale factor, because PdfBox due to the matrix transformation also changes position parameters of the image
    		float xAxis = dimensionAndPosition.getImageX();
    		if (parameters.getTextParameters() != null)
    			xAxis *= dimensionAndPosition.getxDpiRatio();
    		float yAxis = dimensionAndPosition.getImageY();
    		if (parameters.getTextParameters() != null)
    			yAxis *= dimensionAndPosition.getyDpiRatio();
    		
    		float width = getWidth(dimensionAndPosition);
    		float height = getHeight(dimensionAndPosition);
    				
	        cs.drawImage(imageXObject, xAxis, yAxis, width, height);
			cs.transform(Matrix.getRotateInstance(((double) 360 - ImageRotationUtils.getRotation(parameters.getRotation())), width, height));
            
            cs.restoreGraphicsState();
		}
   	}
}
 
Example 8
Source File: NativePdfBoxVisibleSignatureDrawer.java    From dss with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
protected String getColorSpaceName(DSSDocument image) throws IOException {
	try (InputStream is = image.openStream()) {
		byte[] bytes = IOUtils.toByteArray(is);
		PDImageXObject imageXObject = PDImageXObject.createFromByteArray(document, bytes, image.getName());
		PDColorSpace colorSpace = imageXObject.getColorSpace();
		return colorSpace.getName();
	}
}
 
Example 9
Source File: PdfContentImagePreprocessor.java    From tika-server with Apache License 2.0 4 votes vote down vote up
private PDImageXObject makeImageObjectCopy(PDImageXObject img) throws IOException {
    BufferedImage flatImg = flattenImage(img.getImage());
    byte[] bytes = getImageBytes(flatImg);
    return PDImageXObject.createFromByteArray(document, bytes, "image");
}
 
Example 10
Source File: TestUtils.java    From easytable with MIT License 4 votes vote down vote up
public static PDImageXObject createTuxImage() throws IOException {
    final byte[] tuxBytes = IOUtils.toByteArray(Objects.requireNonNull(TestUtils.class.getClassLoader().getResourceAsStream("tux.png")));
    return PDImageXObject.createFromByteArray(PD_DOCUMENT_FOR_IMAGES, tuxBytes, "tux");
}
 
Example 11
Source File: TestUtils.java    From easytable with MIT License 4 votes vote down vote up
public static PDImageXObject createGliderImage() throws IOException {
    final byte[] gliderBytes = IOUtils.toByteArray(Objects.requireNonNull(TestUtils.class.getClassLoader().getResourceAsStream("glider.png")));
    return PDImageXObject.createFromByteArray(PD_DOCUMENT_FOR_IMAGES, gliderBytes, "glider");
}
 
Example 12
Source File: TestUtils.java    From easytable with MIT License 4 votes vote down vote up
public static PDImageXObject createSampleImage() throws IOException {
    final byte[] sampleBytes = IOUtils.toByteArray(Objects.requireNonNull(TestUtils.class.getClassLoader().getResourceAsStream("sample.png")));
    return PDImageXObject.createFromByteArray(PD_DOCUMENT_FOR_IMAGES, sampleBytes, "sample");
}
 
Example 13
Source File: ImagesTest.java    From easytable with MIT License 4 votes vote down vote up
@Test
public void testImage() throws Exception {

    final Table.TableBuilder tableBuilder = Table.builder()
            .addColumnsOfWidth(200, 200);

    final byte[] bytes1 = IOUtils.toByteArray(getClass().getClassLoader().getResourceAsStream("pic1.jpg"));
    final PDImageXObject image1 = PDImageXObject.createFromByteArray(new PDDocument(), bytes1, "test1");

    final byte[] bytes2 = IOUtils.toByteArray(getClass().getClassLoader().getResourceAsStream("pic2.jpg"));
    final PDImageXObject image2 = PDImageXObject.createFromByteArray(new PDDocument(), bytes2, "test2");

    tableBuilder.addRow(
            Row.builder()
                    .add(TextCell.builder().text("first").build())
                    .add(TextCell.builder().text("second").horizontalAlignment(RIGHT).build())
                    .build());


    tableBuilder.addRow(
            Row.builder()
                    .add(ImageCell.builder().image(image1).scale(0.13f).borderWidth(1).build())
                    .add(ImageCell.builder().image(image2).borderWidth(1).build())
                    .build());

    tableBuilder.addRow(
            Row.builder()
                    .add(TextCell.builder()
                            .text("images from \"https://www.techrepublic.com/pictures/the-21-best-it-and-tech-memes-on-the-internet/5/\"")
                            .colSpan(2)
                            .fontSize(6)
                            .borderWidth(1)
                            .build())
                    .build()
    );

    TestUtils.createAndSaveDocumentWithTable(FILE_NAME, tableBuilder.build());

    CompareResult compareResult = new PdfComparator<>(getExpectedPdfFor(FILE_NAME), getActualPdfFor(FILE_NAME)).compare();
    assertTrue(compareResult.isEqual());
}
 
Example 14
Source File: UseSoftMask.java    From testarea-pdfbox2 with Apache License 2.0 4 votes vote down vote up
/**
 * <a href="https://stackoverflow.com/questions/60198179/creating-a-transparency-group-or-setting-graphics-state-soft-mask-with-pdfbox">
 * Creating a transparency group or setting graphics state soft mask with PDFBox
 * </a>
 * <br/>
 * <a href="https://i.stack.imgur.com/rh9kL.png">
 * rh9kL.png
 * </a> as "Nicolas_image.png"
 * <br/>
 * <a href="https://i.stack.imgur.com/2UoKr.png">
 * 2UoKr.png
 * </a> as "Nicolas_mask.png"
 * <p>
 * This test demonstrates how one can apply transparency group
 * soft masks in extended graphics state parameters.
 * </p>
 */
@Test
public void testSoftMaskedImageAndRectangle() throws IOException {
    try (   PDDocument document = new PDDocument()  ) {
        final PDImageXObject image;
        try (   InputStream imageResource = getClass().getResourceAsStream("Nicolas_image.png")) {
            image = PDImageXObject.createFromByteArray(document, IOUtils.toByteArray(imageResource), "image");
        }

        final PDImageXObject mask;
        try (   InputStream imageResource = getClass().getResourceAsStream("Nicolas_mask.png")) {
            mask = PDImageXObject.createFromByteArray(document, IOUtils.toByteArray(imageResource), "mask");
        }

        PDTransparencyGroupAttributes transparencyGroupAttributes = new PDTransparencyGroupAttributes();
        transparencyGroupAttributes.getCOSObject().setItem(COSName.CS, COSName.DEVICEGRAY);

        PDTransparencyGroup transparencyGroup = new PDTransparencyGroup(document);
        transparencyGroup.setBBox(PDRectangle.A4);
        transparencyGroup.setResources(new PDResources());
        transparencyGroup.getCOSObject().setItem(COSName.GROUP, transparencyGroupAttributes);
        try (   PDFormContentStream canvas = new PDFormContentStream(transparencyGroup)   ) {
            canvas.drawImage(mask, new Matrix(400, 0, 0, 400, 100, 100));
        }

        COSDictionary softMaskDictionary = new COSDictionary();
        softMaskDictionary.setItem(COSName.S, COSName.LUMINOSITY);
        softMaskDictionary.setItem(COSName.G, transparencyGroup);

        PDExtendedGraphicsState extendedGraphicsState = new PDExtendedGraphicsState();
        extendedGraphicsState.getCOSObject().setItem(COSName.SMASK, softMaskDictionary);

        PDPage page = new PDPage(PDRectangle.A4);
        document.addPage(page);
        try (   PDPageContentStream canvas = new PDPageContentStream(document, page)   ) {
            canvas.saveGraphicsState();
            canvas.setGraphicsStateParameters(extendedGraphicsState);
            canvas.setNonStrokingColor(Color.BLACK);
            canvas.addRect(100, 100, 400, 400);
            canvas.fill();
            canvas.drawImage(image, new Matrix(400, 0, 0, 300, 100, 150));
            canvas.restoreGraphicsState();
        }

        document.save(new File(RESULT_FOLDER, "SoftMaskedImageAndRectangle.pdf"));
    }
}