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

相关推荐
asdfg125896312 小时前
JavaBean是什么?怎么理解?有什么用途?
java·开发语言
dsyyyyy110112 小时前
JavaScript变量
开发语言·javascript·ecmascript
qq_4221525712 小时前
PDF 加水印工具怎么选?2026 年文档版权保护方案对比
前端·pdf·github
z落落13 小时前
C#WinForm 窗体切换与窗体传值(登录跳转案例)+WinForm 窗体传值(从上往下传、从下往上传)
开发语言·windows·c#
allway213 小时前
How to Echo Multiline to a File in Bash [3 Methods]
开发语言·chrome·bash
weixin_4624462313 小时前
手把手教你用 Bash 脚本自动更新 /etc/hosts —— 自动绑定网卡 IP 与节点名
开发语言·tcp/ip·bash
一个梦醒了13 小时前
安装git bash选项推荐
开发语言·git·bash
摇滚侠13 小时前
SpringMVC 入门到实战 文件上传 75-77
java·后端·spring·maven·intellij-idea
GIS数据转换器13 小时前
城市排水生命线安全运行监测平台深度解析
java·运维·人工智能·python·安全·数据挖掘·无人机
ct97814 小时前
React 状态管理方案深度对比
开发语言·前端·react