导入依赖 org.apache.pdfbox pdfbox 2.0.19 import org.apache.pdfbox.pdmodel.PDDocument;import org.apache.pdfbox.pdmo
导入依赖
org.apache.pdfbox pdfbox 2.0.19
import org.apache.pdfbox.pdmodel.PDDocument;import org.apache.pdfbox.pdmodel.PDPage;import org.apache.pdfbox.pdmodel.PDPageContentStream;import org.apache.pdfbox.pdmodel.common.PDRectangle;import org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject;
在桌面准备一张图片a.png,定位并转化为multipartFile
@Testpublic void testPdf() throws Exception{ boolean is = false; File file = new File("C:\\Users\\scz\\Desktop\\a.png"); FileInputStream fileInputStream = new FileInputStream(file); MultipartFile multipartFile = new MockMultipartFile("copy"+file.getName(),file.getName(), ContentType.APPLICATION_OCTET_STREAM.toString(),fileInputStream); try { PDDocument document = new PDDocument(); //这里是设置pdf的大小,大小固定,所有不推荐,下面是根据图片大小动态生成pdf大小 String filename = multipartFile.getOriginalFilename(); String fileSuffix = filename.substring(filename.lastIndexOf(".") + 1); Iterator readers = ImageIO.getImageReadersByFORMatName(fileSuffix); ImageReader reader = (ImageReader) readers.next(); ImageInputStream input = ImageIO.createImageInputStream(multipartFile.getInputStream()); reader.setInput(input, true); int width = reader.getWidth(0)+300; int height = reader.getHeight(0)+500; PDPage pdPage = new PDPage(new PDRectangle(width, height));//根据图片大小动态生成pdf大小 document.addPage(pdPage); PDImageXObject pdImageXObject = PDImageXObject.createFromByteArray(document, multipartFile.getBytes(), "构建图片错误"); PDPageContentStream contentStream = new PDPageContentStream(document, pdPage); //写入图片 contentStream.drawImage(pdImageXObject, 0, 0); contentStream.close(); document.save("C:\\Users\\scz\\Desktop\\1.pdf");//pdf输出 document.close(); is = true; } catch (Exception e) { is = false; } System.out.println(is);}
最后会在桌面输出一个1.pdf
注意:桌面的路径要改成自己的
来源地址:https://blog.csdn.net/leese233/article/details/130942784
--结束END--
本文标题: java将图片转化为pdf并输出
本文链接: https://lsjlt.com/news/420204.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
2024-04-01
2024-04-03
2024-04-03
2024-01-21
2024-01-21
2024-01-21
2024-01-21
2023-12-23
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0