Search code examples
javapdfbox

Converting from image to Pdf and then sending it as response without saving in disk java


I am trying to convert the image to pdf and then sending it back as response without saving getting trouble. Below is the code snippet.

PDDocument document = new PDDocument();
InputStream in = new FileInputStream(sourceFile);
BufferedImage bimg = ImageIO.read(in);
float width = bimg.getWidth();
float height = bimg.getHeight();
PDPage page = new PDPage(new PDRectangle(width, height));
document.addPage(page);
PDImageXObject img = PDImageXObject.createFromFile(sourceFile.getPath(), document);
PDPageContentStream contentStream = new PDPageContentStream(document, page);
contentStream.drawImage(img, 0, 0);
contentStream.close();
 in.close();       
 document.close();
 PDPage documentPage = document.getPage(0);
 InputStream pdfStream = documentPage.getContents();
 byte[] pdfData = new byte[pdfStream.available()];
 pdfStream.read(pdfData); 
 return Response.ok((Object) document).build();

Solution

  • Try this using ByteArrayOutputStream are doing it wrong way below is the code snippet. I have edit this so it will be helpful for others as well this is how i am converting image to PDF using pdf box.Below is the working code

            @GET
    @Path("/endpoint/{resourceName}")
    @Produces("application/pdf")
    public Response downloadPdfFile(@PathParam("resourceName") String res) throws IOException {
        File sourceFile = new File("directoryPath/"+ res+ ".png");
        if (!sourceFile.exists()) {
            return Response.status(400).entity("resource not exist").build();
        }
            PDDocument document = new PDDocument();
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            InputStream in = new FileInputStream(sourceFile);
            BufferedImage bimg = ImageIO.read(in);
            float width = bimg.getWidth();
            float height = bimg.getHeight();
            PDPage page = new PDPage(new PDRectangle(width, height));
            document.addPage(page);
            PDImageXObject img = PDImageXObject.createFromFile(sourceFile.getPath(), 
            document);
            PDPageContentStream contentStream = new PDPageContentStream(document, page);
            contentStream.drawImage(img, 0, 0);
            contentStream.close();
            in.close();
            document.save(outputStream);
            document.close();
            return Response.ok(outputStream.toByteArray()).build();