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

The following examples show how to use org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject. 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: PdfContentImagePreprocessor.java    From tika-server with Apache License 2.0 7 votes vote down vote up
private void processImagesFromResources(PDResources resources) throws IOException {
    for (COSName xObjectName : resources.getXObjectNames()) {
        PDXObject xObject = resources.getXObject(xObjectName);

        if (xObject instanceof PDFormXObject) {
            processImagesFromResources(((PDFormXObject) xObject).getResources());
        } else if (xObject instanceof PDImageXObject) {
            PDImageXObject img = (PDImageXObject) xObject;
            if (!img.getImage().getColorModel().hasAlpha())
                return;

            PDImageXObject cpy = makeImageObjectCopy(img);
            resources.put(xObjectName, cpy);
            imagesWereChanged = true;
        }
    }
}
 
Example #2
Source File: PDFBoxTree.java    From Pdf2Dom with GNU Lesser General Public License v3.0 6 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 #3
Source File: PDFCreator.java    From Knowage-Server with GNU Affero General Public License v3.0 6 votes vote down vote up
private static void createPDF(List<InputStream> inputImages, Path output) throws IOException {
	PDDocument document = new PDDocument();
	try {
		for (InputStream is : inputImages) {
			BufferedImage bimg = ImageIO.read(is);
			float width = bimg.getWidth();
			float height = bimg.getHeight();
			PDPage page = new PDPage(new PDRectangle(width, height));
			document.addPage(page);

			PDImageXObject img = LosslessFactory.createFromImage(document, bimg);
			try (PDPageContentStream contentStream = new PDPageContentStream(document, page)) {
				contentStream.drawImage(img, 0, 0);
			}
		}
		document.save(output.toFile());
	} finally {
		document.close();
	}
}
 
Example #4
Source File: ImageSizingOnRowSpanningTest.java    From easytable with MIT License 6 votes vote down vote up
private Table createColSpanningTable(PDImageXObject glider) {
    final Table.TableBuilder tableBuilder = Table.builder()
            .addColumnsOfWidth(100, 100);
    // First row
    tableBuilder.addRow(
            Row.builder()
                    .add(TextCell.builder().rowSpan(2).text("Row span").borderWidth(1).build())
                    .add(ImageCell.builder().image(glider).borderWidth(1).build())
                    .build());

    // Second row
    tableBuilder.addRow(
            Row.builder()
                    .add(ImageCell.builder().image(glider).borderWidth(1).build())
                    .build());
    return tableBuilder.build();
}
 
Example #5
Source File: PDAbstractContentStream.java    From gcs with Mozilla Public License 2.0 6 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(PDImageXObject image, float x, float y, float width, float height) throws IOException
{
    if (inTextMode)
    {
        throw new IllegalStateException("Error: drawImage is not allowed within a text block.");
    }

    saveGraphicsState();

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

    writeOperand(resources.add(image));
    writeOperator(OperatorName.DRAW_OBJECT);

    restoreGraphicsState();
}
 
Example #6
Source File: DrawImage.java    From testarea-pdfbox2 with Apache License 2.0 6 votes vote down vote up
/**
 * <a href="https://stackoverflow.com/questions/58606529/pdf-size-too-large-generating-through-android-pdfdocument-and-while-using-pdfbo">
 * PDF size too large generating through Android PDFDocument. And while using pdfbox it is cutting image in output
 * </a>
 * <p>
 * This code shows how to draw an image onto a page with
 * the image "default size".
 * </p>
 */
@Test
public void testDrawImageToFitPage() throws IOException {
    try (   InputStream imageResource = getClass().getResourceAsStream("Willi-1.jpg")) {
        PDDocument document = new PDDocument();

        PDImageXObject ximage = JPEGFactory.createFromStream(document,imageResource);

        PDPage page = new PDPage(new PDRectangle(ximage.getWidth(), ximage.getHeight()));
        document.addPage(page);

        PDPageContentStream contentStream = new PDPageContentStream(document, page);
        contentStream.drawImage(ximage, 0, 0);
        contentStream.close();

        document.save(new File(RESULT_FOLDER, "Willi-1.pdf"));
        document.close();
    }
}
 
