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 文件

相关推荐
showyoui40 分钟前
Python 闭包(Closure)实战总结
开发语言·python
做题不NG42 分钟前
大模型应用开发-LangChain4j
java
今天背单词了吗9801 小时前
算法学习笔记:7.Dijkstra 算法——从原理到实战,涵盖 LeetCode 与考研 408 例题
java·开发语言·数据结构·笔记·算法
Eiceblue1 小时前
使用 C# 发送电子邮件(支持普通文本、HTML 和附件)
开发语言·c#·html·visual studio
小小小小王王王1 小时前
hello判断
开发语言·c#
高兴达2 小时前
RPC--Netty客户端实现
java·spring·rpc
苦夏木禾2 小时前
js请求避免缓存的三种方式
开发语言·javascript·缓存
重庆小透明2 小时前
力扣刷题记录【1】146.LRU缓存
java·后端·学习·算法·leetcode·缓存
超级土豆粉2 小时前
Turndown.js: 优雅地将 HTML 转换为 Markdown
开发语言·javascript·html
lang201509282 小时前
Reactor操作符的共享与复用
java