Java Code Examples for org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject

The following are top voted examples for showing how to use org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject. 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: 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 2
Project: IDBuilderFX   File: ExtractPhoto.java   Source Code and License 7 votes vote down vote up
public static void findPhoto(String path,int empId) throws IOException, SQLException, Error{
		// Loading an existing document
		int imageFound=0;
		File file = new File(path);
		PDDocument document=PDDocument.load(file);
		PDPageTree list=document.getPages();
		for(PDPage page:list){						//check in all pages of pdf
			PDResources pdResources=page.getResources();		//get all resources
			for(COSName cosName:pdResources.getXObjectNames())		//loop for all resources
			{
				PDXObject pdxObject=pdResources.getXObject(cosName);
				 if (pdxObject instanceof PDImageXObject) {			//check that the resource is image
		                BufferedImage br=((PDImageXObject) pdxObject).getImage();
		                RgbImage im = RgbImageJ2se.toRgbImage(br);
		                // step #3 - convert image to greyscale 8-bits
		                RgbAvgGray toGray = new RgbAvgGray();
		                toGray.push(im);
		                // step #4 - initialize face detector with correct Haar profile
		                InputStream is  = ExtractPhoto.class.getResourceAsStream("/haar/HCSB.txt");
		                Gray8DetectHaarMultiScale detectHaar = new Gray8DetectHaarMultiScale(is, 1,40);
		                // step #5 - apply face detector to grayscale image
		                List<Rect> result= detectHaar.pushAndReturn(toGray.getFront());
		                if(result.size()!=0)
		                {
		                database.StorePhoto.storePhoto(empId,br);
		                imageFound=1;
		                break;
		                }
				 }
			}
			if(imageFound==1)
				break;
}
		System.out.println(imageFound);
		if(imageFound!=1){
			BufferedImage in = ImageIO.read(ExtractPhoto.class.getResource("/images/nopic.jpg"));
            database.StorePhoto.storePhoto(empId,in);
		}
	document.close();	
	}
 
Example 3
Project: kumoreg   File: StaffBadge2017.java   Source Code and License 7 votes vote down vote up
private void drawAgeImageFront(PDPage page, Attendee attendee) throws IOException {

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

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

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

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

    PDImageXObject xImage = PDImageXObject.createFromFile(imageFilename, document);
    Dimension scaledDim = getScaledDimension(
            new Dimension(xImage.getWidth(),  xImage.getHeight()),
            new Dimension(149, 115));
    stream.drawImage(xImage,
            201 + ((149-scaledDim.width)/2),
            344 + ((158-scaledDim.height)/2),
            scaledDim.width, scaledDim.height);
    stream.close();
}
 
Example 5
Project: pdf-box-examples   File: PdfImagesHelper.java   Source Code and License 7 votes vote down vote up
private List<RenderedImage> getImagesFromResources(PDResources resources) throws IOException {

        List<RenderedImage> images = new ArrayList<>();
        for (COSName xObjectName : resources.getXObjectNames()) {
            PDXObject xObject = resources.getXObject(xObjectName);
            if (xObject instanceof PDImageXObject) {
                images.add(((PDImageXObject) xObject).getImage());
            } else if (xObject instanceof PDFormXObject) {
                images.addAll(getImagesFromResources(((PDFormXObject) xObject).getResources()));
            }
        }
        return images;
    }
 
Example 6
Project: pdfbox-layout   File: CompatibilityHelper.java   Source Code and License 7 votes vote down vote up
public static void drawImage(final BufferedImage image,
    final PDDocument document, final PDPageContentStream contentStream,
    Position upperLeft, final float width, final float height)
    throws IOException {
PDImageXObject cachedImage = getCachedImage(document, image);
float x = upperLeft.getX();
float y = upperLeft.getY() - height;
contentStream.drawImage(cachedImage, x, y, width, height);
   }
 
Example 7
Project: ph-pdf-layout   File: PDPageContentStreamExt.java   Source Code and License 7 votes vote down vote up
/**
 * Draw an image at the x,y coordinates, with the given size.
 *
 * @param image
 *        The image to draw.
 * @param x
 *        The x-coordinate to draw the image.
 * @param y
 *        The y-coordinate to draw the image.
 * @param width
 *        The width to draw the image.
 * @param height
 *        The height to draw the image.
 * @throws IOException
 *         If there is an error writing to the stream.
 * @throws IllegalStateException
 *         If the method was called within a text block.
 */