Example #7
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 #8
Source File: PDAbstractContentStream.java    From gcs with Mozilla Public License 2.0 6 votes vote down vote up
/**
 * Draw an image at the origin with the given transformation matrix.
 *
 * @param image The image to draw.
 * @param matrix The transformation matrix to apply to 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(PDImageXObject image, Matrix matrix) throws IOException
{
    if (inTextMode)
    {
        throw new IllegalStateException("Error: drawImage is not allowed within a text block.");
    }

    saveGraphicsState();

    AffineTransform transform = matrix.createAffineTransform();
    transform(new Matrix(transform));

    writeOperand(resources.add(image));
    writeOperator(OperatorName.DRAW_OBJECT);

    restoreGraphicsState();
}
 
Example #9
Source File: PDPageContentStream.java    From gcs with Mozilla Public License 2.0 6 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(PDImageXObject image, float x, float y, float width, float height) throws IOException
{
    if (inTextMode)
    {
        throw new IllegalStateException("Error: drawImage is not allowed within a text block.");
    }

    saveGraphicsState();

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

    writeOperand(resources.add(image));
    writeOperator(OperatorName.DRAW_OBJECT);

    restoreGraphicsState();
}
 
Example #10
Source File: PDPageContentStream.java    From gcs with Mozilla Public License 2.0 6 votes vote down vote up
/**
 * Draw an image at the origin with the given transformation matrix.
 *
 * @param image The image to draw.
 * @param matrix The transformation matrix to apply to 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(PDImageXObject image, Matrix matrix) throws IOException
{
    if (inTextMode)
    {
        throw new IllegalStateException("Error: drawImage is not allowed within a text block.");
    }

    saveGraphicsState();

    AffineTransform transform = matrix.createAffineTransform();
    transform(new Matrix(transform));

    writeOperand(resources.add(image));
    writeOperator(OperatorName.DRAW_OBJECT);

    restoreGraphicsState();
}
 
Example #11
Source File: PdfGenerator.java    From blog-tutorials with MIT License 6 votes vote down vote up
public byte[] createPdf() throws IOException {
  try (PDDocument document = new PDDocument()) {
    PDPage page = new PDPage(PDRectangle.A4);
    page.setRotation(90);

    float pageWidth = page.getMediaBox().getWidth();
    float pageHeight = page.getMediaBox().getHeight();

    PDPageContentStream contentStream = new PDPageContentStream(document, page);

    PDImageXObject chartImage = JPEGFactory.createFromImage(document,
      createChart((int) pageHeight, (int) pageWidth));

    contentStream.transform(new Matrix(0, 1, -1, 0, pageWidth, 0));
    contentStream.drawImage(chartImage, 0, 0);
    contentStream.close();

    document.addPage(page);

    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    document.save(byteArrayOutputStream);
    return byteArrayOutputStream.toByteArray();
  }

}
 
Example #12
Source File: PdfTools.java    From MyBox with Apache License 2.0 6 votes vote down vote up
public static List<PDImageXObject> getImageListFromPDF(PDDocument document,
        Integer startPage) throws Exception {
    List<PDImageXObject> imageList = new ArrayList<>();
    if (null != document) {
        PDPageTree pages = document.getPages();
        startPage = startPage == null ? 0 : startPage;
        int len = pages.getCount();
        if (startPage < len) {
            for (int i = startPage; i < len; ++i) {
                PDPage page = pages.get(i);
                Iterable<COSName> objectNames = page.getResources().getXObjectNames();
                for (COSName imageObjectName : objectNames) {
                    if (page.getResources().isImageXObject(imageObjectName)) {
                        imageList.add((PDImageXObject) page.getResources().getXObject(imageObjectName));
                    }
                }
            }
        }
    }
    return imageList;
}
 
Example #13
Source File: GraphicsParser.java    From tephra with MIT License 6 votes vote down vote up
private boolean clip(Matrix matrix, PDImageXObject pdImageXObject) throws IOException {
    if (clipTypes.isEmpty() || (clipTypes.size() == 1 && clipTypes.get(0).equals("rect")
            && Math.abs(matrix.getScaleX() / matrix.getScalingFactorY()
            - (clipArea[2] - clipArea[0]) / (clipArea[3] - clipArea[1])) <= 0.01D))
        return false;

    SVGGraphics2D svgGraphics2D = new SVGGraphics2D(GenericDOMImplementation.getDOMImplementation()
            .createDocument(SVGDOMImplementation.SVG_NAMESPACE_URI, "svg", null));
    if (pdImageXObject != null) {
        int w = (int) matrix.getScalingFactorX();
        int h = (int) matrix.getScalingFactorY();
        svgGraphics2D.clip(getPath(clipTypes, clipPoints, clipArea));
        svgGraphics2D.drawImage(pdImageXObject.getImage().getScaledInstance(w, h, Image.SCALE_SMOOTH),
                (int) (matrix.getTranslateX() - clipArea[0]), (int) (matrix.getTranslateY() - clipArea[1]), w, h, null);
    }
    save(svgGraphics2D, clipArea[0], clipArea[1], (clipArea[2] - clipArea[0]), (clipArea[3] - clipArea[1]));

    return true;
}
 
Example #14
Source File: PDVisibleSigBuilder.java    From gcs with Mozilla Public License 2.0 6 votes vote down vote up
@Override
public void createImageForm(PDResources imageFormResources, PDResources innerFormResource,
                            PDStream imageFormStream, PDRectangle bbox, AffineTransform at,
                            PDImageXObject img) throws IOException
{
    PDFormXObject imageForm = new PDFormXObject(imageFormStream);
    imageForm.setBBox(bbox);
    imageForm.setMatrix(at);
    imageForm.setResources(imageFormResources);
    imageForm.setFormType(1);

    imageFormResources.getCOSObject().setDirect(true);

    COSName imageFormName = COSName.getPDFName("n2");
    innerFormResource.put(imageFormName, imageForm);
    COSName imageName = imageFormResources.add(img, "img");
    pdfStructure.setImageForm(imageForm);
    pdfStructure.setImageFormName(imageFormName);
    pdfStructure.setImageName(imageName);
    LOG.info("Created image form");
}
 
Example #15
Source File: PDFWriter.java    From attic-polygene-java with Apache License 2.0 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 #16
Source File: PDFBoxTree.java    From Pdf2Dom with GNU Lesser General Public License v3.0 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 #17
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 #18
Source File: GraphicsParser.java    From tephra with MIT License 5 votes vote down vote up
private String getUrl(PDImageXObject pdImageXObject, MediaWriter mediaWriter, MediaType mediaType) throws IOException {
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    ImageIO.write(pdImageXObject.getImage(), pdImageXObject.getSuffix().toUpperCase(), outputStream);
    outputStream.close();

    ByteArrayInputStream inputStream = new ByteArrayInputStream(outputStream.toByteArray());
    String url = mediaWriter.write(mediaType, "pdf." + pdImageXObject.getSuffix(), inputStream);
    inputStream.close();

    return url;
}
 
Example #19
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 #20
Source File: ExtractImages.java    From testarea-pdfbox2 with Apache License 2.0 5 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 = Loader.loadPDF(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 #21
Source File: CompatibilityHelper.java    From pdfbox-layout with MIT 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 #22
Source File: CompatibilityHelper.java    From pdfbox-layout with MIT License 5 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 #23
Source File: ExtractImages.java    From testarea-pdfbox2 with Apache License 2.0 5 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 = Loader.loadPDF(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 #24
Source File: CompatibilityHelper.java    From pdfbox-layout with MIT 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 #25
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 #26
Source File: DrawObject.java    From gcs with Mozilla Public License 2.0 5 votes vote down vote up
@Override
public void process(Operator operator, List<COSBase> operands) throws IOException
{
    if (operands.isEmpty())
    {
        throw new MissingOperandException(operator, operands);
    }
    COSBase base0 = operands.get(0);
    if (!(base0 instanceof COSName))
    {
        return;
    }
    COSName objectName = (COSName) base0;
    PDXObject xobject = context.getResources().getXObject(objectName);

    if (xobject == null)
    {
        throw new MissingResourceException("Missing XObject: " + objectName.getName());
    }
    else if (xobject instanceof PDImageXObject)
    {
        PDImageXObject image = (PDImageXObject)xobject;
        context.drawImage(image);
    }
    else if (xobject instanceof PDTransparencyGroup)
    {
        getContext().showTransparencyGroup((PDTransparencyGroup) xobject);
    }
    else if (xobject instanceof PDFormXObject)
    {
        getContext().showForm((PDFormXObject) xobject);
    }
}
 
Example #27
Source File: CompareResultImpl.java    From pdfcompare with Apache License 2.0 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 #28
Source File: PDFPage.java    From Open-Lowcode with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * @param left        in page coordinates. This attribute and next defines the
 *                    top-left point for the image.
 * @param top         in page coordinates. This attribute and next defines the
 *                    top-left point for the image.
 * @param filecontent a byte array with the file content
 * @param filename    the name of the file with suffix
 * @param targetwidth the width the image will be scaled to, preserving aspect
 *                    ratio
 */
