当前位置: 首页 > news >正文

JAVA 有关PDF文件和图片文件合并并生产一个PDF

情景:

1.文件列表包含多个图片和PDF时需要对文件进行合并

2.合并时保持文件顺序

开淦:

一、导入POM

  <dependency><groupId>org.apache.pdfbox</groupId><artifactId>pdfbox</artifactId><version>2.0.24</version></dependency><dependency><groupId>org.apache.pdfbox</groupId><artifactId>fontbox</artifactId><version>2.0.24</version></dependency><dependency><groupId>org.apache.pdfbox</groupId><artifactId>xmpbox</artifactId><version>2.0.24</version></dependency><dependency><groupId>org.apache.pdfbox</groupId><artifactId>pdfbox-tools</artifactId><version>2.0.24</version></dependency>

二、Java 代码

package com.aisino.datadocking;import org.apache.pdfbox.io.MemoryUsageSetting;
import org.apache.pdfbox.multipdf.PDFMergerUtility;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.graphics.image.LosslessFactory;
import org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject;import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;/*** @description: ImgPDF* @author: Stiven* @create: 2023-12-20 16:57**/
public class MergeImgPDFUntil {public static void main(String[] args) throws Exception {String[] urls={"http://+IP+wKgFOGV7uYuAMWldAAMsi8rvZ3Y062.jpg","http:+IP+/group1/M01/03/76/wKgFOGWKOA6AZ5i-eecoQ405.pdf","http://+IP+/group1/M01/02/FF/wKgFOGV7ubyAb6q3AATSEcwOiu8024.jpg"};//文件临时存储位置(必须) 同时需要定时清理String target = "/Users/stiven/IdeaProjects/tmp/";List<String> fileList = new ArrayList<>();for(String url:urls){fileList.add(downloadFile(url,target));}// 执行合并mergePDFAndImages(fileList,target);}/*** 文件和图片同时合并* @param FileList     需要合并的文件地址list* @param mergedFilePath  合并后文件存储位置* @throws Exception*/public static String mergePDFAndImages( List<String> FileList, String mergedFilePath) throws Exception {
// 创建一个 PDFMergerUtility 对象PDFMergerUtility merger = new PDFMergerUtility();for (String filePath : FileList) {String extension = "";int dotIndex = filePath.lastIndexOf(".");if (dotIndex > 0 && dotIndex < filePath.length() - 1) {extension = filePath.substring(dotIndex + 1).toLowerCase();}if(extension.equals("pdf")){merger.addSource(new File(filePath));}else if(extension.equals("png")||extension.equals("jpg")||extension.equals("jpeg")){merger.addSource(convertImageToPdf(new File(filePath),mergedFilePath));}}String mergeTmpFilePath=mergedFilePath+UUID.randomUUID().toString() +"_merged.pdf";// 合并所有文件并写入指定文件merger.setDestinationFileName(mergeTmpFilePath);merger.mergeDocuments(MemoryUsageSetting.setupMainMemoryOnly());return mergeTmpFilePath;}/*** 图片转pdf* @param imageFile* @return* @throws IOException*/private static String convertImageToPdf(File imageFile,String mergedFilePath) throws IOException {//图片临时记录pdf文件存储,未做删除。String tempPdfFilename = mergedFilePath+UUID.randomUUID().toString() + ".pdf";BufferedImage image = ImageIO.read(imageFile);float width = image.getWidth();float height = image.getHeight();PDDocument document = new PDDocument();PDPage page = new PDPage();document.addPage(page);try (FileInputStream fis = new FileInputStream(imageFile)) {PDImageXObject pdImage = LosslessFactory.createFromImage(document, ImageIO.read(fis));float pageWidth = page.getMediaBox().getWidth();float pageHeight = page.getMediaBox().getHeight();//图片高宽自适应pdfif (width > pageWidth || height > pageHeight) {float scale = Math.min(pageWidth / width, pageHeight / height);float scaledWidth = width * scale;float scaledHeight = height * scale;float x = (pageWidth - scaledWidth) / 2;float y = (pageHeight - scaledHeight) / 2;page.setCropBox(new PDPage().getMediaBox());page.setMediaBox(new PDPage().getMediaBox());page.setBleedBox(new PDPage().getMediaBox());page.setTrimBox(new PDPage().getMediaBox());page.setArtBox(new PDPage().getMediaBox());PDPageContentStream contentStream = new PDPageContentStream(document, page);contentStream.drawImage(pdImage, x, y, scaledWidth, scaledHeight);contentStream.close();} else {PDPageContentStream contentStream = new PDPageContentStream(document, page);contentStream.drawImage(pdImage, 0, 0);contentStream.close();}}document.save(tempPdfFilename);document.close();return tempPdfFilename;}/*** 文件下载* @param fileUrl* @param targetDirectory* @throws IOException*/public static String  downloadFile(String fileUrl, String targetDirectory) throws IOException {URL url = new URL(fileUrl);HttpURLConnection connection = (HttpURLConnection) url.openConnection();String filePath="";try (InputStream inputStream = new BufferedInputStream(connection.getInputStream())) {String fileName = getFileNameFromUrl(fileUrl);filePath = targetDirectory + fileName;try (FileOutputStream outputStream = new FileOutputStream(filePath)) {byte[] buffer = new byte[1024];int bytesRead;while ((bytesRead = inputStream.read(buffer)) != -1) {outputStream.write(buffer, 0, bytesRead);}}}connection.disconnect();return filePath;}/*** 获取文件名称* @param fileUrl* @return*/public static String getFileNameFromUrl(String fileUrl) {int lastIndexOfSlash = fileUrl.lastIndexOf("/");if (lastIndexOfSlash != -1 && lastIndexOfSlash < fileUrl.length() - 1) {return fileUrl.substring(lastIndexOfSlash + 1);}return "";}}

http://www.lryc.cn/news/267819.html

相关文章:

