从图像转换为 Pdf,然后将其作为响应发送而不保存在磁盘中 java

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

我正在尝试将图像转换为 pdf,然后将其作为响应发回,以免遇到麻烦。下面是代码片段。

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

试试这个使用 ByteArrayOutputStream 的方法是错误的,下面是代码片段。我已经对此进行了编辑,因此它对其他人也有帮助这就是我使用 pdf box.Below 将图像转换为 PDF 的方式 box.Below 是工作代码

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