1.导入依赖
<dependency> <groupId>org.apache.pdfbox</groupId> <artifactId>pdfbox</artifactId> <version>2.0.19</version> </dependency>
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;
2.在桌面准备一张图片a.png,定位并转化为multipartFile
@Test public 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(); /* PDPage page = new PDPage(); PDRectangle rectangle = new PDRectangle(468, 450); page.setMediaBox(rectangle);*/ //这里是设置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); }
3.最后会在桌面输出一个1.pdf文章来源:https://www.toymoban.com/news/detail-551717.html
注意:桌面的路径要改成自己的文章来源地址https://www.toymoban.com/news/detail-551717.html
到了这里,关于java将图片转化为pdf并输出的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!