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

相关推荐
风铃儿~8 分钟前
RabbitMQ
java·微服务·rabbitmq
开开心心就好16 分钟前
解决 PDF 难题:批量处理、文档清理与自由拆分合并
java·学习·eclipse·pdf·word·excel·生活
ElasticPDF-新国产PDF编辑器19 分钟前
Vue 项目使用 pdf.js 及 Elasticpdf 教程
javascript·vue.js·pdf
FirstMrRight27 分钟前
自动挡线程池OOM最佳实践
java·后端
Lccee28 分钟前
Windows安装 PHP 8 和mysql9,win下使用phpcustom安装php8.4.5和mysql9
开发语言·php
Yang-Never35 分钟前
Open GL ES ->GLSurfaceView在正交投影下的图片旋转、缩放、位移
android·开发语言·kotlin·android studio·贴图
程序员清风39 分钟前
Redis Pipeline 和 MGET,如果报错了,他们的异常机制是什么样的?
java·后端·面试
风铃儿~1 小时前
Sentinel深度解析:微服务流量防卫兵的原理与实践
java·微服务·sentinel
niuniu_6661 小时前
针对 Python 3.7.0,以下是 Selenium 版本的兼容性建议和安装步骤
开发语言·chrome·python·selenium·测试工具