JAVA PDF 截取N页,生成新文件,转图片,多个PDF 合并

<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.5.13</version>
</dependency>
import com.itextpdf.text.Document;
import com.itextpdf.text.pdf.PdfCopy;
import com.itextpdf.text.pdf.PdfImportedPage;
import com.itextpdf.text.pdf.PdfReader;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPageTree;
import org.apache.pdfbox.rendering.PDFRenderer; import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*; public class PdfUtil { /**
* 截取pdfFile的第from页至第end页,组成一个新的文件名
*
* @param pdfFile 要切割的pdf文件
* @param newFile 切割后形成的新的pdf文件
* @param from 从第N页开始
* @param end 到第N页结束
*/
public static void partitionPdf(String pdfFile, String newFile, int from, int end) {
Document document = null;
PdfCopy copy = null;
PdfReader reader = null;
try {
reader = new PdfReader(pdfFile);
int pageCount = reader.getNumberOfPages();
if (from < 1) {
from = 1;
}
if (from > pageCount) {
from = pageCount;
}
if (end == 0 || end > pageCount) {
end = pageCount;
}
document = new Document(reader.getPageSize(1));
copy = new PdfCopy(document, new FileOutputStream(newFile));
document.open();
for (int j = from; j <= end; j++) {
document.newPage();
PdfImportedPage page = copy.getImportedPage(reader, j);
copy.addPage(page);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (document != null) {
document.close();
}
if (copy != null) {
copy.close();
}
if (reader != null) {
reader.close();
}
}
} /**
* pdf转图片
*
* @param pdfFile PDF 文件
* @param imageFile 输出的图片文件
* @param from 开始页 从1开始
* @param end 结束页 最大为PDF总页数
* @throws Exception
*/
public static void pdfToImage(String pdfFile, String imageFile, int from, int end) throws Exception {
PDDocument doc = null;
ByteArrayOutputStream os = null;
InputStream stream = null;
OutputStream out = null;
try {
//pdf路径
stream = new FileInputStream(pdfFile);
// 加载解析PDF文件
doc = PDDocument.load(stream);
PDFRenderer pdfRenderer = new PDFRenderer(doc);
PDPageTree pages = doc.getPages();
int pageCount = pages.getCount();
if (from < 1) {
from = 1;
}
if (from > pageCount) {
from = pageCount;
}
if (end == 0 || end > pageCount) {
end = pageCount;
}
for (int i = from; i <= end; i++) {
BufferedImage bim = pdfRenderer.renderImageWithDPI(i - 1, 200); //PDFBOX 是从0开始的,from初始值为1,所以这边要减 i-1
os = new ByteArrayOutputStream();
ImageIO.write(bim, "jpg", os);
byte[] dataList = os.toByteArray();
//只取一页,等于传进来的名称,多页时,加上 页号
String imageFilePath = from == end ? saveImgFile : saveImgFile.replace(".jpg", "_" + i + ".jpg");
File file = new File(imageFilePath);
if (!file.getParentFile().exists()) {
// 不存在则创建父目录及子文件
file.getParentFile().mkdirs();
file.createNewFile();
}
out = new FileOutputStream(file);
out.write(dataList);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (doc != null) {
doc.close();
}
if (os != null) {
os.close();
}
if (stream != null) {
stream.close();
}
if (out != null) {
out.close();
}
}
} //多个PDF合并成一个
public static void mergePDFFiles(List<String> pdfFiles, String outputPdf) throws IOException {
// 创建一个新的 PDF 阅读器对象和一个新的 PDF 写入对象
PdfReader reader = null;
PdfCopy copy = null;
Document document = new Document();
try {
// 创建 PDF 阅读器对象和写入对象
reader = new PdfReader(pdfFiles.get(0));
copy = new PdfCopy(document, new FileOutputStream(outputPdf));
// 打开文档准备写入内容
document.open(); // 将第一个 PDF 的所有页面复制到输出 PDF 中
for (int i = 1; i <= reader.getNumberOfPages(); i++) {
PdfImportedPage page = copy.getImportedPage(reader, i);
copy.addPage(page);
} // 将其它PDF的所有页,输出到 PDF 中
for (int i = 1; i < pdfFiles.size(); i++) {
reader = new PdfReader(pdfFiles.get(i));
for (int j = 1; j <= reader.getNumberOfPages(); j++) {
PdfImportedPage page = copy.getImportedPage(reader, j);
copy.addPage(page);
}
} } catch (Exception e) {
e.printStackTrace();
} finally {
if (document != null) {
document.close();
}
if (copy != null) {
copy.close();
}
if (reader != null) {
reader.close();
}
}
}
}

@Test
void pdf() throws Exception {
String pdfFile = "D:\\Desktop\\20220117.pdf";
String jpgFile = "D:\\Desktop\\20220117.jpg";
PdfUtil.pdfToImage(pdfFile, jpgFile, 1, 1);
} @Test
void testMerge() throws IOException {
List<String> pdfFiles = new ArrayList<>();
pdfFiles.add("D:\\Projects\\20231225180735.pdf");
pdfFiles.add("D:\\Projects\\20231225182535.pdf");
pdfFiles.add("D:\\Projects\\20231225184135.pdf");
PdfUtil.mergePDFFiles(pdfFiles, "D:\\Projects\\New.pdf");
}

JAVA PDF 截取N页,生成新文件,转图片,多个PDF 合并的更多相关文章

  1. java 写 Excel(不生成实体文件,写为流的形式)

    java 写 Excel(不生成实体文件,写为流的形式) public String exportReportExcel(String mediaCode, List<SimpleMediaRe ...

  2. Java写Excel(不生成实体文件,写为流的形式)

    java 写 Excel(不生成实体文件,写为流的形式) public String exportReportExcel(String mediaCode, List<SimpleMediaRe ...

  3. JAVA - SpringBoot项目引用generator生成 Mybatis文件

    JAVA - SpringBoot项目引用generator生成 Mybatis文件  在spring官网https://start.spring.io/自动生成springboot项目,这里选择项目 ...

  4. Java中使用DOM4J来生成xml文件和解析xml文件

    一.前言 现在有不少需求,是需要我们解析xml文件中的数据,然后导入到数据库中,当然解析xml文件也有好多种方法,小编觉得还是DOM4J用的最多最广泛也最好理解的吧.小编也是最近需求里遇到了,就来整理 ...

  5. [.Net] - 使用 iTextSharp 生成基于模板的 PDF,生成新文件并保留表单域

    背景 基于 PDF Template 预填充表单项,生成一份新的 PDF 文件,并保留表单域允许继续修改. 代码段 using iTextSharp.text.pdf; /* Code Snippet ...

  6. linux提取指定字符的行列并生成新文件(awk命令)

    如图所示,命名为file文件的表头有BP.A1.TEST等 假如想提取含有"ADD"的行和该行对应列的"BP"和"P"值,则需要用到以下命令 ...

  7. 转载:C#保存文件时重名自动生成新文件的方法

    /// <summary> /// Generates a new path for duplicate filenames. /// </summary> /// <p ...

  8. shell脚本选择LOG里面特定的行,生成新文件并rsync上传

    rsync.sh #!/bin/bash tool_path=$(cd `dirname $`; pwd) eval `cat ${tool_path}/conf.properties` rsync_ ...

  9. 根据html生成Word文件,包含图片

    根据html内容生成word,并自动下载下来.使用到了itext-1.4.6.jar import java.io.File; import java.io.FileInputStream; impo ...

  10. java 在MySQL中存储文件,读取文件(包括图片,word文档,excel表格,ppt,zip文件等)

    转自:https://blog.csdn.net/u014475796/article/details/49893261 在设计到数据库的开发中,难免要将图片或文档文件(如word)插入到数据库中的情 ...

随机推荐

  1. JUC并发编程学习笔记(十五)JMM

    JMM 请你谈谈对Volatile的理解 Volatile是java虚拟机提供的轻量级的同步机制 1.保证可见性 2.不保证原子性 3.禁止指令重排 什么是JMM JVM->java虚拟机 JM ...

  2. Navicat Premium破解工具及教程

    使用Navicat_Keygen_Patch5破解Navicat Premium 更新:2019-06-11 10:16 使用Navicat_Keygen_Patch_v5.0_By_DFoX破解Na ...

  3. matlab实现频谱感知-认知无线电

    1.前言 \(\quad\) 频谱感知的方法有很多,比如匹配滤波探测,能量检测,静态循环特征探测等方法,然后最近因为在用硬件做能量检测,所以本文主要是说了如何用matlab实现能量检测,它的大概流程就 ...

  4. 面向对象java前三次pta作业

    目录: 1.前言 2.设计与分析 3.踩坑心得 4.主要困难及改进建议 5.总结 1.前言 面向对象程序设计(Object-Oriented Programming,简称OOP)是一种编程范式,它以对 ...

  5. 信创就用国产的 Solon Java Framework,v2.6.0 发布

    先吹牛! 在 v2.6 这个新的里程碑节点,Solon 又完成了几件惊天大事(每一件,都是经历了漫长时间打磨与积累): (1)Solon Native,有了第一个开源案例:dromara/neutri ...

  6. Eclipse 安装 ABAP 插件报错 Microsoft Visual C++ 2013 (x64) 快速解决

    去官网下载Microsoft Visual C++ 2013 (x64) 安装   Download Visual C++ Redistributable Packages for Visual St ...

  7. 如何实现图像搜索,文搜图,图搜图,CLIP+faiss向量数据库实现图像高效搜索

    如何实现图像搜索,文搜图,图搜图,CLIP+faiss向量数据库实现图像高效搜索 这是AIGC的时代,各种GPT大模型生成文本,还有多模态图文并茂大模型, 以及stable diffusion和sta ...

  8. C++ Qt开发:TreeWidget 树形选择组件

    Qt 是一个跨平台C++图形界面开发库,利用Qt可以快速开发跨平台窗体应用程序,在Qt中我们可以通过拖拽的方式将不同组件放到指定的位置,实现图形化开发极大的方便了开发效率,本章将重点介绍TreeWid ...

  9. Celery 定义和调用异步任务Task

    https://docs.celeryq.dev/en/stable/userguide/tasks.html 使用app.task装饰器定义 需要通过导入celery app,然后使用@app.ta ...

  10. django自带的cache缓存框架使用

    https://docs.djangoproject.com/zh-hans/4.2/topics/cache/#top 主要步骤官网也写得很清楚了,包含怎么区使用. 这里就展示一些配置django- ...