public void drawImage (final PDImageXObject image,
                       final float x,
                       final float y,
                       final float width,
                       final float height) throws IOException
{
  if (inTextMode)
  {
    throw new IllegalStateException ("Error: drawImage is not allowed within a text block.");
  }

  saveGraphicsState ();

  final AffineTransform transform = new AffineTransform (width, 0, 0, height, x, y);
  transform (new Matrix (transform));

  writeOperand (resources.add (image));
  writeOperator ((byte) 'D', (byte) 'o');

  restoreGraphicsState ();
}
 
Example 8
Project: pdfbox-graphics2d   File: PdfBoxGraphics2D.java   Source Code and License 6 votes vote down vote up
public boolean drawImage(Image img, AffineTransform xform, ImageObserver obs) {
	AffineTransform tf = new AffineTransform();
	tf.concatenate(baseTransform);
	tf.concatenate(transform);
	tf.concatenate((AffineTransform) xform.clone());

	PDImageXObject pdImage = imageEncoder.encodeImage(document, contentStream, img);
	try {
		contentStreamSaveState();
		int imgHeight = img.getHeight(obs);
		tf.translate(0, imgHeight);
		tf.scale(1, -1);
		contentStream.transform(new Matrix(tf));

		Object keyInterpolation = renderingHints.get(RenderingHints.KEY_INTERPOLATION);
		if (RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR.equals(keyInterpolation))
			pdImage.setInterpolate(false);
		contentStream.drawImage(pdImage, 0, 0, img.getWidth(obs), imgHeight);
		contentStreamRestoreState();
	} catch (IOException e) {
		throwException(e);
	}
	return true;
}
 
Example 9
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 10
Project: oma-riista-web   File: HunterPaymentPdfFeature.java   Source Code and License 6 votes vote down vote up
public PaymentPdfBuilder barCode(final String barCodeMessage,
                                 final float x,
                                 final float y) throws IOException {
    final float scale = 100f / BAR_CODE_DPI;
    final Code128Bean code128Bean = new Code128Bean();
    code128Bean.setCodeset(Code128Constants.CODESET_C);
    code128Bean.setMsgPosition(HumanReadablePlacement.HRP_NONE);
    code128Bean.setBarHeight(scale * BAR_CODE_HEIGHT_MM);

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

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

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

    return this;
}
 
Example 11
Project: pdfcompare   File: ResourceCacheWithLimitedImages.java   Source Code and License 6 votes vote down vote up
@Override
public void put(COSObject indirect, PDXObject xobject) throws IOException {
    final int length = xobject.getStream().getLength();
    if (length > Environment.getMaxImageSize()) {
        LOG.trace("Not caching image with Size: {}", length);
        return;
    }
    if (xobject instanceof PDImageXObject) {
        PDImageXObject imageObj = (PDImageXObject) xobject;
        if (imageObj.getWidth() * imageObj.getHeight() > Environment.getMaxImageSize()) {
            return;
        }
    }
    this.xobjects.put(indirect, new SoftReference(xobject));
}
 
Example 12
Project: kumoreg   File: StaffBadge2017.java   Source Code and License 6 votes vote down vote up
private void drawImage(PDPage page, Attendee attendee) throws IOException {
        String imageFilename = BadgeLib.getStaffImageFilename(attendee);
        if (imageFilename == null) {
            imageFilename = BadgeLib.getMascotImageFilename();
        }

        PDImageXObject xImage;
        try (PDPageContentStream stream = new PDPageContentStream(document, page, PDPageContentStream.AppendMode.APPEND, true, false)) {
            xImage = PDImageXObject.createFromFile(imageFilename, document);
            Dimension scaledDim = getScaledDimension(
                    new Dimension(xImage.getWidth(),  xImage.getHeight()),
                    new Dimension(149, 158));
            stream.drawImage(xImage,
                    150 + ((149-scaledDim.width)/2),
                    334 + ((158-scaledDim.height)/2),
                    scaledDim.width, scaledDim.height);
//            stream.fillRect(150, 334, 149, 158);
            stream.close();
        } catch (IIOException ex) {
            System.out.println("Error opening " + imageFilename);
        }
    }
 
