I have a question about writting 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.createFromFil 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 is images is that they are (THUMBNAIL format) and i don't know how to convert from byte[] to those format. thanks a lot for any help or indication.
(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();
}