public void drawImageAt(float left, float top, byte[] filecontent, String filename, float targetwidth) {
	this.widgetstoprint.add(() -> {

		float newtop = top;

		if (this.topatzero) {
			newtop = height - top;

		}

		PDImageXObject pdImage = PDImageXObject.createFromByteArray(document, filecontent, filename);
		// PDImageXObject.createFromFile(imagepath, document);
		float scaling = (targetwidth * MM_TO_POINT) / pdImage.getWidth();
		contentStream.drawImage(pdImage, left * MM_TO_POINT,
				newtop * MM_TO_POINT - 1 * pdImage.getHeight() * scaling, pdImage.getWidth() * scaling,
				pdImage.getHeight() * scaling);
	});
}
 
Example #29
Source File: GraphicsParser.java    From tephra with MIT License 5 votes vote down vote up
@Override
public void drawImage(PDImage pdImage) throws IOException {
    Matrix matrix = getGraphicsState().getCurrentTransformationMatrix();
    PDImageXObject pdImageXObject = (PDImageXObject) pdImage;
    if (!clip(matrix, pdImageXObject))
        image(matrix, pdImageXObject);
    reset();
}
 
Example #30
Source File: ResourceCacheWithLimitedImages.java    From pdfcompare with Apache License 2.0 5 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));
}