Example 13
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 14
Project: testarea-pdfbox2   File: ExtractImages.java   Source Code and License 6 votes vote down vote up
/**
 * <a href="http://stackoverflow.com/questions/40531871/how-can-i-check-if-pdf-page-is-imagescanned-by-pdfbox-xpdf">
 * How can I check if PDF page is image(scanned) by PDFBOX, XPDF
 * </a>
 * <br/>
 * <a href="https://drive.google.com/file/d/0B9izTHWJQ7xlT2ZoQkJfbGRYcFE">
 * 10948.pdf
 * </a>
 * <p>
 * The only special thing about the two images returned for the sample PDF is that
 * one image is merely a mask used for the other image, and the other image is the
 * actual image used on the PDF page. If one only wants the images immediately used
 * in the page content, one also has to scan the page content.
 * </p>
 */
@Test
public void testExtractPageImageResources10948() throws IOException
{
    try (   InputStream resource = getClass().getResourceAsStream("10948.pdf"))
    {
        PDDocument document = PDDocument.load(resource);
        int page = 1;
        for (PDPage pdPage : document.getPages())
        {
            PDResources resources = pdPage.getResources();
            if (resource != null)
            {
                int index = 0;
                for (COSName cosName : resources.getXObjectNames())
                {
                    PDXObject xobject = resources.getXObject(cosName);
                    if (xobject instanceof PDImageXObject)
                    {
                        PDImageXObject image = (PDImageXObject)xobject;
                        File file = new File(RESULT_FOLDER, String.format("10948-%s-%s.%s", page, index, image.getSuffix()));
                        ImageIO.write(image.getImage(), image.getSuffix(), file);
                        index++;
                    }
                }
            }
            page++;
        }
    }
}
 
Example 15
Project: testarea-pdfbox2   File: ExtractImages.java   Source Code and License 6 votes vote down vote up
/**
 * <a href="http://stackoverflow.com/questions/40531871/how-can-i-check-if-pdf-page-is-imagescanned-by-pdfbox-xpdf">
 * How can I check if PDF page is image(scanned) by PDFBOX, XPDF
 * </a>
 * <br/>
 * <a href="https://drive.google.com/open?id=0B9izTHWJQ7xlYi1XN1BxMmZEUGc">
 * 10948.pdf
 * </a>, renamed "10948-new.pdf" here to prevent a collision
 * <p>
 * Here the code extracts no image at all because the images are not immediate page
 * resources but wrapped in form xobjects.
 * </p>
 */
@Test
public void testExtractPageImageResources10948New() throws IOException
{
    try (   InputStream resource = getClass().getResourceAsStream("10948-new.pdf"))
    {
        PDDocument document = PDDocument.load(resource);
        int page = 1;
        for (PDPage pdPage : document.getPages())
        {
            PDResources resources = pdPage.getResources();
            if (resource != null)
            {
                int index = 0;
                for (COSName cosName : resources.getXObjectNames())
                {
                    PDXObject xobject = resources.getXObject(cosName);
                    if (xobject instanceof PDImageXObject)
                    {
                        PDImageXObject image = (PDImageXObject)xobject;
                        File file = new File(RESULT_FOLDER, String.format("10948-new-%s-%s.%s", page, index, image.getSuffix()));
                        ImageIO.write(image.getImage(), image.getSuffix(), file);
                        index++;
                    }
                }
            }
            page++;
        }
    }
}
 
Example 16
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");
}
 
Example 17
Project: pdf-box-examples   File: PdfImagesHelper.java   Source Code and License 6 votes vote down vote up
private void drawXObject(PDImageXObject xobject, PDResources resources, OutputStream os,
                         float x, float y, float width, float height) throws IOException {
    // This is similar to PDPageContentStream.drawXObject()
    COSName xObjectId = resources.add(xobject);

    appendRawCommands(os, SAVE_GRAPHICS_STATE);
    appendRawCommands(os, formatDecimal.format(width));
    appendRawCommands(os, SPACE);
    appendRawCommands(os, formatDecimal.format(0));
    appendRawCommands(os, SPACE);
    appendRawCommands(os, formatDecimal.format(0));
    appendRawCommands(os, SPACE);
    appendRawCommands(os, formatDecimal.format(height));
    appendRawCommands(os, SPACE);
    appendRawCommands(os, formatDecimal.format(x));
    appendRawCommands(os, SPACE);
    appendRawCommands(os, formatDecimal.format(y));
    appendRawCommands(os, SPACE);
    appendRawCommands(os, CONCATENATE_MATRIX);
    appendRawCommands(os, SPACE);
    appendRawCommands(os, "/");
    appendRawCommands(os, xObjectId.getName());
    appendRawCommands(os, SPACE);
    appendRawCommands(os, XOBJECT_DO);
    appendRawCommands(os, SPACE);
    appendRawCommands(os, RESTORE_GRAPHICS_STATE);
}
 
