当前位置: 首页> 汽车> 新车 > Java实现将图片转换成PDF

Java实现将图片转换成PDF

时间:2025/8/25 18:30:17来源:https://blog.csdn.net/XuDream/article/details/140320038 浏览次数: 1次

1.引入依赖

<dependency><groupId>org.apache.pdfbox</groupId><artifactId>pdfbox</artifactId><version>2.0.24</version>
</dependency>

2.工具方法

package com.prescription.transfer.system.utils;import org.apache.pdfbox.io.IOUtils;
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;import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;public class ImgToPdf {/*** 图片转Pdf** @param imgFile* @return* @throws IOException*/public static File getPdfFile(File imgFile, String filePath) throws IOException {File outputFile = new File(filePath);genPdf(readBytesFromFile(imgFile), outputFile);return outputFile;}private static void genPdf(byte[] imageBytes, File outputFile) throws IOException {PDDocument document = new PDDocument();//2. 生成一页 PDF documentPDImageXObject image = PDImageXObject.createFromByteArray(document, imageBytes, "image");// 这里是你生成PDF自适应图片大小,不设置会默认为A4PDRectangle pageSize = new PDRectangle(image.getWidth(), image.getHeight());PDPage page = new PDPage(pageSize);document.addPage(page);// 3.将 图片 添加进PDF documentPDPageContentStream contentStream = new PDPageContentStream(document, page);float pageWidth = pageSize.getWidth();float pageHeight = pageSize.getHeight();float imageWidth = image.getWidth();float imageHeight = image.getHeight();float scale = Math.min(pageWidth / imageWidth, pageHeight / imageHeight);float scaledWidth = imageWidth * scale;float scaledHeight = imageHeight * scale;float x = (pageWidth - scaledWidth) / 2;float y = (pageHeight - scaledHeight) / 2;// 这里是将你的图片填充入pdf页contentStream.drawImage(image, x, y, scaledWidth, scaledHeight);contentStream.close();document.save(outputFile);document.close();}/*** 从文件读取字节** @param file 文件* @return {@link byte[]}* @throws IOException ioexception*/private static byte[] readBytesFromFile(File file) throws IOException {FileInputStream inputStream = new FileInputStream(file);byte[] bytes = IOUtils.toByteArray(inputStream);inputStream.close();return bytes;}}
关键字:Java实现将图片转换成PDF

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

责任编辑: