JAVA PDF 截取N页,生成新文件,转图片,多个PDF 合并
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 合并的更多相关文章
- java 写 Excel(不生成实体文件,写为流的形式)
java 写 Excel(不生成实体文件,写为流的形式) public String exportReportExcel(String mediaCode, List<SimpleMediaRe ...
- Java写Excel(不生成实体文件,写为流的形式)
java 写 Excel(不生成实体文件,写为流的形式) public String exportReportExcel(String mediaCode, List<SimpleMediaRe ...
- JAVA - SpringBoot项目引用generator生成 Mybatis文件
JAVA - SpringBoot项目引用generator生成 Mybatis文件 在spring官网https://start.spring.io/自动生成springboot项目,这里选择项目 ...
- Java中使用DOM4J来生成xml文件和解析xml文件
一.前言 现在有不少需求,是需要我们解析xml文件中的数据,然后导入到数据库中,当然解析xml文件也有好多种方法,小编觉得还是DOM4J用的最多最广泛也最好理解的吧.小编也是最近需求里遇到了,就来整理 ...
- [.Net] - 使用 iTextSharp 生成基于模板的 PDF,生成新文件并保留表单域
背景 基于 PDF Template 预填充表单项,生成一份新的 PDF 文件,并保留表单域允许继续修改. 代码段 using iTextSharp.text.pdf; /* Code Snippet ...
- linux提取指定字符的行列并生成新文件(awk命令)
如图所示,命名为file文件的表头有BP.A1.TEST等 假如想提取含有"ADD"的行和该行对应列的"BP"和"P"值,则需要用到以下命令 ...
- 转载:C#保存文件时重名自动生成新文件的方法
/// <summary> /// Generates a new path for duplicate filenames. /// </summary> /// <p ...
- shell脚本选择LOG里面特定的行,生成新文件并rsync上传
rsync.sh #!/bin/bash tool_path=$(cd `dirname $`; pwd) eval `cat ${tool_path}/conf.properties` rsync_ ...
- 根据html生成Word文件,包含图片
根据html内容生成word,并自动下载下来.使用到了itext-1.4.6.jar import java.io.File; import java.io.FileInputStream; impo ...
- java 在MySQL中存储文件,读取文件(包括图片,word文档,excel表格,ppt,zip文件等)
转自:https://blog.csdn.net/u014475796/article/details/49893261 在设计到数据库的开发中,难免要将图片或文档文件(如word)插入到数据库中的情 ...
随机推荐
- Java 基础学习第二弹
1. HashMap和HashT able的区别 HashMap和Hashtable是两种常见的哈希表数据结构,它们在实现上有一些区别. 线程安全性:Hashtable是线程安全的,而HashMap不 ...
- 开源模型 Zephyr-7B 发布——跨越三大洲的合作
最近我们刚刚发布了新的开源模型 Zephry-7B,这个模型的诞生离不开全球三大洲开源社区的协作 ️. 我们的 CSO Thomas 录了一个视频介绍了它的起源故事: 就在几个月前,巴黎的一个新团队发 ...
- 嵌入式C编码规范
每个程序员都有自己的编码风格,自己喜欢就好. 嵌入式C编码规范 上述博文来自转载
- 终端必备大杀器----Fish
目录 下载 安装 添加 权限 依赖库安装 cmake 预处理 编译 安装 配置fish 其他 下载 Github 地址-- fish-shell openSUSE 开源下载地址 openSUSE 开源 ...
- 后台获取的map集合封装json
let list = [] let arr = {'a':'1','b':'2','c':'3','d':'4'} for(var key in arr){ console.log("key ...
- [JDK/APM] 应用诊断工具之VisualVM
1 概述 1.1 简介 VisualVM is a visual tool integrating commandline JDK tools and lightweight profiling ca ...
- .NET开源且好用的权限工作流管理系统
前言 系统权限管理.工作流是企业应用开发中很常见的功能,虽说开发起来难度不大,但是假如从零开始开发一个完整的权限管理和工作流平台的话也是比较耗费时间的.今天推荐一款.NET开源且好用的权限工作流管理系 ...
- .Net 8与硬件设备能碰撞出怎么样的火花(使用ImageSharp和Protobuf协议通过HidApi与设备通讯)
前言 本人最近在社区里说想做稚晖君的那个瀚文键盘来着,结果遇到两个老哥一个老哥送了我电路板,一个送了我焊接好元件的电路板,既然大家这么舍得,那我也就真的投入制作了这把客制化键盘,当然我为了省钱也是特意 ...
- 【C++】关于引用类型学习记录
学习模板(泛型)的时候针对定义为引用类型有些费解 1 class BigType { 2 // 假设这里有大量的数据和复杂的操作 3 }; 4 5 template <typename T> ...
- ASR项目实战-后处理
本文深入探讨后处理环节. 在本环节要处理的重要特性有分词.断句.标点符号.大小写.数字等的格式归一等. 分词 和NLP.搜索等场景下的分词含义不同.对于拼音类的语言,比如英语.法语等,句子由多个单词组 ...