You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

iText可提取PDF文本但PdfCopy复制页面提示需所有者密码如何解决

iText PdfCopy复制PDF页面报错解决方案

报错根因

你遇到的问题有两个核心原因:

  • 目标PDF设置了权限保护:文本提取权限为公开状态,所以PdfReaderContentParser可以正常读取文本内容,但页面复制属于编辑类操作,iText要求必须提供PDF的所有者密码才能执行该类操作
  • 代码存在页码逻辑错误:iText操作PDF时页码从1开始计数,你的循环中从0开始传入页码,即使密码校验通过也会触发页码越界报错

修复步骤

  1. 构造PdfReader时传入所有者密码,使用带密码参数的构造方法:PdfReader(String filePath, byte[] ownerPassword)
  2. 修正循环内的页码参数,传入i+1作为要复制的页码,同时获取页面尺寸时也要对应使用实际页码,避免所有拆分页面都和第一页尺寸一致

修复后完整代码

import java.io.FileOutputStream;
import com.itextpdf.text.Document;
import com.itextpdf.text.pdf.PdfCopy;
import com.itextpdf.text.pdf.PdfImportedPage;
import com.itextpdf.text.pdf.PdfReader;

public class TestExtractPdf {
    public static void main(String[] args) {
        try {
            String dirHasil = "D:/disertasi orang penting/OSD/hasil/";
            // 替换为你的PDF所有者密码字节数组
            byte[] ownerPassword = "你的PDF所有者密码".getBytes();
            PdfReader reader = new PdfReader("D:/disertasi orang penting/OSD/disertasi doktor OSD.pdf", ownerPassword);
            int n = reader.getNumberOfPages();
            System.out.println("Number of pages : " + n);
            
            for (int i = 0; i < n; i++) {
                int currentPage = i + 1;
                String outfile = dirHasil + currentPage + ".pdf";
                System.out.println("Writing " + outfile);
                Document document = new Document(reader.getPageSizeWithRotation(currentPage));
                PdfCopy copy = new PdfCopy(document, new FileOutputStream(outfile));
                document.open();
                PdfImportedPage page = copy.getImportedPage(reader, currentPage);
                copy.addPage(page);
                document.close();
                copy.close();
            }
            reader.close();
        } catch (Exception e) {
            System.out.println("error");
            e.printStackTrace();
        }
    }
}

注意事项

  • 请确保你对操作的PDF拥有合法的使用权限,禁止未经授权操作受版权保护的PDF文档,如果不知道所有者密码,请优先联系文档提供者获取。
  • 如果你确认自己对该PDF拥有合法操作权限但无法获取所有者密码,可以在构造PdfReader后添加一行代码PdfReader.unethicalreading = true; 跳过权限校验,该配置仅用于合法场景,请勿用于侵权操作。

内容的提问来源于stack exchange,提问作者Mohammad Fajar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.20 21:06:07