java操作PDF:转换、合成、切分

将PDF每一页切割成图片

PDFUtils.cutPNG("D:/tmp/1.pdf","D:/tmp/输出图片路径/");

将PDF转换成一张长图片

PDFUtils.transition_ONE_PNG("D:/tmp/1.pdf");

将多张图片合并成一个PDF文件

PDFUtils.merge_PNG("D:/tmp/测试图片/");

将多个PDF合并成一个PDF文件

PDFUtils.merge_PDF("D:/tmp/测试图片/");

取出指定PDF的起始和结束页码作为新的pdf

PDFUtils.getPartPDF("D:/tmp/1.pdf",3,5);

引入依赖

<!--        apache PDF转图片--><dependency><groupId>org.apache.pdfbox</groupId><artifactId>pdfbox</artifactId><version>2.0.24</version></dependency>
<!--        itext 图片合成PDF--><dependency><groupId>com.itextpdf</groupId><artifactId>itextpdf</artifactId><version>5.5.13.2</version></dependency>

代码(如下4个java类放在一起直接使用即可)

PDFUtils.java

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Image;
import com.itextpdf.text.pdf.*;
import org.apache.pdfbox.io.MemoryUsageSetting;
import org.apache.pdfbox.multipdf.PDFMergerUtility;
import org.apache.pdfbox.multipdf.Splitter;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDResources;
import org.apache.pdfbox.pdmodel.common.PDRectangle;
import org.apache.pdfbox.rendering.ImageType;
import org.apache.pdfbox.rendering.PDFRenderer;import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;/*** pdf工具类*/
public class PDFUtils {/*** PDF分解图片文件** @param pdfPath pdf文件路径*/public static void cutPNG(String pdfPath) throws IOException {File pdf = new File(pdfPath);cutPNG(pdfPath, pdf.getParent() + File.separator + pdf.getName() + "_pngs");}/*** PDF分解图片文件** @param pdfPath pdf文件路径* @param outPath 输出文件夹路径*/public static void cutPNG(String pdfPath, String outPath) throws IOException {File outDir = new File(outPath);if (!outDir.exists()) outDir.mkdirs();cutPNG(new File(pdfPath), outDir);}/*** PDF分解图片文件** @param pdf    pdf文件* @param outDir 输出文件夹*/public static void cutPNG(File pdf, File outDir) throws IOException {LogUtils.info("PDF分解图片工作开始");List<BufferedImage> list = getImgList(pdf);LogUtils.info(pdf.getName() + " 一共发现了 " + list.size() + " 页");FileUtils.cleanDir(outDir);for (int i = 0; i < list.size(); i++) {IMGUtils.saveImageToFile(list.get(i), outDir.getAbsolutePath() + File.separator + (i + 1) + ".png");LogUtils.info("已保存图片:" + (i + 1) + ".png");}LogUtils.info("PDF分解图片工作结束,一共分解出" + list.size() + "个图片文件,保存至:" + outDir.getAbsolutePath());}/*** 将pdf文件转换成一张图片** @param pdfPath pdf文件路径*/public static void transition_ONE_PNG(String pdfPath) throws IOException {transition_ONE_PNG(new File(pdfPath));}/*** 将pdf文件转换成一张图片** @param pdf pdf文件*/public static void transition_ONE_PNG(File pdf) throws IOException {LogUtils.info("PDF转换长图工作开始");List<BufferedImage> list = getImgList(pdf);LogUtils.info(pdf.getName() + " 一共发现了 " + list.size() + " 页");BufferedImage image = list.get(0);for (int i = 1; i < list.size(); i++) {image = IMGUtils.verticalJoinTwoImage(image, list.get(i));}byte[] data = IMGUtils.getBytes(image);String imgPath = pdf.getParent() + File.separator + pdf.getName().replaceAll("\\.", "_") + ".png";FileUtils.saveDataToFile(imgPath, data);LogUtils.info("PDF转换长图工作结束,合成尺寸:" + image.getWidth() + "x" + image.getHeight() + ",合成文件大小:" + data.length / 1024 + "KB,保存至:" + imgPath);}/*** 将PDF文档拆分成图像列表** @param pdf PDF文件*/private static List<BufferedImage> getImgList(File pdf) throws IOException {PDDocument pdfDoc = PDDocument.load(pdf);List<BufferedImage> imgList = new ArrayList<>();PDFRenderer pdfRenderer = new PDFRenderer(pdfDoc);int numPages = pdfDoc.getNumberOfPages();for (int i = 0; i < numPages; i++) {BufferedImage image = pdfRenderer.renderImageWithDPI(i, 300, ImageType.RGB);imgList.add(image);}pdfDoc.close();return imgList;}/*** 图片合成PDF** @param pngsDirPath 图片文件夹路径*/public static void merge_PNG(String pngsDirPath) throws Exception {File pngsDir = new File(pngsDirPath);merge_PNG(pngsDir, pngsDir.getName() + ".pdf");}/*** 图片合成pdf** @param pngsDir 图片文件夹* @param pdfName 合成pdf名称*/private static void merge_PNG(File pngsDir, String pdfName) throws Exception {File pdf = new File(pngsDir.getParent() + File.separator + pdfName);if (!pdf.exists()) pdf.createNewFile();File[] pngList = pngsDir.listFiles((dir, name) -> name.toLowerCase().endsWith(".png"));LogUtils.info("在" + pngsDir.getAbsolutePath() + ",一共发现" + pngList.length + "个PNG文件");Document document = new Document();FileOutputStream fo = new FileOutputStream(pdf);PdfWriter writer = PdfWriter.getInstance(document, fo);document.open();for (File f : pngList) {document.newPage();byte[] bytes = FileUtils.getFileBytes(f);Image image = Image.getInstance(bytes);float heigth = image.getHeight();float width = image.getWidth();int percent = getPercent2(heigth, width);image.setAlignment(Image.MIDDLE);image.scalePercent(percent + 3);// 表示是原来图像的比例;document.add(image);System.out.println("正在合成" + f.getName());}document.close();writer.close();System.out.println("PDF文件生成地址:" + pdf.getAbsolutePath());}private static int getPercent2(float h, float w) {int p = 0;float p2 = 0.0f;p2 = 530 / w * 100;p = Math.round(p2);return p;}/*** 多PDF合成** @param pngsDirPath pdf所在文件夹路径*/public static void merge_PDF(String pngsDirPath) throws IOException {File pngsDir = new File(pngsDirPath);merge_PDF(pngsDir, pngsDir.getName() + "_合并.pdf");}/*** 多PDF合成** @param pngsDir pdf所在文件夹* @param pdfName 合成pdf文件名*/private static void merge_PDF(File pngsDir, String pdfName) throws IOException {File[] pdfList = pngsDir.listFiles((dir, name) -> name.toLowerCase().endsWith(".pdf"));LogUtils.info("在" + pngsDir.getAbsolutePath() + ",一共发现" + pdfList.length + "个PDF文件");PDFMergerUtility pdfMergerUtility = new PDFMergerUtility();pdfMergerUtility.setDestinationFileName(pngsDir.getParent() + File.separator + pdfName);for (File f : pdfList) {pdfMergerUtility.addSource(f);}pdfMergerUtility.mergeDocuments(MemoryUsageSetting.setupMainMemoryOnly());}public static void getPartPDF(String pdfPath, int from, int end) throws Exception {pdfPath = pdfPath.trim();Document document = null;PdfCopy copy = null;PdfReader reader = new PdfReader(pdfPath);int n = reader.getNumberOfPages();if (end == 0) {end = n;}document = new Document(reader.getPageSize(1));copy = new PdfCopy(document, new FileOutputStream(pdfPath.substring(0, pdfPath.length() - 4) + "_" + from + "_" + end + ".pdf"));document.open();for (int j = from; j <= end; j++) {document.newPage();PdfImportedPage page = copy.getImportedPage(reader, j);copy.addPage(page);}document.close();}}

IMGUtils.java

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException;public class IMGUtils {/*** 将图像转为png文件的字节数据* @param image 目标图像* @return 返回数据*/public static byte[] getBytes(BufferedImage image){return getBytes(image,"png");}/*** 将图像转换为指定媒体文件类型的字节数据* @param image  目标图像* @param fileType  文件类型(后缀名)* @return 返回数据*/public static byte[] getBytes(BufferedImage image,String fileType){ByteArrayOutputStream outStream = new ByteArrayOutputStream();try {ImageIO.write(image,fileType,outStream);} catch (IOException e) {e.printStackTrace();}return outStream.toByteArray();}/*** 读取图像,通过文件* @param filePath 文件路径* @return BufferedImage*/public static BufferedImage getImage(String filePath){try {return ImageIO.read(new FileInputStream(filePath));} catch (IOException e) {e.printStackTrace();}return null;}/*** 读取图像,通过字节数据* @param data 字节数据* @return BufferedImage*/public static BufferedImage getImage(byte[] data){try {return ImageIO.read(new ByteArrayInputStream(data));} catch (IOException e) {e.printStackTrace();}return null;}/*** 保存图像到指定文件* @param image 图像* @param filePath 文件路径*/public static void saveImageToFile(BufferedImage image,String filePath) throws IOException {FileUtils.saveDataToFile(filePath,getBytes(image));}/*** 纵向拼接图片*/public static BufferedImage verticalJoinTwoImage(BufferedImage image1, BufferedImage image2){if(image1==null)return image2;if(image2==null)return image1;BufferedImage image=new BufferedImage(image1.getWidth(),image1.getHeight()+image2.getHeight(),image1.getType());Graphics2D g2d = image.createGraphics();g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);g2d.drawImage(image1, 0, 0, image1.getWidth(), image1.getHeight(), null);g2d.drawImage(image2, 0, image1.getHeight(), image2.getWidth(), image2.getHeight(), null);g2d.dispose();// 释放图形上下文使用的系统资源return image;}/*** 剪裁图片* @param image 对象* @param x  顶点x* @param y  顶点y* @param width   宽度* @param height   高度* @return 剪裁后的对象*/public static BufferedImage cutImage(BufferedImage image,int x,int y,int width,int height){if(image==null)return null;return image.getSubimage(x,y,width,height);}}

FileUtils.java

import java.io.*;public class FileUtils {/*** 将数据保存到指定文件路径*/public static void saveDataToFile(String filePath,byte[] data) throws IOException {File file = new File(filePath);if(!file.exists())file.createNewFile() ;FileOutputStream outStream = new FileOutputStream(file);outStream.write(data);outStream.flush();outStream.close();}/*** 读取文件数据*/public static byte[] getFileBytes(File file) throws IOException {if(!file.exists()||(file.exists()&&!file.isFile()))return null;InputStream inStream=new FileInputStream(file);ByteArrayOutputStream outStream = new ByteArrayOutputStream();byte[] buffer = new byte[1024];int len;while ((len = inStream.read(buffer)) != -1) {outStream.write(buffer, 0, len);}inStream.close();return outStream.toByteArray();}/*** 读取文本文件字*/public static String getFileText(String path){try {byte[] data= getFileBytes(new File(path));return new String(data);} catch (Exception e) {return "";}}/*** 清空文件夹下所有文件*/public static void cleanDir(File dir){if(dir!=null&&dir.isDirectory()){for(File file:dir.listFiles()){if(file.isFile())file.delete();if(file.isDirectory())cleanDir(file);}}}}

LogUtils.java

public class LogUtils {public static void info(String context){System.out.println(context);}public static void warn(String context){System.out.println(context);}public static void error(String context){System.out.println(context);}}

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

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

相关文章

CSRF 攻击和 XSS 攻击分别代表什么?如何防范?

一&#xff1a;PHP 1. CSRF 攻击和 XSS 攻击分别代表什么&#xff1f; 1.CSRF攻击 1.概念&#xff1a; CSRF&#xff08;Cross-site request forgery&#xff09;跨站请求伪造&#xff0c;用户通过跨站请求&#xff0c;以合法身份做非法的事情 2.原理&#xff1a; 1.登录受信任…

或许有用的开源项目平台——物联网、区块链、商城、CMS、客服系统、低代码、可视化、ERP等

摘自个人印象笔记Evernote Export wumei-smart-物美智能开源物联网平台 官网&#xff1a;https://wumei.live/ gitee&#xff1a;https://gitee.com/kerwincui/wumei-smart 一个简单易用的物联网平台。可用于搭建物联网平台以及二次开发和学习。适用于智能家居、智慧办公、智慧…

Windows 无法安装到这个硬盘。选中的磁盘具有MBR分区。在EFI系统上,Windows只能安装到GPT磁盘

Windows无法安装到这个磁盘,选中的磁盘具有MBR分区表的解决方法 - 知乎 (zhihu.com) Windows无法安装到这个磁盘 选中的磁盘具有MBR分区表 - 知乎 (zhihu.com) 选中的磁盘具有MBR分区表&#xff0c;在EFI系统上&#xff0c;windows只能安装到GPT磁盘_选中的磁盘具有mbr分区表…

提速Rust编译器!

Nethercote是一位研究Rust编译器的软件工程师。最近&#xff0c;他正在探索如何提升Rust编译器的性能&#xff0c;在他的博客文章中介绍了Rust编译器是如何将代码分割成代码生成单元&#xff08;CGU&#xff09;的以及rustc的性能加速。 他解释了不同数量和大小的CGU之间的权衡…

Java基础集合框架学习(下)

文章目录 Dog必须改写equals方法LinkedList独有方法Set入门Set去重现象TreeSet算法依赖于一个比较接口HashMap案例map常用方法泛型入门使用泛型迭代器IteratorCollections集合框架工具类 Dog必须改写equals方法 在Java中&#xff0c;当你希望对自定义类的对象进行相等性比较时…

华为OD真题---玩牌高手--带答案

2023华为OD统一考试&#xff08;AB卷&#xff09;题库清单-带答案&#xff08;持续更新&#xff09;or2023年华为OD真题机考题库大全-带答案&#xff08;持续更新&#xff09; 玩牌高手 给定一个长度为n的整型数组&#xff0c;表示一个选手在n轮内可选择的牌面分数。选手基于规…

考虑微网新能源经济消纳的共享储能优化配置(Matlab代码实现

&#x1f4a5;&#x1f4a5;&#x1f49e;&#x1f49e;欢迎来到本博客❤️❤️&#x1f4a5;&#x1f4a5; &#x1f3c6;博主优势&#xff1a;&#x1f31e;&#x1f31e;&#x1f31e;博客内容尽量做到思维缜密&#xff0c;逻辑清晰&#xff0c;为了方便读者。 ⛳️座右铭&a…

西门子AI面试问答(STAR法则回答实例)

0.试题情况 0.未来三到五年的职业规划&#xff08;不计入成绩&#xff0c;测试用&#xff09;&#xff1b; 1.一些基本问题&#xff0c;目前所在城市目标薪资意向工作城市&#xff08;手动输入&#xff0c;非视频录制&#xff09;&#xff1b; 2.宝洁8大问的问题1个英文回答…

VSCode Remote-SSH (Windows)

1. VSCode 安装 VSCode 2. 安装扩展 Remote SSH Getting started Follow the step-by-step tutorial or if you have a simple SSH host setup, connect to it as follows: Press F1 and run the Remote-SSH: Open SSH Host… command.Enter your user and host/IP in the …

Sui网络的稳定性和高性能

Sui的最初的协议开发者设计了可扩展的网络&#xff0c;通过水平扩展的方式来保持可负担得起的gas费用。其他区块链与之相比&#xff0c;则使用稀缺性和交易成本来控制网络活动。 Sui主网上线前90天的数据指标证明了这一设计概念&#xff0c;在保持100&#xff05;正常运行的同…

实现Jenkins自动发包配置

参考抖音&#xff1a;Java不良人 其中的视频演示代码 不推荐把jenkins端口一直开放&#xff0c;推荐使用时候放开&#xff08;版本不太新&#xff0c;避免漏洞攻击&#xff09; [rootVM-4-12-centos soft]# docker-compose -v Docker Compose version v2.19.1docker-compose.…

提升效率!云原生生态从业人员不可或缺的工具集合!

&#x1f337;&#x1f341; 博主猫头虎 带您 Go to New World.✨&#x1f341; &#x1f984; 博客首页——猫头虎的博客&#x1f390; &#x1f433;《面试题大全专栏》 文章图文并茂&#x1f995;生动形象&#x1f996;简单易学&#xff01;欢迎大家来踩踩~&#x1f33a; &a…

Angular FormControl value属性的一些事

背景&#xff1a;一个输入校验&#xff0c;允许输入多行&#xff0c;每一行是ip或网段。写了个校验&#xff0c;将其按行拆分后单独校验。 1. FormControl无法深复制 使用JSON.parse(JSON.stringify(control))进行简单深复制报错&#xff0c;因为不是json类型&#xff1b;使用d…

​ATF(TF-A)安全通告 TFV-7 (CVE-2018-3639)​

ATF(TF-A)安全通告汇总 目录 一、ATF(TF-A)安全通告 TFV-7 (CVE-2018-3639) 二、静态缓解&#xff08;Static mitigation&#xff09; 三、动态缓解&#xff08;Dynamic mitigation&#xff09; 一、ATF(TF-A)安全通告 TFV-7 (CVE-2018-3639) Title TF-A披露基于cache前瞻…

92. 反转链表 II

92. 反转链表 II 题目-中等难度示例1. 获取头 反转中间 获取尾 -> 拼接2. 链表转换列表 -> 计算 -> 转换回链表 题目-中等难度 给你单链表的头指针 head 和两个整数 left 和 right &#xff0c;其中 left < right 。请你反转从位置 left 到位置 right 的链表节点…

如何适应新的算法备案要求:企业的策略与挑战

随着人工智能和机器学习技术的普及&#xff0c;其在各种行业应用中的影响也日益显著。然而&#xff0c;如此强大的技术自然也带来了各种挑战&#xff0c;特别是在确保公正和透明性方面。为此&#xff0c;许多国家开始出台算法备案的法规&#xff0c;确保这些技术在符合道德和法…

请求转发和请求重定向

目录 1. 定义层面 2. 请求方层面 3. 数据共享层面 4. 最终 url 层面 5. 代码实现层面 请求转发 请求重定向 在Java中&#xff0c;跳转网页的方式有两种&#xff0c;一种是请求转发&#xff0c;另一种是请求重定向&#xff0c;而实际上&#xff0c;这两种方式是有着明显…

JavaScript数据结构【进阶】

注&#xff1a;最后有面试挑战&#xff0c;看看自己掌握了吗 文章目录 使用 splice() 添加元素使用 slice() 复制数组元素使用展开运算符复制数组使用展开运算符合并数组使用 indexOf() 检查元素是否存在使用 for 循环遍历数组中的全部元素创建复杂的多维数组将键值对添加到对象…

“深入解析JVM:探秘Java虚拟机的工作原理“

标题&#xff1a;深入解析JVM&#xff1a;探秘Java虚拟机的工作原理 摘要&#xff1a;本文将深入探讨Java虚拟机&#xff08;JVM&#xff09;的工作原理&#xff0c;包括类加载、内存管理、垃圾回收、即时编译等关键概念。通过详细解析JVM的各个组成部分&#xff0c;读者将能够…

APP外包开发的H5开发框架

跨平台移动应用开发框架允许开发者使用一套代码在多个操作系统上构建应用程序&#xff0c;从而节省时间和资源。以下是一些常见的跨平台移动应用开发框架以及它们的特点&#xff0c;希望对大家有所帮助。北京木奇移动技术有限公司&#xff0c;专业的软件外包开发公司&#xff0…