Example usage for com.itextpdf.text.pdf PdfReader getNumberOfPages

List of usage examples for com.itextpdf.text.pdf PdfReader getNumberOfPages

Introduction

In this page you can find the example usage for com.itextpdf.text.pdf PdfReader getNumberOfPages.

Prototype

public int getNumberOfPages() 

Source Link

Document

Gets the number of pages in the document.

Usage

From source file:org.jrimum.bopepo.excludes.PDFs.java

License:Apache License

public static Map<String, Collection<BufferedImage>> getImages(byte[] pdf) throws IOException {
    PdfReader reader = new PdfReader(pdf);
    PdfReaderContentParser parser = new PdfReaderContentParser(reader);
    ImageRenderListener listener = new ImageRenderListener();
    for (int i = 1; i <= reader.getNumberOfPages(); i++) {
        parser.processContent(i, listener);
    }//from   ww  w  .  j a v  a2  s.  c om
    reader.close();
    return listener.getImages();
}

From source file:org.karsha.document.PDFBookmark.java

License:Open Source License

public LinkedHashMap splitPDFByBookmarks(byte[] pdf) {
    try {//from   w  w w .  j a v a 2  s .  co m
        PdfReader reader = new PdfReader(pdf);
        //List of bookmarks: each bookmark is a map with values for title, page, etc
        List<HashMap<String, Object>> bookmarks = SimpleBookmark.getBookmark(reader);
        for (int i = 0; i < bookmarks.size(); i++) {
            HashMap bm = bookmarks.get(i);
            HashMap nextBM = i == bookmarks.size() - 1 ? null : bookmarks.get(i + 1);
            HashMap previBM;
            if (i == 0) {
                previBM = bookmarks.get(i);
            } else {
                previBM = bookmarks.get(i - 1);
            }

            //String title = ((String) bm.get("Title")).split(" ")[1]; //get only the up to 2nd word
            if ((String) bm.get("Title") != null && (String) bm.get("Page") != null) {

                String title = ((String) bm.get("Title"));
                // log.debug("Titel: " + title);

                //  System.out.println((String) bm.get("Page"));
                String startPage = ((String) bm.get("Page")).split(" ")[0];
                //String startPage = ((String) bm.get("Page"));
                String startPageNextBM = nextBM == null ? "" + (reader.getNumberOfPages() + 1)
                        : ((String) nextBM.get("Page")).split(" ")[0];
                //log.debug("Page: " + startPage);
                // log.debug("------------------");

                parsePdf(reader, title, ((String) previBM.get("Title")), Integer.valueOf(startPage),
                        Integer.valueOf(startPageNextBM));

                // extractBookmarkToPDF(reader, Integer.valueOf(startPage), Integer.valueOf(startPageNextBM), title + ".pdf", outputFolder);
            }
        }
    } catch (IOException e) {
        //log.error(e.getMessage());
    }
    return docsSeperated;
}

From source file:org.mortagne.budget.internal.transaction.io.lcl.pdf.LCLPDFTransactionReader.java

License:Open Source License

public void open() throws IOException {
    close();//  w w  w  .  j  av  a2s .c  o m

    List<DefaultTransaction> transactions = new ArrayList<DefaultTransaction>();

    // Parse transactions
    PdfReader reader = new PdfReader(this.transationStream);

    int nb = reader.getNumberOfPages();

    double currentTotal;
    try {
        LCLLocationTextExtractionStrategy strategy = parsePage(reader, 1, transactions, null);
        currentTotal = strategy.getPreviousTotal();

        for (int i = 2; i <= nb; ++i) {
            strategy = parsePage(reader, i, transactions, strategy.getLastType());
        }

    } finally {
        reader.close();
    }

    // Order transactions

    Collections.sort(transactions, new Comparator<DefaultTransaction>() {
        public int compare(DefaultTransaction t1, DefaultTransaction t2) {
            return t1.getRealDate().compareTo(t2.getRealDate());
        }
    });

    // Set total

    Date currentDate = null;
    for (DefaultTransaction transaction : transactions) {
        // total
        currentTotal += transaction.getValue();
        transaction.setTotal(currentTotal);

        // date
        if (!transaction.getRealDate().equals(currentDate)) {
            currentDate = transaction.getDate();
        }
    }

    // Iterator
    this.it = transactions.iterator();
}

From source file:org.pdfsam.pdf.DefaultITextLoader.java

License:Open Source License

public void accept(PdfReader reader, PdfDocumentDescriptor descriptor) {
    descriptor.pages(reader.getNumberOfPages());
    descriptor.setVersion(new PdfVersionAdapter(Character.toString(reader.getPdfVersion())).getEnumValue());
    Map<String, String> info = reader.getInfo();
    descriptor.setInformationDictionary(info);
    Optional.ofNullable(PdfDate.decode(info.get("CreationDate"))).map(FORMATTER::format)
            .ifPresent(c -> descriptor.putInformation("FormattedCreationDate", c));
}

