Search code examples
restspring-mvcpdfbox

Print byte[] to PDF using PDFBox


I have a question about writing image to PDF using PDFBox.

My requirement is very simple: I get an image from a web service using Spring RestTemplate, I store it in a byte[] variable, but I need to draw the image into a PDF document.

I know that the following is provided:

final byte[] image = this.restTemplate.getForObject(
        this.imagesUrl + cableReference + this.format,
        byte[].class
);

JPEGFactory.createFromStream() for JPEG format, CCITTFactory.createFromFile() for TIFF images, LosslessFactory.createFromImage() if starting with buffered images. But I don't know what to use, as the only information I know about those images is that they are in THUMBNAIL format and I don't know how to convert from byte[] to those formats.

Thanks a lot for any help.


Solution

  • (This applies to version 2.0, not to 1.8)

    I don't know what you mean with THUMBNAIL format, but give this a try:

        final byte[] image = ... // your code
        ByteArrayInputStream bais = new ByteArrayInputStream(image);
        BufferedImage bim = ImageIO.read(bais);
        PDImageXObject pdImage = LosslessFactory.createFromImage(doc, bim);
    

    It might be possible to create a more advanced solution by using

    PDImageXObject.createFromFileByContent()
    

    but this one uses a file and not a stream, so it would be slower (but produce the best possible image type).

    To add this image to your PDF, use this code:

        PDDocument doc = new PDDocument();
        try
        {
            PDPage page = new PDPage();
            doc.addPage(page);
    
            PDPageContentStream contents = new PDPageContentStream(doc, page);
    
            // draw the image at full size at (x=20, y=20)
            contents.drawImage(pdImage, 20, 20);
    
            // to draw the image at half size at (x=20, y=20) use
            // contents.drawImage(pdImage, 20, 20, pdImage.getWidth() / 2, pdImage.getHeight() / 2);
    
            contents.close();
            doc.save(pdfPath);
        }
        finally
        {
            doc.close();
        }