首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从图像转换为Pdf,然后将其作为响应发送,而不保存在磁盘中

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

Stack Overflow用户
提问于 2020-01-13 16:03:25
回答 1查看 109关注 0票数 1

我正在尝试将图像转换为pdf,然后将其作为响应发送回来,而不会省去获得的麻烦。下面是代码片段。

代码语言:javascript
复制
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();
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-01-13 16:18:10

尝试使用ByteArrayOutputStream来做这件事我们做错了,下面是代码片段。我已经编辑了这个,所以它也会对其他人有帮助,这就是我如何使用PDF转换图像到pdf的box.Below是工作代码

代码语言:javascript
复制
        @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();
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/59712593

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档