From source file:org.pdfsam.pdf.ITextPdfLoadService.java

License:Open Source License

public void load(Collection<PdfDocumentDescriptor> toLoad) {
    LOG.debug(DefaultI18nContext.getInstance().i18n("Loading"));
    for (PdfDocumentDescriptor current : toLoad) {
        if (!current.isInvalid()) {
            LOG.trace("Loading {}", current.getFileName());
            PdfReader reader = null;
            try {
                current.moveStatusTo(LOADING);
                reader = current.toPdfFileSource().open(new DefaultPdfSourceOpener());
                current.setPages(reader.getNumberOfPages());
                current.setVersion(String.format("1.%c", reader.getPdfVersion()));
                current.setInformationDictionary(reader.getInfo());
                if (current.hasPassword()) {
                    current.moveStatusTo(LOADED_WITH_USER_PWD_DECRYPTION);
                } else {
                    current.moveStatusTo(LOADED);
                }/*  ww  w. j  a v a  2 s.  c o m*/
            } catch (TaskWrongPasswordException twpe) {
                current.moveStatusTo(ENCRYPTED);
                LOG.warn("User password required for '{}'", current.getFileName(), twpe);
            } catch (Exception e) {
                LOG.error("An error occured loading the document '{}'", current.getFileName(), e);
                current.moveStatusTo(WITH_ERRORS);
            } finally {
                try {
                    nullSafeClosePdfReader(reader);
                } catch (RuntimeException e) {
                    LOG.warn("An error occured closing the document", e);
                }
            }
        } else {
            LOG.trace("Skipping invalid document {}", current.getFileName());
        }
    }
    LOG.debug(DefaultI18nContext.getInstance().i18n("Documents loaded"));
}

From source file:org.sejda.impl.itext5.component.AbstractPdfCopier.java

License:Open Source License

public void addBlankPageIfOdd(PdfReader reader) throws TaskException {
    if (reader.getNumberOfPages() % 2 != 0) {
        addBlankPage(reader);/*from  w w  w .ja va  2  s. c  o m*/
    }
}

From source file:org.sejda.impl.itext5.component.AbstractPdfCopier.java

License:Open Source License

/**
 * Adds to the {@link PdfSmartCopy} all the pages from the input reader
 * //  w  w  w  . j  a  v  a2  s  . com
 * @param reader
 * @throws TaskException
 */
public void addAllPages(PdfReader reader) throws TaskException {
    try {
        pdfCopy.addDocument(reader);
    } catch (DocumentException e) {
        throw new TaskIOException("An IO error occurred adding pages to the PdfSmartCopy.", e);
    } catch (IOException e) {
        throw new TaskIOException("An IO error occurred adding pages to the PdfSmartCopy.", e);
    }
    numberOfCopiedPages += reader.getNumberOfPages();
}

From source file:org.sejda.impl.itext5.component.ITextOutlineSubsetProvider.java

License:Open Source License

public ITextOutlineSubsetProvider(PdfReader reader) {
    if (reader == null) {
        throw new IllegalArgumentException("Unable to retrieve bookmarks from a null reader.");
    }//ww w  . j a v a2  s . c  om

    this.totalNumberOfPages = reader.getNumberOfPages();
    this.bookmarks = getBookmarksOrEmpty(reader);
}

From source file:org.sejda.impl.itext5.component.PdfStamperHandler.java

License:Open Source License

/**
 * Enables compression if compress is true
 * //from w  w  w  .  ja  v  a  2  s  .  c  om
 * @param compress
 * @throws TaskException
 */
public void setCompression(boolean compress, PdfReader reader) throws TaskException {
    if (compress) {
        try {
            stamper.getWriter().setCompressionLevel(PdfStream.BEST_COMPRESSION);
            int total = reader.getNumberOfPages() + 1;
            for (int i = 1; i < total; i++) {
                reader.setPageContent(i, reader.getPageContent(i));
            }
            stamper.setFullCompression();
        } catch (DocumentException de) {
            throw new TaskException("Unable to set compression on stamper", de);
        } catch (IOException e) {
            throw new TaskException("Unable to set compression on stamper", e);
        }
    }
}

From source file:org.sejda.impl.itext5.component.PdfUnpacker.java

License:Open Source License

private Set<PdfDictionary> getFileAttachmentsDictionaries(PdfReader reader) {
    Set<PdfDictionary> retSet = new NullSafeSet<PdfDictionary>();
    for (int k = 1; k <= reader.getNumberOfPages(); ++k) {
        PdfArray annots = reader.getPageN(k).getAsArray(PdfName.ANNOTS);
        if (annots != null) {
            for (PdfObject current : annots) {
                PdfDictionary annot = (PdfDictionary) PdfReader.getPdfObject(current);
                if (PdfName.FILEATTACHMENT.equals(annot.getAsName(PdfName.SUBTYPE))) {
                    retSet.add(annot.getAsDict(PdfName.FS));
                }// www .ja  va2  s. c om
            }
        }
    }
    return retSet;
}