How to get number of pages of Portable Collection

2019-09-21 16:00发布

问题:

PdfReader reader = new PdfReader(pdfFile, new byte[0]);
pages = reader.getNumberOfPages();

Suppose there are two pdfs(Each pdf contains 2 pages) inside portable collection. When i try to get number of pages it returns just 1. I think it is considering cover page of the portable collection document. Is there any way to get number of pages of portable colletion ? I am using Java 11 and IText 5.5 version.

回答1:

I found solution for this but i think it is unnecessary to check the below things and solution is not a efficient way of getting the total pdf page numbers.

private int getNumberOfPages(PdfReader reader) {
            int pages = 0;
            PdfObject obj;
            for (int i = 1; i <= reader.getXrefSize(); i++) {
                obj = reader.getPdfObject(i);
                if (obj != null && obj.isStream()) {
                    PRStream stream = (PRStream)obj;
                    byte[] b;
                    try {
                        b = PdfReader.getStreamBytes(stream);
                        PdfReader pdfReader = new PdfReader(b);
                        pages += pdfReader.getNumberOfPages();
                    } catch(InvalidPdfException e) {

                    } catch (IOException e) {

                    }

                }
            }
            if (pages == 0) {
                pages = reader.getNumberOfPages();
            }
            return pages;
        }


标签: java pdf itext