从PDF文件中提取页码

时间:2013-05-31 10:00:58

标签: java pdf itext

我有一个PDF文档,可能是通过从另一个PDF文档中提取少量页面而创建的。我想知道如何获取页码。由于起始页码为572,因此完整的PDF文档应为1.

您认为将PDF转换为XMl会对此问题进行排序吗?

2 个答案:

答案 0 :(得分:1)

该文档很可能包含/PageLabels中的Document Catalog条目。此条目也指定页码的编号样式和起始编号。

您可能需要更新起始编号或完全删除该条目。以下文档包含有关/PageLabels条目的更多信息:

如果您决定更新条目,文档中的示例2可能会有用。

答案 1 :(得分:1)

最后用iText弄明白了。如果没有Bovrosky的暗示,那是不可能的。非常感谢他。发布代码示例:

public void process(PdfReader reader) {
    PRIndirectReference obj = (PRIndirectReference) dict.get(com.itextpdf.text.pdf.PdfName.PAGELABELS);
    System.out.println(obj.getNumber());
    PdfObject ref = reader.getPdfObject(obj.getNumber());
    PdfArray array = (PdfArray)((PdfDictionary) ref).get(com.itextpdf.text.pdf.PdfName.NUMS);
    System.out.println("Start Page: " + resolvePdfIndirectReference(array, reader));
}

private static int resolvePdfIndirectReference(PdfObject obj, PdfReader reader) {
    if (obj instanceof PdfArray) {
        PdfDictionary subDict = null;
        PdfIndirectReference indRef = null;
        ListIterator < PdfObject > itr = ((PdfArray) obj).listIterator();
        while (itr.hasNext()) {
            PdfObject pdfObj = itr.next();
            if (pdfObj instanceof PdfIndirectReference)
                indRef = (PdfIndirectReference) pdfObj;
            if (pdfObj instanceof PdfDictionary) {
                subDict = (PdfDictionary) pdfObj;
                break;
            }
        }
        if (subDict != null) {
            return resolvePdfIndirectReference(subDict, reader);
        } else if (indRef != null)
            return resolvePdfIndirectReference(indRef, reader);
    } else if (obj instanceof PdfIndirectReference) {
        PdfObject ref = reader.getPdfObject(((PdfIndirectReference) obj).getNumber());
        return resolvePdfIndirectReference(ref, reader);
    } else if (obj instanceof PdfDictionary) {
        PdfNumber num = (PdfNumber)((PdfDictionary) obj).get(com.itextpdf.text.pdf.PdfName.ST);
        return num.intValue();
    }
    return 0;
}