Example 18
Project: polygene-java   File: PDFWriter.java   Source Code and License 6 votes vote down vote up
private void writeGraphPage( GraphDisplay graphDisplay )
    throws IOException
{
    File tFile = File.createTempFile( "envisage", ".png" );
    graphDisplay.saveImage( new FileOutputStream( tFile ), "png", 1d );

    BufferedImage img = ImageIO.read( tFile );

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

    int inset = 40;
    PDRectangle pdRect = new PDRectangle( w + inset, h + inset );
    PDPage page = new PDPage();
    page.setMediaBox( pdRect );
    doc.addPage( page );

    PDImageXObject xImage = PDImageXObject.createFromFileByExtension( tFile, doc );

    PDPageContentStream contentStream = new PDPageContentStream( doc, page );
    contentStream.drawImage( xImage, ( pdRect.getWidth() - w ) / 2, ( pdRect.getHeight() - h ) / 2 );
    contentStream.close();
}
 
Example 19
Project: kumoreg   File: StaffBadge2017.java   Source Code and License 6 votes vote down vote up
private void drawAgeImageFront(PDPage page, Attendee attendee) throws IOException {

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

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

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

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

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

        PDImageXObject xImage;
        try (PDPageContentStream stream = new PDPageContentStream(document, page, PDPageContentStream.AppendMode.APPEND, true, false)) {
            xImage = PDImageXObject.createFromFile(imageFilename, document);
            Dimension scaledDim = getScaledDimension(
                    new Dimension(xImage.getWidth(),  xImage.getHeight()),
                    new Dimension(149, 158));
            stream.drawImage(xImage,
                    150 + ((149-scaledDim.width)/2),
                    334 + ((158-scaledDim.height)/2),
                    scaledDim.width, scaledDim.height);
//            stream.fillRect(150, 334, 149, 158);
            stream.close();
        } catch (IIOException ex) {
            System.out.println("Error opening " + imageFilename);
        }
    }
 
Example 22
Project: CSSBoxPdf   File: PDFRenderer.java   Source Code and License 6 votes vote down vote up
/**
 * Inserts image to recent PDF page using PDFBox
 */
private int insertImagePDFBox (BufferedImage img, float x, float y, float width, float height) {
	// transform X,Y coordinates to Apache PDFBox format
    y = pageFormat.getHeight() - height - y;

    try {
        //PDXObjectImage ximage = new PDPixelMap(doc, img);
        //content.drawXObject(ximage, x, y, width, height);
        PDImageXObject ximage = LosslessFactory.createFromImage(doc, img);
        content.drawImage(ximage, x, y, width, height);
    } catch (IOException e) {
    	e.printStackTrace();
        return -1;	
    }
    return 0;
}
 
Example 23
Project: Pdf2Dom   File: PDFBoxTree.java   Source Code and License 6 votes vote down vote up
protected void processImageOperation(List<COSBase> arguments) throws IOException
{
    COSName objectName = (COSName)arguments.get( 0 );
    PDXObject xobject = getResources().getXObject( objectName );
    if (xobject instanceof PDImageXObject)
    {
        PDImageXObject pdfImage = (PDImageXObject) xobject;
        BufferedImage outputImage = pdfImage.getImage();
        outputImage = rotateImage(outputImage);

        ImageResource imageData = new ImageResource(getTitle(), outputImage);

        Rectangle2D bounds = calculateImagePosition(pdfImage);
        float x = (float) bounds.getX();
        float y = (float) bounds.getY();

        renderImage(x, y, (float) bounds.getWidth(), (float) bounds.getHeight(), imageData);
    }
}
 
