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

相关推荐
皮肤科大白5 小时前
无法将ggplot图保存为PDF文件怎么办
pdf
程序员皮皮林1 天前
开源PDF工具 Apache PDFBox 认识及使用(知识点+案例)
java·pdf·开源·apache
weixin_419349791 天前
Python pdf转换为html
python·pdf
易我科技1 天前
PDF里怎么直接编辑文字?简单操作指南
pdf
海绵波波1073 天前
Zotero使用(一)PDF文件导入不会自动识别
pdf
2401_856926933 天前
图片转PDF技巧揭秘:四款高效工具推荐!
学习·pdf·图片转pdf·图片转pdf工具
alex18013 天前
python实现多个pdf文件合并
java·python·pdf
似璟如你3 天前
Vue点击按钮生成pdf文件/Vue点击按钮生成png图片
pdf
deephub3 天前
概率分布深度解析:PMF、PDF和CDF的技术指南
人工智能·python·机器学习·pdf·概率论
William.csj3 天前
PDF——压缩大小的方法
pdf