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");
}
目录
相关文章
|
3天前
|
Java
Java开发实现图片URL地址检验,如何编码?
【10月更文挑战第14天】Java开发实现图片URL地址检验,如何编码?
16 4
|
3天前
|
Java
Java开发实现图片地址检验,如果无法找到资源则使用默认图片,如何编码?
【10月更文挑战第14天】Java开发实现图片地址检验,如果无法找到资源则使用默认图片,如何编码?
16 2
|
3天前
|
Java 数据安全/隐私保护
Java ffmpeg 实现视频加文字/图片水印功能
【10月更文挑战第22天】在 Java 中使用 FFmpeg 实现视频加文字或图片水印功能,需先安装 FFmpeg 并添加依赖(如 JavaCV)。通过构建 FFmpeg 命令行参数,使用 `drawtext` 滤镜添加文字水印,或使用 `overlay` 滤镜添加图片水印。示例代码展示了如何使用 JavaCV 实现文字水印。
|
4天前
|
Java Apache Maven
将word文档转换成pdf文件方法
在Java中,将Word文档转换为PDF文件可采用多种方法:1) 使用Apache POI和iText库,适合处理基本转换需求;2) Aspose.Words for Java,提供更高级的功能和性能;3) 利用LibreOffice命令行工具,适用于需要开源解决方案的场景。每种方法都有其适用范围,可根据具体需求选择。
|
4天前
|
Java
Java开发如何实现文件的移动,但是在移动结束后才进行读取?
【10月更文挑战第13天】Java开发如何实现文件的移动,但是在移动结束后才进行读取?
13 2
|
4天前
|
Java Apache Maven
Java将word文档转换成pdf文件的方法?
【10月更文挑战第13天】Java将word文档转换成pdf文件的方法?
12 1
|
4天前
|
监控 Java
Java定时扫码一个文件夹下的文件,如何保证文件写入完成后才进行处理?
【10月更文挑战第13天】Java定时扫码一个文件夹下的文件,如何保证文件写入完成后才进行处理?
16 1
|
8天前
|
小程序 Oracle Java
JVM知识体系学习一:JVM了解基础、java编译后class文件的类结构详解,class分析工具 javap 和 jclasslib 的使用
这篇文章是关于JVM基础知识的介绍,包括JVM的跨平台和跨语言特性、Class文件格式的详细解析,以及如何使用javap和jclasslib工具来分析Class文件。
21 0
JVM知识体系学习一:JVM了解基础、java编译后class文件的类结构详解,class分析工具 javap 和 jclasslib 的使用
|
5天前
|
JavaScript 前端开发 容器
Vue生成PDF文件攻略:html2canvas与jspdf联手,中文乱码与自动换行难题攻克
Vue生成PDF文件攻略:html2canvas与jspdf联手,中文乱码与自动换行难题攻克
11 0
|
消息中间件 缓存 运维
憋了半个月的 PDF:精通 Java(七)
真诚的和大家说一句抱歉,因为最近家庭原因 + 我自己思想的懒惰,所以导致有一段时间没有更新技术文章,一直都在憋这一篇关于学习 Java 如何从入门到精通的文章,在没有发文的这段时间很煎熬,甚至无数次的想放弃写这篇文章,因为这篇文章不是很好写,我付出大量的时间和心血来收集大量的素材、研究大量的书本进而熔铸成这篇文章,希望对你有所帮助。
憋了半个月的 PDF:精通 Java(七)