Example 24
Project: ph-pdf-layout   File: PLStreamImage.java   Source Code and License 6 votes vote down vote up
@Override
@Nonnull
protected PDImageXObject getXObject (@Nonnull final PagePreRenderContext aCtx) throws IOException
{
  // The input stream is only sometimes closed automatically
  final InputStream aIS = m_aIIS.getInputStream ();
  if (aIS == null)
    throw new IOException ("Failed to open InputStream from " + m_aIIS);

  try (final InputStream aRealIS = aIS)
  {
    final byte [] aBytes = StreamHelper.getAllBytes (aRealIS);
    switch (getImageType ())
    {
      case CCITT:
        return CCITTFactory.createFromByteArray (aCtx.getDocument (), aBytes);
      case JPEG:
        return JPEGFactory.createFromByteArray (aCtx.getDocument (), aBytes);
      case LOSSLESS:
        // API does not support it
        throw new IllegalStateException ("Lossless images cannot be read from Stream - use the version with BufferedImage!");
      default:
        throw new IllegalStateException ("Unsupported image type: " + toString ());
    }
  }
}
 
Example 25
Project: ph-pdf-layout   File: PLImage.java   Source Code and License 6 votes vote down vote up
@Override
@Nonnull
protected PDImageXObject getXObject (@Nonnull final PagePreRenderContext aCtx) throws IOException
{
  switch (getImageType ())
  {
    case CCITT:
      return CCITTFactory.createFromImage (aCtx.getDocument (), m_aImage);
    case JPEG:
      return JPEGFactory.createFromImage (aCtx.getDocument (), m_aImage);
    case LOSSLESS:
      return LosslessFactory.createFromImage (aCtx.getDocument (), m_aImage);
    default:
      throw new IllegalStateException ("Unsupported image type: " + toString ());
  }
}
 
Example 26
Project: peten   File: GreyscaleLosslessFactory.java   Source Code and License 5 votes vote down vote up
/**
 * Creates a new GREYSCALE lossless encoded Image XObject from a Buffered Image.
 *
 * @param document the document where the image will be created
 * @param image the buffered image to embed
 * @return a new Image XObject
 * @throws IOException if something goes wrong
 */
public static PDImageXObject createFromImage(PDDocument document, BufferedImage image)
        throws IOException
{
    int bpc;
    PDDeviceColorSpace deviceColorSpace;

    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    int height = image.getHeight();
    int width = image.getWidth();

    if (image.getType() == BufferedImage.TYPE_BYTE_GRAY && image.getColorModel().getPixelSize() == 8)
    {
        // grayscale images need one color per sample
        bpc = image.getColorModel().getPixelSize();
        deviceColorSpace = PDDeviceGray.INSTANCE;
        DataBufferByte backingByteBuffer = (DataBufferByte)image.getData().getDataBuffer();
        bos.write(backingByteBuffer.getData());
    }
    else
    {
        throw new IOException("Expected greyscale image, with no alpha channel.");
    }

    PDImageXObject pdImage = prepareImageXObject(document, bos.toByteArray(), 
            image.getWidth(), image.getHeight(), bpc, deviceColorSpace);

    if (image.getColorModel().hasAlpha()) {
    	throw new IOException("No alpha support.");
    }
    
    return pdImage;
}
 
Example 27
Project: peten   File: GreyscaleLosslessFactory.java   Source Code and License 5 votes vote down vote up
/**
 * Create a PDImageXObject while making a decision whether not to 
 * compress, use Flate filter only, or Flate and LZW filters.
 * 
 * @param document The document.
 * @param byteArray array with data.
 * @param width the image width
 * @param height the image height
 * @param bitsPerComponent the bits per component
 * @param initColorSpace the color space
 * @return the newly created PDImageXObject with the data compressed.
 * @throws IOException 
 */
private static PDImageXObject prepareImageXObject(PDDocument document, 
        byte [] byteArray, int width, int height, int bitsPerComponent, 
        PDColorSpace initColorSpace) throws IOException
{
    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    Filter filter = FilterFactory.INSTANCE.getFilter(COSName.FLATE_DECODE);
    filter.encode(new ByteArrayInputStream(byteArray), baos, new COSDictionary(), 0);

    ByteArrayInputStream encodedByteStream = new ByteArrayInputStream(baos.toByteArray());
    return new PDImageXObject(document, encodedByteStream, COSName.FLATE_DECODE, 
            width, height, bitsPerComponent, initColorSpace);
}
 