  • 八股文打卡day10——计算机网络(10)
  • Spring Boot学习:Flyway详解
  • Spark编程实验三:Spark SQL编程
  • 文献研读|Prompt窃取与保护综述
  • cfa一级考生复习经验分享系列(十四)
  • vue本地缓存搜索记录(最多4条)
  • Linux创建Macvlan网络
  • 从企业级负载均衡到云原生,深入解读F5
  • 什么是redis雪崩
  • [足式机器人]Part2 Dr. CAN学习笔记-Ch00 - 数学知识基础
  • Jmeter、postman、python 三大主流技术如何操作数据库?
  • IRIS、Cache系统类汉化
  • 【三维生成】稀疏重建、Image-to-3D方法(汇总)
  • Java基础知识:单元测试和调试技巧
  • [c]扫雷
  • 数据结构-十大排序算法
  • Apache RocketMQ,构建云原生统一消息引擎
  • (四) ClickHouse 中使用 `MaterializedMySQL` 引擎单独同步 MySQL 数据库中的特定表(例如 `aaa` 和 `bbb`)
  • TikTok真题第4天 | 1366. 通过投票对团队排名、1029.两地调度、562.矩阵中最长的连续1线段
  • 时序预测 | Matlab实现SSA-CNN-LSTM麻雀算法优化卷积长短期记忆神经网络时间序列预测
  • 负载均衡——Ribbon
  • 7.微服务设计原则
  • 【MATLAB库函数系列】线性调频Z(Chirp-Z,CZT)的MATLAB源码和C语言实现
  • BIT-6-指针(C语言初阶学习)
  • 傻瓜式教学Docker 使用docker compose部署 php nginx mysql
  • node express简单微服务
  • nginx-proxy-manager初次登录502 bad gateway
  • Servlet见解2
  • 【SpringCloud】-OpenFeign实战及源码解析、与Ribbon结合
  • 走进数字金融峰会,为金融科技数字化赋能