JAVA 实现PDF转图片(pdfbox版)

news2025/7/10 10:15:26

依赖:

pdf存放路径

正文开始:

pdf转换多张图片、长图

@Test
void pdf2Image() {
        String dstImgFolder = "";
        String PdfFilePath = "";
 
        String relativelyPath=System.getProperty("user.dir");
        PdfFilePath = relativelyPath + "/uploadTest/"+"文档.pdf";
        dstImgFolder = relativelyPath + "/uploadTest/";
        /* dpi越大转换后越清晰,相对转换速度越慢 */
        int dpi = 450;
        File file = new File(PdfFilePath);
        PDDocument pdDocument; // 创建PDF文档
        try {
            String imgPDFPath = file.getParent();
            int dot = file.getName().lastIndexOf('.');
            String imagePDFName = file.getName().substring(0, dot); // 获取图片文件名
            String imgFolderPath = null;
            if (dstImgFolder.equals("")) {
                imgFolderPath = imgPDFPath + File.separator;// 获取图片存放的文件夹路径
            } else {
                imgFolderPath = dstImgFolder + File.separator;
            }
            if (createDirectory(imgFolderPath)) {
                pdDocument = PDDocument.load(file);
                PDFRenderer renderer = new PDFRenderer(pdDocument);
                PdfReader reader = new PdfReader(PdfFilePath);
                int pages = reader.getNumberOfPages();
                StringBuffer imgFilePath = null;
               BufferedImage[] bufferedImages = new BufferedImage[pages];
                for (int i = 0; i < pages; i++) {
                    String imgFilePathPrefix = imgFolderPath + File.separator;
                    imgFilePath = new StringBuffer();
                    imgFilePath.append(imgFilePathPrefix);
                    imgFilePath.append("_");
                    imgFilePath.append(i + 1);
                    imgFilePath.append(".png");
                    // File dstFile = new File(imgFilePath.toString());
                    BufferedImage image = renderer.renderImageWithDPI(i, dpi);
                   bufferedImages[i] = image;
                    // ImageIO.write(image, "png", dstFile);
                }
                dstImgFolder = dstImgFolder + imagePDFName + ".png";
                // PDF文件全部页数转PNG图片,若多张展示注释即可 工具类贴在下面
               ImageMergeUtil.mergeImage(bufferedImages, 2, dstImgFolder);
                System.out.println("PDF文档转PNG图片成功!");
            } else {
                System.out.println("PDF文档转PNG图片失败:" + "创建" + imgFolderPath + "失败");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
 
    private static boolean createDirectory(String folder) {
        File dir = new File(folder);
        if (dir.exists()) {
            return true;
        } else {
            return dir.mkdirs();
        }
    }

// ImageMergeUtil 图片的合并,多张图片合成长图
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
 
public class ImageMergeUtil {
    public static void main(String[] args) throws IOException {
        String filePath = "D:\\temp\\ImageMergeUtil\\";
        String path1 = filePath + "a.png";
        String path2 = filePath + "b.png";
        mergeImage(path1, path2,  2, filePath+"c.png");
    }
 
    /**
     * 图片拼接
     * @param path1     图片1路径
     * @param path2     图片2路径
     * @param type      1 横向拼接, 2 纵向拼接
     * (注意:必须两张图片长宽一致)
     */
    public static void mergeImage( String path1, String path2, int type, String targetFile) throws IOException {
        File file1 = new File(path1);
        File file2 = new File(path2);
        //两张图片的拼接
        int len = 2;
        BufferedImage[] images = new BufferedImage[len];
        images[0] = ImageIO.read(file1);
        images[1] = ImageIO.read(file2);
        mergeImage(images, type, targetFile);
 
    }
 
    /**
     * 图片拼接
     * @param images     图片数组
     * @param type      1 横向拼接, 2 纵向拼接
     * (注意:必须两张图片长宽一致)
     */
    public static void mergeImage(BufferedImage[] images, int type, String targetFile) throws IOException {
        int len = images.length;
        int[][] ImageArrays = new int[len][];
 
        for (int i = 0; i < len; i++) {
            int width = images[i].getWidth();
            int height = images[i].getHeight();
            ImageArrays[i] = new int[width * height];
            ImageArrays[i] = images[i].getRGB(0, 0, width, height, ImageArrays[i], 0, width);
        }
        int newHeight = 0;
        int newWidth = 0;
        for (int i = 0; i < images.length; i++) {
            // 横向
            if (type == 1) {
                newHeight = newHeight > images[i].getHeight() ? newHeight : images[i].getHeight();
                newWidth += images[i].getWidth();
            } else if (type == 2) {// 纵向
                newWidth = newWidth > images[i].getWidth() ? newWidth : images[i].getWidth();
                newHeight += images[i].getHeight();
            }
        }
        if (type == 1 && newWidth < 1) {
            return;
        }
        if (type == 2 && newHeight < 1) {
            return;
        }
        // 生成新图片
        try {
            BufferedImage ImageNew = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_RGB);
            int height_i = 0;
            int width_i = 0;
            for (int i = 0; i < images.length; i++) {
                if (type == 1) {
                    ImageNew.setRGB(width_i, 0, images[i].getWidth(), newHeight, ImageArrays[i], 0,
                            images[i].getWidth());
                    width_i += images[i].getWidth();
                } else if (type == 2) {
                    ImageNew.setRGB(0, height_i, newWidth, images[i].getHeight(), ImageArrays[i], 0, newWidth);
                    height_i += images[i].getHeight();
                }
            }
 
            //输出想要的图片
            ImageIO.write(ImageNew, "png", new File(targetFile));
        } catch (Exception e) {
 
            e.printStackTrace();
        }
    }

展示效果:

附加:小程序预览wxml代码

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1158129.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

使用vue3+vite+elctron构建小项目介绍Electron进程间通信

进程间通信 (IPC) 是在 Electron 中构建功能丰富的桌面应用程序的关键部分之一。 由于主进程和渲染器进程在 Electron 的进程模型具有不同的职责&#xff0c;因此 IPC 是执行许多常见任务的唯一方法&#xff0c;例如从 UI 调用原生 API 或从原生菜单触发 Web 内容的更改。 在 …

【嵌入式开发学习02】esp32cam烧录human_face_detect实现人脸识别

Ubuntu20.04系统为esp32cam烧录human_face_detect 1. 下载esp-dl2. 安装esp-idf3. 烧录human_face_detect 如果使用ubuntu 16.04在后续的步骤中会报错如下&#xff0c;因为ubuntu 16.04不支持glibc2.23以上的版本&#xff08;可使用strings /lib/x86_64-linux-gnu/libc.so.6 | …

抖音直播招聘报白与求职者互动的招聘方式企业或者人力资源公司

人力资源行业抖音招聘报白开始了&#xff0c;但是目前的市面的价格不一&#xff0c;很多人力资源公司最近想做抖音的直播报白&#xff0c;做直播待岗&#xff0c;因为最近刚好是招聘高峰期啊&#xff0c;企业需求大&#xff0c;赶上这一波&#xff0c;但是对目前市面上做抖音报…

数据分析实战 - 2 订单销售数据分析(pandas 进阶)

题目来源&#xff1a;和鲸社区的题目推荐&#xff1a; 刷题源链接&#xff08;用于直接fork运行 https://www.heywhale.com/mw/project/6527b5560259478972ea87ed 刷题准备 请依次运行这部分的代码&#xff08;下方4个代码块&#xff09;&#xff0c;完成刷题前的数据准备 …

虽迟但到,Postman终于支持Websocket接口了

&#x1f4e2;专注于分享软件测试干货内容&#xff0c;欢迎点赞 &#x1f44d; 收藏 ⭐留言 &#x1f4dd; 如有错误敬请指正&#xff01;&#x1f4e2;交流讨论&#xff1a;欢迎加入我们一起学习&#xff01;&#x1f4e2;资源分享&#xff1a;耗时200小时精选的「软件测试」资…

2023年9月CSDN客服月报|解决个3重大问题、5个次要问题、21个一般问题,处理1个用户需求

听用户心声&#xff0c;解用户之需。hello&#xff0c;大家好&#xff0c;这里是《CSDN客诉报告》第24期&#xff0c;接下来就请大家一同回顾我们9月份解决的bug&#xff5e; 一、重大问题 1、【BI】BI数据延迟导致一周小结/榜单等数据不更新 反馈量&#xff1a;11 2、【UC…

idea 拉取代码

md老长时间 不用git 差点忘了 现在 演示 非常简单

八段流水线运行示意图

流水线如下图所示: 存储周期存取时间恢复时间, 即存取完数据后需要一定量的时间来恢复, 而低位交叉编址的流水线所利用的正是恢复时间 流水线与非流水线对比如下: 经典例题: 2013年408真题

本地打包jar方式

第一种&#xff1a;命令打包mvn clean package 或者使用idea的clean、package 该方式pom文件需要引入打包插件 <build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifact…

淘宝商品详情API接口(选品上架,数据分析,代购商城建站,erp系统商品数据选品,价格监控)

淘宝商品详情API接口&#xff08;item_get-获得taobao商品详情接口&#xff09;&#xff0c;淘宝API接口可获取到商品链接&#xff0c;商品ID&#xff0c;商品标题&#xff0c;商品价格&#xff0c;品牌名称&#xff0c;店铺昵称&#xff0c;sku规格&#xff0c;sku属性&#x…

C++设计模式_24_Visitor 访问器

Visitor 访问器也是属于“行为变化”模式。 文章目录 1. 动机( Motivation)2. 代码演示Visitor 访问器3. 模式定义4. 结构(Structure)5. 要点总结6. 其他参考 1. 动机( Motivation) 在软件构建过程中&#xff0c;由于需求的改变&#xff0c;某些类层次结构中常常需要增加新的行…

Techlink TL24G10 网络变压器 10G 基座单端口变压器

功能特征&#xff1a; 1、符合IEEE 802.3标准。 2、符合RoHS。 3、工作温度范围&#xff1a;0C至70C。 4、储存温度范围&#xff1a;-20C至125C。 封装&#xff1a;SOP24

横屏签字板手写签名并旋转90°转为横屏显示base64

手写签名并旋转90转为横屏显示base64 base64 data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAApsAAAF3CAYAAADq/IAAAAAAAXNSR0IArs4c6QAAIABJREFUeF7t3W3MPlldH/CvwLK7wEKNoiABZLvYiBqIdJGnQlor9gVBaAtJmzQsoI2wgKD4hqVNmrD7ohWhPFRSIgaKO0XTS8AVLb4AIVtFnaSiMPSktxoyVVWFxAF…

ios开发者(Apple Developer Program)如何续费

前言 会员资格到期之日前 30 天才可以进行续费 1. 联系官方 查询续费方式与入口 官网地址&#xff1a;https://developer.apple.com/ 2. Apple Developer App 进行续订 需要下载 Apple Developer 进入App内进行续订。 3. 如果没有续订按钮&#xff0c;联系官方更换订阅…

RTSP/Onvif安防视频平台EasyNVR接入EasyNVS,出现Login error报错的解决方法

安防视频监控汇聚EasyNVR平台&#xff0c;是基于RTSP/Onvif协议的安防视频平台&#xff0c;可支持将接入的视频流进行全平台、全终端分发&#xff0c;分发的视频流包括RTSP、RTMP、HTTP-FLV、WS-FLV、HLS、WebRTC等格式。为了满足用户的集成与二次开发需求&#xff0c;我们也提…

厦门万宾科技智能井盖监测仪器的作用如何?

越来越多的人们希望改善生活&#xff0c;走出农村走出大山&#xff0c;前往城市之中居住。由此城市的人口和车辆在不断增加&#xff0c;与之而来的是城市的交通压力越来越大&#xff0c;时常会出现道路安全隐患&#xff0c;这给城市未来发展和智慧城市建设都带来一定的难题&…

vue详细安装教程

这里写目录标题 一、下载和安装node二、创建全局安装目录和缓存日志目录三、安装vue四、创建一个应用程序五、3x版本创建六、创建一个案例 一、下载和安装node 官网下载地址&#xff1a;https://nodejs.org/en/download 选择适合自己的版本&#xff0c;推荐LTS&#xff0c;长久…

模块化机柜PDU为数据中心机房末端配电提供可靠解决方案

数据中心是国家确定的“新基建”七大领域之一&#xff0c;数据中心在国民经济和社会发展中所起的作用越来越重要&#xff0c;数据中心已经成为了各行各业的关键基础设施&#xff0c;数据中心供配电系统相当于一个人的“心脏和血管”&#xff0c;负责把能量输送到系统的每一台设…

驱动开发11-1 编写IIC驱动-读取温湿度数据

头文件 head.h #ifndef __HEAD_H__ #define __HEAD_H__ #define GET_HUM _IOR(m, 1, int) #define GET_TEM _IOR(m, 0, int) #endif 应用程序 si7006.c #include <stdlib.h> #include <stdio.h> #include <sys/types.h> #include <sys/stat.h> #inc…

人人都能看懂的DDPM反向降噪过程公式推导

0 前言 上一篇介绍了前向加噪过程&#xff0c;得到如下从 x 0 x_0 x0​ 一步到 x t x_t xt​ 过程&#xff1a; α t β t 1 \alpha_t \beta_t1 αt​βt​1&#xff0c;其中 β t \beta_t βt​ 是正态分布方差&#xff0c;即第 t t t 步产生的噪声从 N ( 0 , β t ) …