Print byte[] to pdf using pdfbox

风格不统一 提交于 2019-12-24 15:27:40

问题


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.


回答1:


(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();
    }


来源:https://stackoverflow.com/questions/35751150/print-byte-to-pdf-using-pdfbox

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!