java图片转pdf

前言

图片文件转pdf

如何将图片转pdf

  1. 引入依赖
xml 复制代码
      <dependency>
            <groupId>com.lowagie</groupId>
            <artifactId>itext</artifactId>
            <version>4.2.1</version>
        </dependency>
         <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>itextpdf</artifactId>
            <version>5.5.13.3</version>
        </dependency>
  1. 转换工具
java 复制代码
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;


public class ImageToPdfUtil {

    private static Logger log = LoggerFactory.getLogger(ImageToPdfUtil.class);

    /**
     * 支持png jpg
     *
     * @param source
     * @param target
     * @return
     */
    public static boolean image2Pdf(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("image to pdf fail," + source + "-->" + target, ioe);
            return false;
        } finally {
            // 关闭文档
            try {
                document.close();
                fos.flush();
                fos.close();
            } catch (IOException e) {
                log.error("document close fail", e);
            }
        }
        return true;
    }
}
  1. 测试用例
java 复制代码
ImageToPdfUtil.image2Pdf("C:\\test\\test.jpg", "C:\\test\\test.pdf");

读取test.jpg生成一个pdf 文件

相关推荐
二哈赛车手20 小时前
新人笔记---ApiFox的一些常见使用出错
java·笔记·spring
为何创造硅基生物21 小时前
C语言 结构体内存对齐规则(通俗易懂版)
c语言·开发语言
吃好睡好便好21 小时前
在Matlab中绘制横直方图
开发语言·学习·算法·matlab
栗子~~21 小时前
JAVA - 二层缓存设计(本地缓冲+redis缓冲+广播所有本地缓冲失效) demo
java·redis·缓存
星寂樱易李21 小时前
iperf3 + Python-- 网络带宽、网速、网络稳定性
开发语言·网络·python
YDS82921 小时前
DeepSeek RAG&MCP + Agent智能体项目 —— RAG知识库的搭建和接口实现
java·ai·springboot·agent·rag·deepseek
仰泳之鹅21 小时前
【C语言】自定义数据类型2——联合体与枚举
c语言·开发语言·算法
之歆21 小时前
DAY_12JavaScript DOM 完全指南(二):实战与性能篇
开发语言·前端·javascript·ecmascript
未若君雅裁1 天前
MyBatis 一级缓存、二级缓存与清理机制
java·缓存·mybatis
cen__y1 天前
Linux12(Git01)
linux·运维·服务器·c语言·开发语言·git