Example 28
Project: pdfcompare   File: CompareResult.java   Source Code and License 5 votes vote down vote up
protected void addPageToDocument(final PDDocument document, final ImageWithDimension image) throws IOException {
    PDPage page = new PDPage(new PDRectangle(image.width, image.height));
    document.addPage(page);
    final PDImageXObject imageXObject = LosslessFactory.createFromImage(document, image.bufferedImage);
    try (PDPageContentStream contentStream = new PDPageContentStream(document, page)) {
        contentStream.drawImage(imageXObject, 0, 0, image.width, image.height);
    }
}
 
Example 29
Project: Gargoyle   File: PDFUtil.java   Source Code and License 5 votes vote down vote up
public static void toPdf(File newPdfFile, File imageFile) throws IOException {
	try (PDDocument doc = new PDDocument()) {
		PDPage pdPage = new PDPage();
		doc.addPage(pdPage);

		PDImageXObject pdImage = PDImageXObject.createFromFile(imageFile.getAbsolutePath(), doc);

		try (PDPageContentStream stream = new PDPageContentStream(doc, pdPage)) {
			stream.drawImage(pdImage, 0, 420);

		}

		doc.save(newPdfFile);
	}
}
 
Example 30
Project: testarea-pdfbox2   File: PlaceRotatedImage.java   Source Code and License 5 votes vote down vote up
/**
 * @see #testPlaceByBoundingBox()
 */
void placeImage(PDDocument document, PDPage page, PDImageXObject image, float bbLowerLeftX, float bbLowerLeftY, float width, float height, float angle) throws IOException {
    try (   PDPageContentStream contentStream = new PDPageContentStream(document, page, AppendMode.APPEND, true, true)   ) {
        float bbWidth = (float)(Math.abs(Math.sin(angle))*height + Math.abs(Math.cos(angle))*width);
        float bbHeight = (float)(Math.abs(Math.sin(angle))*width + Math.abs(Math.cos(angle))*height);
        contentStream.transform(Matrix.getTranslateInstance((bbLowerLeftX + .5f*bbWidth), (bbLowerLeftY + .5f*bbHeight)));
        contentStream.transform(Matrix.getRotateInstance(angle, 0, 0));
        contentStream.drawImage(image, -.5f*width, -.5f*height, width, height);
    }
}
 
Example 31
Project: pdf-box-examples   File: ImageExtractor.java   Source Code and License 5 votes vote down vote up
/**
 * This is used to handle an operation.
 *
 * @param operator The operation to perform.
 * @param operands The list of arguments.
 * @throws IOException If there is an error processing the operation.
 */
@Override
protected void processOperator(Operator operator, List<COSBase> operands) throws IOException {
    String operation = operator.getName();
    if (INVOKE_OPERATOR.equals(operation)) {
        COSName objectName = (COSName) operands.get(0);
        PDXObject xobject = getResources().getXObject(objectName);
        if (xobject instanceof PDImageXObject) {

            PDImageXObject image = (PDImageXObject) xobject;
            Matrix ctmNew = getGraphicsState().getCurrentTransformationMatrix();

            Image im = new Image();
            im.setPage(currentPage);
            im.setXPosition(ctmNew.getTranslateX());
            im.setYPosition(ctmNew.getTranslateY());
            im.setOriginalHeight(image.getHeight());
            im.setOriginalWidth(image.getWidth());
            im.setRenderedWidth(Math.round(ctmNew.getScaleX()));
            im.setRenderedHeight(Math.round(ctmNew.getScaleY()));
            images.add(im);

            if (!output.exists()) output.mkdirs();
            // TODO enable option to set the output format. right now it uses original which means: tiff needs extra dependency and tiff are HUGE!
            // String extension = "png";
            String extension = image.getSuffix();
            File out = new File(output, basename + "-" + currentPage + "-" + count + "." + extension);

            ImageIO.write(image.getImage(), extension, new FileOutputStream(out));
            count++;

        } else if (xobject instanceof PDFormXObject) {
            PDFormXObject form = (PDFormXObject) xobject;
            showForm(form);
        }
    } else {
        super.processOperator(operator, operands);
    }
}
 
