
iText 7 本身未提供类似 PDFBox 的 getSignedContent() 方法,但可通过解析签名字段的 /ByteRange 属性,结合随机读取文件视图,精准提取被签名覆盖前的原始字节序列(即签名域占位区之外的完整 PDF 内容)。
itext 7 本身未提供类似 pdfbox 的 `getsignedcontent()` 方法,但可通过解析签名字段的 `/byterange` 属性,结合随机读取文件视图,精准提取被签名覆盖前的原始字节序列(即签名域占位区之外的完整 pdf 内容)。
在数字签名验证或自定义签名流程中,获取 PDF 的“已签名内容”(signed content)至关重要——它并非原始 PDF 文件,也不是签名前的完整文件,而是根据 /ByteRange 字段排除签名值占位区域后、由剩余字节拼接而成的确定性字节流。该字节流正是签名算法(如 SHA256)实际计算摘要的对象。
iText 7 中,PdfSignature 对象可通过 getByteRange() 获取一个三元 PdfArray,其格式为 [0, offset1, offset2, length],表示签名覆盖范围:第一段从字节 0 到 offset1-1,第二段从 offset2 开始、长度为 length。中间被跳过的区间(即 offset1 到 offset2-1)正是签名值(/Contents)将被写入的位置,因此需被排除。
以下是一个安全、高效的提取示例(适用于 iText 7.2+):
import com.itextpdf.kernel.pdf.*;
import com.itextpdf.kernel.pdf.filespec.PdfFileSpec;
import com.itextpdf.kernel.utils.RandomAccessSourceFactory;
import com.itextpdf.kernel.utils.RASInputStream;
import java.io.*;
import java.util.Arrays;
public byte[] extractSignedContent(PdfDocument pdfDoc, PdfSignature signature) throws IOException {
PdfArray byteRange = signature.getByteRange();
if (byteRange == null || byteRange.size() != 4) {
throw new IllegalArgumentException("Invalid or missing /ByteRange in signature");
}
long[] range = byteRange.toLongArray();
// range[0] = 0, range[1] = first segment end, range[2] = second segment start, range[3] = second segment length
PdfReader reader = pdfDoc.getReader();
RandomAccessFileOrArray raf = reader.getSafeFile();
try (ByteArrayOutputStream baos = new ByteArrayOutputStream();
InputStream rangedStream = new RASInputStream(
new RandomAccessSourceFactory().createRanged(
raf.createSourceView(), range))) {
byte[] buf = new byte[8192];
int n;
while ((n = rangedStream.read(buf)) != -1) {
baos.write(buf, 0, n);
}
return baos.toByteArray();
}
}
✅ 关键说明与注意事项:
- 必须使用
reader.getSafeFile()获取底层文件句柄,确保支持随机访问;若 PDF 来源于内存流(如new PdfReader(new ByteArrayInputStream(...))),需提前将其持久化为临时文件或使用RandomAccessSource的内存实现(如new RandomAccessSourceFactory().createSource(new ByteArrayInputStream(...)))。 -
/ByteRange是 PDF 签名标准强制字段,但仅对 已签名 的文档有效;未签名或签名损坏的文档中该字段可能缺失或无效。 - 提取结果为原始二进制字节(非 Base64、非 DER),可直接用于哈希计算(例如
MessageDigest.getInstance("SHA-256").digest(extractedBytes))以验证签名有效性。 - 不建议直接修改或重写该字节流——它仅用于验证目的;任何变更都将导致签名失效。
综上,虽然 iText 7 没有开箱即用的 getSignedContent(),但通过合理组合 PdfSignature.getByteRange() 与 RandomAccessSourceFactory.createRanged(),即可可靠、高效地还原出签名所依据的原始内容字节,满足合规性验证、签名调试及高级签名集成等核心需求。











