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

简介: 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");
}
目录
相关文章
|
7天前
|
Arthas Java 测试技术
Java字节码文件、组成,jclasslib插件、阿里arthas工具,Java注解
Java字节码文件、组成、详解、分析;常用工具,jclasslib插件、阿里arthas工具;如何定位线上问题;Java注解
Java字节码文件、组成,jclasslib插件、阿里arthas工具,Java注解
|
6天前
|
Java API 开发者
【Java字节码操控新篇章】JDK 22类文件API预览:解锁Java底层的无限可能!
【9月更文挑战第6天】JDK 22的类文件API为Java开发者们打开了一扇通往Java底层世界的大门。通过这个API,我们可以更加深入地理解Java程序的工作原理,实现更加灵活和强大的功能。虽然目前它还处于预览版阶段,但我们已经可以预见其在未来Java开发中的重要地位。让我们共同期待Java字节码操控新篇章的到来!
|
3天前
|
Java API 开发者
【Java字节码的掌控者】JDK 22类文件API:解锁Java深层次的奥秘,赋能开发者无限可能!
【9月更文挑战第8天】JDK 22类文件API的引入,为Java开发者们打开了一扇通往Java字节码操控新世界的大门。通过这个API,我们可以更加深入地理解Java程序的底层行为,实现更加高效、可靠和创新的Java应用。虽然目前它还处于预览版阶段,但我们已经可以预见其在未来Java开发中的重要地位。让我们共同期待Java字节码操控新篇章的到来,并积极探索类文件API带来的无限可能!
|
4天前
|
算法 Java
Java 压缩文件
在Java中压缩文件是一个常见的需求,通常可以通过使用Java自带的`java.util.zip`包来实现。这个包提供了`ZipOutputStream`类来创建ZIP格式的压缩文件。以下是一个简单的示例,展示了如何将多个文件压缩到一个ZIP文件中。 ### 示例:将多个文件压缩到一个ZIP文件中 ```java import java.io.*; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; public class ZipFilesExample { public static vo
|
9天前
|
数据采集 存储 前端开发
Java爬虫开发:Jsoup库在图片URL提取中的实战应用
Java爬虫开发:Jsoup库在图片URL提取中的实战应用
|
13天前
|
移动开发 资源调度 JavaScript
Vue移动端网页(H5)预览pdf文件(pdfh5和vue-pdf)
这篇文章介绍了在Vue移动端网页中使用`pdfh5`和`vue-pdf`两个插件来实现PDF文件的预览,包括滚动查看、缩放、添加水印、分页加载、跳转指定页数等功能。
Vue移动端网页(H5)预览pdf文件(pdfh5和vue-pdf)
|
11天前
|
C# 开发者 Windows
WPF与PDF文档:解锁创建和编辑PDF文件的新技能——从环境配置到代码实践,手把手教你如何在WPF应用中高效处理PDF,提升文档管理效率
【8月更文挑战第31天】随着数字文档的普及,PDF因跨平台兼容性和高保真度成为重要格式。WPF虽不直接支持PDF处理,但借助第三方库(如iTextSharp)可在WPF应用中实现PDF的创建与编辑。本文通过具体案例和示例代码,详细介绍了如何在WPF中集成PDF库,并展示了从设计用户界面到实现PDF创建与编辑的完整流程。不仅包括创建新文档的基本步骤,还涉及在现有PDF中添加页眉页脚等高级功能。通过这些示例,WPF开发者可以更好地掌握PDF处理技术,提升应用程序的功能性和实用性。
26 0
|
12天前
|
Java
java判断文件内容不为空
请注意,在实际的生产环境中,处理文件时需要考虑异常处理。在上述代码中,如果在文件读取过程中发生 `IOException`,则会被捕获,并在控制台打印堆栈跟踪信息。在更复杂的系统中,可能还需要更精细的异常处理策略。
25 0
|
27天前
|
XML 缓存 JSON
为什么浏览器中有些图片、PDF等文件点击后有些是预览,有些是下载
为什么浏览器中有些图片、PDF等文件点击后有些是预览,有些是下载
96 0
|
30天前
|
Linux Python Windows
Python PDF文件转Word格式,只需要3秒(附打包)
Python PDF文件转Word格式,只需要3秒(附打包)
46 3
Python PDF文件转Word格式,只需要3秒(附打包)