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. 【pwn】[MoeCTF 2022]babyfmt --格式化字符串漏洞,got表劫持

    拿到程序,先checksec一下 发现是Partial RELRO,got表可修改 当RELRO保护为NO RELRO的时候,init.array.fini.array.got.plt均可读可写:为P ...

  2. ST 表

    ST 表 定义 ST 表是用于解决 可重复贡献问题 的数据结构,通俗来说,一般可以解决区间查询问题. 区间最值和 \(gcd\) 我们以最大值为例,然后可以再推广到最小值和区间 \(gcd\) 首先你 ...

  3. Atcoder abc 221 E - LEQ

    原题链接:E - LEQ 思路: 题目要求对于从数组1~n找出所有符合开头数字小于等于结尾数字的子序列,\(A' = (A_1', A_2', ... , A_k')\),满足\(A_1' \leq ...

  4. 玩转开源 | 搭建 Hugo 管理 Markdown 文档

    在工作.学习中,不可避免会要写一些文档:又或者想搭建个简单网站,记录和分享您的生活经验或知识:撰写这些文档中使用 markdown 是一个非常不错的选择,让我们更加聚焦在文档表达的内容上.实际上笔者的 ...

  5. GPTs大受欢迎但问题多,企服软件厂商的AI Agent更被B端客户器重

    GPTs大受欢迎但问题多,企服软件厂商的AI Agent更被B端客户器重 比尔盖茨预言智能体是下个平台,超自动化平台的AI Agent更靠谱? 以GPTs为代表的AI Agent只是玩具?揭秘真实可用 ...

  6. 方法覆盖Override

    继承作用: 基本作用:代码复用 重要作用:方法覆盖和多态机制 ===================================================================== ...

  7. 通信技术 Communication

    缩写 全称 翻译 备注 I2C Inter-Integrated Circuit 集成电路总线 通信协议 SPI Serial Peripheral Interface 串行外设接口 通信协议 QSP ...

  8. 从根上理解elasticsearch(lucene)查询原理(1)-lucece查询逻辑介绍

    大家好,我是蓝胖子,最近在做一些elasticsearch 慢查询优化的事情,通常用分析elasticsearch 慢查询的时候可以通过profile api 去分析,分析结果显示的底层lucene在 ...

  9. docker启动完美容器的过程

    这里是我用docker启动所有常见的容器完美的过程,就是一次创建,后面就可以一直使用 文档: nanshaws/docker-everything: 用docker来创建各种容器,完美文档教你按照步骤 ...

  10. 基于python人脸识别考勤系统(语音播报)

    介绍: 本项目是大二寒假在家没事写的,一直没有时间讲本项目分享出来,现在有时间了哈.那就让我简单的将项目介绍一下吧.好了废话不多说了,直接上图 初始化界面: 可以看到所有的功能都展现在了左边的功能栏中 ...