一、实现方式
采用itextpdf和itext包,使用java代码,把图片转换为pdf.
支持文件格式:png,jpg, jpeg,gif
二、java代码实现
1、maven依赖
<!-- https://mvnrepository.com/artifact/com.itextpdf/itextpdf --><dependency><groupId>com.itextpdf</groupId><artifactId>itextpdf</artifactId><version>5.5.13</version></dependency><!-- https://mvnrepository.com/artifact/com.lowagie/itext --><dependency><groupId>com.lowagie</groupId><artifactId>itext</artifactId><version>4.2.1</version></dependency>
2、java转换工具类
ImgToPdfUtil.java
package com.lan.fts.util;import com.itextpdf.text.Document;
import com.itextpdf.text.Image;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.PdfWriter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;import java.io.FileOutputStream;
import java.io.IOException;/*** @Author lanhezhong* @Date 2022/3/14*/
public class ImgToPdfUtil {private static Logger log = LoggerFactory.getLogger(ImgToPdfUtil.class);/*** 支持png jpg* @param source* @param target* @return*/public static boolean imgToPdf(String source, String target){Document document = new Document();// 设置文档页边距document.setMargins(0, 0, 0, 0);FileOutputStream fos = null;try {fos = new FileOutputStream(target);PdfWriter.getInstance(document, fos);// 打开文档document.open();// 获取图片的宽高Image image = Image.getInstance(source);float imageHeight = image.getScaledHeight();float imageWidth = image.getScaledWidth();// 设置页面宽高与图片一致Rectangle rectangle = new Rectangle(imageWidth, imageHeight);document.setPageSize(rectangle);// 图片居中image.setAlignment(Image.ALIGN_CENTER);// 新建一页添加图片document.newPage();document.add(image);} catch (Exception ioe) {log.error("图片转PDF失败,"+source+"-->"+target, ioe);return false;} finally {// 关闭文档try {document.close();fos.flush();fos.close();} catch (IOException e) {log.error("图片转PDF关闭文档失败,"+source+"-->"+target, e);}}return true;}
}
三、运行测试
public static void main(String[] args) {ImgToPdfUtil.imgToPdf("D:\\data\\out\\lanhezhong文件转换.jpg", "D:\\data\\out\\lanhezhong文件转换.jpg.pdf");}
结果:
总结:图片转pdf,其实就是用itext,把图片写入。然后再用itextpdf,把itext文档输出到pdf。可以在代码中设置页边距等信息。
***********************************************************************************************
author:蓝何忠
email:lanhezhong@163.com
***********************************************************************************************