我正在尝试将图像转换为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();发布于 2020-01-13 16:18:10
尝试使用ByteArrayOutputStream来做这件事我们做错了,下面是代码片段。我已经编辑了这个,所以它也会对其他人有帮助,这就是我如何使用PDF转换图像到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();https://stackoverflow.com/questions/59712593
复制相似问题