Example 32
Project: pdfbox-layout   File: CompatibilityHelper.java   Source Code and License 5 votes vote down vote up
private static synchronized Map<BufferedImage, PDImageXObject> getImageCache(
    final PDDocument document) {
Map<String, Map<?, ?>> documentCache = getDocumentCache(document);
@SuppressWarnings("unchecked")
Map<BufferedImage, PDImageXObject> imageCache = (Map<BufferedImage, PDImageXObject>) documentCache
	.get(IMAGE_CACHE);
if (imageCache == null) {
    imageCache = new HashMap<BufferedImage, PDImageXObject>();
    documentCache.put(IMAGE_CACHE, imageCache);
}
return imageCache;
   }
 
Example 33
Project: pdfbox-layout   File: CompatibilityHelper.java   Source Code and License 5 votes vote down vote up
private static synchronized PDImageXObject getCachedImage(
    final PDDocument document, final BufferedImage image)
    throws IOException {
Map<BufferedImage, PDImageXObject> imageCache = getImageCache(document);
PDImageXObject pdxObjectImage = imageCache.get(image);
if (pdxObjectImage == null) {
    pdxObjectImage = LosslessFactory.createFromImage(document, image);
    imageCache.put(image, pdxObjectImage);
}
return pdxObjectImage;
   }
 
Example 34
Project: paint   File: PDFUtils.java   Source Code and License 5 votes vote down vote up
/**
 * Test: Create pdf from image and pdf file.
 *
 * @param _inputFile 	pdf input
 * @param _imagePath 	image input
 * @param _outputFile 	pdf output
 *
 * @throws IOException occurs if reading the data fails.
 */
public void saveAsPdf(
	 String _imagePath, String _outputFile )
        throws IOException{

	
	
	PDDocument doc = null;
    try
    {
    	
    	// create new document and insert empty page to the document.
    	doc = new PDDocument();
        PDPage page = new PDPage();
        doc.addPage(page);

        // createFromFile is the easiest way with an image file
        // if you already have the image in a BufferedImage, 
        // call LosslessFactory.createFromImage() instead
        PDImageXObject pdImage = PDImageXObject.createFromFile(_imagePath, doc);
        PDPageContentStream contentStream = new PDPageContentStream(doc, page, true, true);

        // contentStream.drawImage(ximage, 20, 20 );
        // better method inspired by http://stackoverflow.com/a/22318681/535646
        // reduce this value if the image is too large
        float scale = 1f;
        contentStream.drawImage(pdImage, 20, 20, pdImage.getWidth()*scale, pdImage.getHeight()*scale);

        contentStream.close();
        doc.save( _outputFile );
    }
    finally
    {
        if( doc != null )
        {
            doc.close();
        }
    }
}
 
Example 35
Project: paint   File: PdfTest.java   Source Code and License 5 votes vote down vote up
/**
 * Test: Create pdf from image and pdf file.
 *
 * @param _inputFile 	pdf input
 * @param _imagePath 	image input
 * @param _outputFile 	pdf output
 *
 * @throws IOException occurs if reading the data fails.
 */
public void createPDFFromImage(
		String _inputFile, String _imagePath, String _outputFile )
        throws IOException
{

	PDDocument doc = null;
    try
    {
    	
    	doc = new PDDocument();
        //doc = PDDocument.load( new File(_inputFile) );

        //we will add the image to the first page.
        PDPage page = doc.getPage(0);

        // createFromFile is the easiest way with an image file
        // if you already have the image in a BufferedImage, 
        // call LosslessFactory.createFromImage() instead
        PDImageXObject pdImage = PDImageXObject.createFromFile(_imagePath, doc);
        PDPageContentStream contentStream = new PDPageContentStream(doc, page, true, true);

        // contentStream.drawImage(ximage, 20, 20 );
        // better method inspired by http://stackoverflow.com/a/22318681/535646
        // reduce this value if the image is too large
        float scale = 1f;
        contentStream.drawImage(pdImage, 20, 20, pdImage.getWidth()*scale, pdImage.getHeight()*scale);

        contentStream.close();
        doc.save( _outputFile );
    }
    finally
    {
        if( doc != null )
        {
            doc.close();
        }
    }
}
 
