Java 通过页码范围提取新的文档(docx、pdf)

客户有一个新的需求。控制用户下载文档的页数。比如。我设置只开放10页。那就要我们去做截取文档。pdf自带有实现的方式。docx暂时没找到开源的。我这边处理的docx。是通过转换成pdf。通过截取pdf后再转成docx去实现的

工具类如下:

复制代码
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
import java.util.Objects;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.PdfCopy;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfSmartCopy;

/**
 * PDF工具类
 */
public class PdfUtils {
    /**
     * 抽取PDF文件
     *
     * @param sourceFile        源PDF文件路径
     * @param targetFile        目标PDF文件路径
     * @param extractedPageNums 需要抽取的页码)
     */
    public static void extract(String sourceFile, String targetFile, List<Integer> extractedPageNums) {
        Objects.requireNonNull(sourceFile);
        Objects.requireNonNull(targetFile);
        PdfReader reader = null;
        Document document = null;
        FileOutputStream outputStream = null;
        PdfCopy pdfCopy = null;
        try {
            // 读取源文件
            reader = new PdfReader(sourceFile);
            // 创建新的文档
            document = new Document();
            // 创建目标PDF文件
            outputStream = new FileOutputStream(targetFile);
            pdfCopy = new PdfSmartCopy(document, outputStream);
            // 获取源文件的页数
            int pages = reader.getNumberOfPages();
            document.open();
            // 注意此处的页码是从1开始
            for (int page = 1; page <= pages; page++) {
                // 如果是指定的页码,则进行复制
                if (extractedPageNums.contains(page)) {
                    pdfCopy.addPage(pdfCopy.getImportedPage(reader, page));
                }
            }
        } catch (IOException | DocumentException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                reader.close();
            }
            if (document != null) {
                document.close();
            }
            if (outputStream != null) {
                try {
                    outputStream.flush();
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(pdfCopy != null){
                pdfCopy.flush();
                pdfCopy.close();
            }
        }
    }
}

如果想实现docx和pdf互转格式不变。请参考另一篇文章

java 实现docx和pdf互转并保留格式_王威振的csdn的博客-CSDN博客

相关推荐
开开心心就好17 小时前
发票合并打印工具,多页布局设置实时预览
linux·运维·服务器·windows·pdf·harmonyos·1024程序员节
软件工程小施同学19 小时前
区块链论文速读 CCF A--VLDB 2025 (1) 附pdf下载
pdf·区块链
Java面试题总结2 天前
基于 Java 的 PDF 文本水印实现方案(iText7 示例)
java·python·pdf
傻啦嘿哟3 天前
Python操作PDF页面详解:删除指定页的完整方案
开发语言·python·pdf
m5655bj3 天前
使用 C# 修改 PDF 页面尺寸
java·pdf·c#
geovindu3 天前
python: 简单提取PDF文档内文字
开发语言·python·pdf
m0_694845573 天前
HandBrake 是什么?视频转码工具使用与服务器部署教程
服务器·前端·pdf·开源·github·音视频
yivifu4 天前
使用PyMuPdf删除PDF文档中的水印
pdf·pymupdf·去水印
ComPDFKit4 天前
ComPDF的产品升级:从工具包到PDF服务
pdf
占疏4 天前
pdf文件解析
pdf