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博客

相关推荐
月巴月巴白勺合鸟月半16 小时前
PDF转图片的另外一种方法
pdf·c#
多则惑少则明16 小时前
AI大模型综合(四)langchain4j 解析PDF文档
pdf·springboot·大语言模型
m5655bj16 小时前
使用 C# 对比两个 PDF 文档的差异
pdf·c#·visual studio
WXDcsdn16 小时前
Windows无法使用Microsoft to PDF输出PDF文件
windows·pdf·电脑·it运维
Yqlqlql17 小时前
基于 Python+PySide6 开发的本地复合文件工具:图片转 PDF+PDF 转 Word 双功能
pdf
softshow102619 小时前
html2canvas + jspdf实现页面导出成pdf
开发语言·javascript·pdf
木叶子---19 小时前
pdf生成排查记录与解决方案
java·pdf
开开心心_Every20 小时前
文件数量统计工具:支持多层文件夹数量统计
游戏·微信·pdf·excel·语音识别·swift·lisp
萧技电创EIIA21 小时前
node-red导出图表PDF
pdf
小程故事多_801 天前
攻克RAG系统最后一公里 图文混排PDF解析的挑战与实战方案
人工智能·架构·pdf·aigc