Example 36
Project: Pdf2Dom   File: PDFBoxTree.java   Source Code and License 5 votes vote down vote up
private Rectangle2D calculateImagePosition(PDImageXObject pdfImage) throws IOException
{
    Matrix ctm = getGraphicsState().getCurrentTransformationMatrix();
    Rectangle2D imageBounds = pdfImage.getImage().getRaster().getBounds();

    AffineTransform imageTransform = new AffineTransform(ctm.createAffineTransform());
    imageTransform.scale(1.0 / pdfImage.getWidth(), -1.0 / pdfImage.getHeight());
    imageTransform.translate(0, -pdfImage.getHeight());

    AffineTransform pageTransform = createCurrentPageTransformation();
    pageTransform.concatenate(imageTransform);

    return pageTransform.createTransformedShape(imageBounds).getBounds2D();
}
 
Example 37
Project: ph-pdf-layout   File: PDPageContentStreamWithCache.java   Source Code and License 5 votes vote down vote up
public void drawXObject (final PDImageXObject aImage,
                         final float fX,
                         final float fY,
                         final float fWidth,
                         final float fHeight) throws IOException
{
  m_aStream.drawImage (aImage, fX, fY, fWidth, fHeight);
}
 
Example 38
Project: BoxTable   File: ImageCell.java   Source Code and License 4 votes vote down vote up
@Override
public void render(final PDDocument document, final PDPageContentStream stream, final float left, final float top, final float width, final float height)
		throws IOException {
	final BufferedImage image = ImageIO.read(file);

	float contentWidth = width - (leftBorder + rightBorder) / 2 - leftPadding - rightPadding;
	float contentHeight = height - (topBorder + bottomBorder) / 2 - topPadding - bottomPadding;

	float imgWidth = image.getWidth();
	float imgHeight = image.getHeight();
	final float ratio = imgWidth / imgHeight;
	if (imgWidth > contentWidth) {
		imgWidth = contentWidth;
		imgHeight = 1 / ratio * imgWidth;
	}
	if (imgHeight > contentHeight) {
		imgHeight = contentHeight;
		imgWidth = ratio * imgHeight;
	}

	super.render(document, stream, left + (width - imgWidth) * hAlign, top - (height - imgHeight) * vAlign, imgWidth, imgHeight);

	final PDImageXObject imageObject = JPEGFactory.createFromImage(document, image);
	stream.drawImage(imageObject, left + (width - imgWidth) * hAlign + leftBorder / 2 + leftPadding,
			top - height + (height - imgHeight) * (1 - vAlign) - topBorder / 2 - topPadding,
			imgWidth, imgHeight);
}
 
Example 39
Project: PrintDF   File: PrintDF.java   Source Code and License 4 votes vote down vote up
public static PDImageXObject pageToImage(PDDocument doc, int page, int scale) throws IOException {
	// return empty pages if page number excedes number of pages
	if(page >= doc.getNumberOfPages()) 
		return null;
	
	PDFRenderer pdfRenderer = new PDFRenderer(doc);
	BufferedImage bim = pdfRenderer.renderImage(page, scale);
	PDImageXObject img = JPEGFactory.createFromImage(doc, bim);
	
	return img;
}
 
Example 40
Project: AwesomeJavaLibraryExamples   File: ExampleAddImage.java   Source Code and License 4 votes vote down vote up
private static void createFinalDocument(File pdfFile, File overlayPdf) throws IOException
{
   PDDocument doc = new PDDocument();

   try
   {
      PDPage page = new PDPage();

      doc.addPage(page);
      PDImageXObject pdImage =JPEGFactory.createFromStream(doc, new AutoCloseInputStream(ExampleAddImage.class.getClassLoader().getResourceAsStream("death-star-plans.jpg")));
      PDPageContentStream contentStream = new PDPageContentStream(doc, page, PDPageContentStream.AppendMode.APPEND, true);
      Map<Integer, String> overlayGuide = new HashMap<>();

      contentStream.drawImage(pdImage, 100, 300, pdImage.getWidth()*scale, pdImage.getHeight()*scale);

      overlayGuide.put(1, overlayPdf.getAbsolutePath());
      Overlay overlay = new Overlay();
      overlay.setInputPDF(doc);
      overlay.setOverlayPosition(Overlay.Position.FOREGROUND);
      overlay.overlay(overlayGuide);

      contentStream.close();
      doc.save(pdfFile);
   }
   finally
   {
      doc.close();
   }
}