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

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

Introduction

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

Prototype

public int getNumberOfPages() 

Source Link

Document

Gets the number of pages in the document.

Usage

From source file:org.sonar.report.pdf.PDFReporter.java

License:Open Source License

public ByteArrayOutputStream getReport()
        throws DocumentException, IOException, org.dom4j.DocumentException, ReportException {
    // Creation of documents
    Document mainDocument = new Document(PageSize.A4, 50, 50, 110, 50);
    Toc tocDocument = new Toc();
    Document frontPageDocument = new Document(PageSize.A4, 50, 50, 110, 50);
    ByteArrayOutputStream mainDocumentBaos = new ByteArrayOutputStream();
    ByteArrayOutputStream frontPageDocumentBaos = new ByteArrayOutputStream();
    PdfWriter mainDocumentWriter = PdfWriter.getInstance(mainDocument, mainDocumentBaos);
    PdfWriter frontPageDocumentWriter = PdfWriter.getInstance(frontPageDocument, frontPageDocumentBaos);

    // Events for TOC, header and pages numbers
    Events events = new Events(tocDocument, new Header(this.getLogo(), this.getProject()));
    mainDocumentWriter.setPageEvent(events);

    mainDocument.open();/*www. j  a  v  a 2 s . co  m*/
    tocDocument.getTocDocument().open();
    frontPageDocument.open();

    Logger.info("Generating PDF report...");
    printFrontPage(frontPageDocument, frontPageDocumentWriter);
    printTocTitle(tocDocument);
    printPdfBody(mainDocument);
    mainDocument.close();
    tocDocument.getTocDocument().close();
    frontPageDocument.close();

    // Get Readers
    PdfReader mainDocumentReader = new PdfReader(mainDocumentBaos.toByteArray());
    PdfReader tocDocumentReader = new PdfReader(tocDocument.getTocOutputStream().toByteArray());
    PdfReader frontPageDocumentReader = new PdfReader(frontPageDocumentBaos.toByteArray());

    // New document
    Document documentWithToc = new Document(tocDocumentReader.getPageSizeWithRotation(1));
    ByteArrayOutputStream finalBaos = new ByteArrayOutputStream();
    PdfCopy copy = new PdfCopy(documentWithToc, finalBaos);

    documentWithToc.open();
    copy.addPage(copy.getImportedPage(frontPageDocumentReader, 1));
    for (int i = 1; i <= tocDocumentReader.getNumberOfPages(); i++) {
        copy.addPage(copy.getImportedPage(tocDocumentReader, i));
    }
    for (int i = 1; i <= mainDocumentReader.getNumberOfPages(); i++) {
        copy.addPage(copy.getImportedPage(mainDocumentReader, i));
    }
    documentWithToc.close();

    // Return the final document (with TOC)
    return finalBaos;
}

From source file:org.sonarqube.report.extendedpdf.OverviewPDFReporter.java

License:Open Source License

@Override
public ByteArrayOutputStream getReport()
        throws DocumentException, IOException, org.dom4j.DocumentException, ReportException {
    // Capture and save screenshots of the required widgets
    captureScreenshots();//  www .ja  v a  2s .  com

    // Creation of documents
    Document mainDocument = new Document(PageSize.LETTER, 50, 50, 75, 50);
    ExtendedToc tocDocument = new ExtendedToc();
    Document frontPageDocument = new Document(PageSize.LETTER, 50, 50, 75, 50);

    ByteArrayOutputStream mainDocumentBaos = new ByteArrayOutputStream();
    ByteArrayOutputStream frontPageDocumentBaos = new ByteArrayOutputStream();

    PdfWriter mainDocumentWriter = PdfWriter.getInstance(mainDocument, mainDocumentBaos);
    PdfWriter frontPageDocumentWriter = PdfWriter.getInstance(frontPageDocument, frontPageDocumentBaos);

    mainDocumentWriter.setStrictImageSequence(true);
    frontPageDocumentWriter.setStrictImageSequence(true);

    // Events for TOC, header and page numbers
    ExtendedEvents events = new ExtendedEvents(tocDocument, new ExtendedHeader(this.getProject()));
    mainDocumentWriter.setPageEvent(events);

    mainDocument.open();
    tocDocument.getTocDocument().open();
    frontPageDocument.open();

    Logger.info("Generating Overview PDF report...");
    printFrontPage(frontPageDocument, frontPageDocumentWriter);
    printTocTitle(tocDocument);
    printPdfBody(mainDocument);

    mainDocument.close();
    tocDocument.getTocDocument().close();
    frontPageDocument.close();

    // Get Readers
    PdfReader mainDocumentReader = new PdfReader(mainDocumentBaos.toByteArray());
    PdfReader tocDocumentReader = new PdfReader(tocDocument.getTocOutputStream().toByteArray());
    PdfReader frontPageDocumentReader = new PdfReader(frontPageDocumentBaos.toByteArray());

    // New document
    Document documentWithToc = new Document(tocDocumentReader.getPageSizeWithRotation(1));
    ByteArrayOutputStream finalBaos = new ByteArrayOutputStream();
    PdfCopy copy = new PdfCopy(documentWithToc, finalBaos);

    documentWithToc.open();
    copy.addPage(copy.getImportedPage(frontPageDocumentReader, 1));
    for (int i = 1; i <= tocDocumentReader.getNumberOfPages(); i++) {
        copy.addPage(copy.getImportedPage(tocDocumentReader, i));
    }
    for (int i = 1; i <= mainDocumentReader.getNumberOfPages(); i++) {
        copy.addPage(copy.getImportedPage(mainDocumentReader, i));
    }
    documentWithToc.close();

    // Return the final document (with TOC)
    return finalBaos;
}

From source file:org.squale.welcom.outils.pdf.advanced.WPdfDecoration.java

License:Open Source License

/**
 * Met a la decoration du document;/*from w  w  w  .  ja va 2 s  .c om*/
 * 
 * @param pdfReader le reader
 * @param out l'outputstream
 * @throws DocumentException exception pouvant etre levee
 * @throws IOException exception pouvant etre levee
 */
public void fill(final PdfReader pdfReader, final OutputStream out) throws DocumentException, IOException {
    final int n = pdfReader.getNumberOfPages();
    final PdfStamper stamp = new PdfStamper(pdfReader, out);
    for (int i = 1; i <= n; i++) {
        if (i >= startDecorationPage) {
            // PdfImportedPage page = stamp.getImportedPage (pdfReader, i);
            final PdfContentByte over = stamp.getOverContent(i);
            final Rectangle pageSize = pdfReader.getPageSizeWithRotation(i);

            if (header != null) {
                header.fill(over, pageSize, i, n);
            }

            if (footer != null) {
                footer.fill(over, pageSize, i, n);
            }

        }
    }
    stamp.close();
}

From source file:org.squale.welcom.outils.pdf.advanced.WPdfMerge.java

License:Open Source License

/**
 * merge/*from  w  w  w. j  a  v a2 s.  c o m*/
 * 
 * @return byte array rempli
 */
private byte[] merge() {
    final ByteArrayOutputStream tmpout = new ByteArrayOutputStream();
    int pageOffset = 0;
    int f = 0;
    Document document = null;
    final ArrayList master = new ArrayList();
    PdfCopy writer = null;

    final Iterator it = readers.iterator();

    while (it.hasNext()) {
        PdfReader reader = (PdfReader) it.next();

        try {
            // Renome tout les champs;
            reader = new PdfReader(renameFieldUnique(reader));

            reader.consolidateNamedDestinations();
            // we retrieve the total number of pages
            final int n = reader.getNumberOfPages();
            final List bookmarks = SimpleBookmark.getBookmark(reader);
            if (bookmarks != null) {
                if (pageOffset != 0) {
                    SimpleBookmark.shiftPageNumbers(bookmarks, pageOffset, null);
                }
                master.addAll(bookmarks);
            }
            pageOffset += n;

            if (f == 0) {
                // step 1: creation of a document-object
                document = new Document(reader.getPageSizeWithRotation(1));
                // step 2: we create a writer that listens to the document
                writer = new PdfCopy(document, tmpout);
                // step 3: we open the document
                document.open();
            }
            // step 4: we add content
            PdfImportedPage page;
            for (int i = 0; i < n;) {
                ++i;
                page = writer.getImportedPage(reader, i);
                writer.addPage(page);
            }
            final PRAcroForm form = reader.getAcroForm();
            if (form != null) {
                writer.copyAcroForm(reader);
            }
            f++;
            if (master.size() > 0) {
                writer.setOutlines(master);
            }
            // step 5: we close the document
            // document.close();

        } catch (final Exception e) {
            e.printStackTrace();
        }
    }
    if (document != null) {
        document.close();
    }
    return tmpout.toByteArray();
}

From source file:org.webpki.pdf.PDFSigner.java

License:Apache License

public byte[] addDocumentSignature(byte[] indoc, boolean certified) throws IOException {
    try {/* w ww. jav  a 2  s. c  o m*/
        PdfReader reader = new PdfReader(indoc);
        ByteArrayOutputStream bout = new ByteArrayOutputStream(8192);
        PdfStamper stp = PdfStamper.createSignature(reader, bout, '\0', null, true);

        for (Attachment file : attachments) {
            stp.addFileAttachment(file.description, file.data, "dummy", file.filename);
        }

        PdfSignatureAppearance sap = stp.getSignatureAppearance();
        sap.setCrypto(null, signer.getCertificatePath(), null, PdfSignatureAppearance.WINCER_SIGNED);

        if (reason != null) {
            sap.setReason(reason);
        }
        if (location != null) {
            sap.setLocation(location);
        }

        if (enable_signature_graphics) {
            sap.setVisibleSignature(new Rectangle(100, 100, 400, 130), reader.getNumberOfPages(), null);
        }

        sap.setCertified(certified);

        //           sap.setExternalDigest (new byte[128], new byte[20], "RSA");
        sap.setExternalDigest(new byte[512], new byte[20], "RSA");
        sap.preClose();
        MessageDigest messageDigest = MessageDigest.getInstance("SHA1");
        byte buf[] = new byte[8192];
        int n;
        InputStream inp = sap.getRangeStream();
        while ((n = inp.read(buf)) > 0) {
            messageDigest.update(buf, 0, n);
        }
        byte hash[] = messageDigest.digest();
        PdfSigGenericPKCS sg = sap.getSigStandard();
        PdfLiteral slit = (PdfLiteral) sg.get(PdfName.CONTENTS);
        byte[] outc = new byte[(slit.getPosLength() - 2) / 2];
        PdfPKCS7 sig = sg.getSigner();
        sig.setExternalDigest(signer.signData(hash, AsymSignatureAlgorithms.RSA_SHA1), hash, "RSA");
        PdfDictionary dic = new PdfDictionary();
        byte[] ssig = sig.getEncodedPKCS7();
        System.arraycopy(ssig, 0, outc, 0, ssig.length);
        dic.put(PdfName.CONTENTS, new PdfString(outc).setHexWriting(true));
        sap.close(dic);

        return bout.toByteArray();
    } catch (NoSuchAlgorithmException nsae) {
        throw new IOException(nsae.getMessage());
    } catch (DocumentException de) {
        throw new IOException(de.getMessage());
    }
}

From source file:oscar.dms.actions.AddEditDocumentAction.java

License:Open Source License

public int countNumOfPages(String fileName) {// count number of pages in a local pdf file

    int numOfPage = 0;
    //      String docdownload = oscar.OscarProperties.getInstance().getProperty("DOCUMENT_DIR");
    //      String filePath = docdownload + fileName;
    String filePath = EDocUtil.getDocumentPath(fileName);

    try {/*from  w  w w .j  av a  2 s. c  o  m*/
        PdfReader reader = new PdfReader(filePath);
        numOfPage = reader.getNumberOfPages();
        reader.close();

    } catch (IOException e) {
        MiscUtils.getLogger().error("Error", e);
    }
    return numOfPage;
}

From source file:oscar.dms.actions.DocumentUploadAction.java

License:Open Source License

/**
 * Counts the number of pages in a local pdf file.
 * @param fileName the name of the file//from  w w w.ja  v  a2  s.  c  o m
 * @return the number of pages in the file
 */
public int countNumOfPages(String fileName) {// count number of pages in a
    // local pdf file
    int numOfPage = 0;
    //      String docdownload = oscar.OscarProperties.getInstance().getProperty("DOCUMENT_DIR");
    //      String filePath = docdownload + fileName;
    String filePath = EDocUtil.getDocumentPath(fileName);

    try {
        PdfReader reader = new PdfReader(filePath);
        numOfPage = reader.getNumberOfPages();
        reader.close();
    } catch (IOException e) {
        logger.debug(e.toString());
    }
    return numOfPage;
}

From source file:oscar.eform.util.EFormPDFServlet.java

License:Open Source License

/**
 * the form txt file has lines in the form:
 *
 * For Checkboxes:/*w w w. j ava2s .c  o m*/
 * ie.  ohip : left, 76, 193, 0, BaseFont.ZAPFDINGBATS, 8, \u2713
 * requestParamName : alignment, Xcoord, Ycoord, 0, font, fontSize, textToPrint[if empty, prints the value of the request param]
 * NOTE: the Xcoord and Ycoord refer to the bottom-left corner of the element
 *
 * For single-line text:
 * ie. patientCity  : left, 242, 261, 0, BaseFont.HELVETICA, 12
 * See checkbox explanation
 *
 * For multi-line text (textarea)
 * ie.  aci : left, 20, 308, 0, BaseFont.HELVETICA, 8, _, 238, 222, 10
 * requestParamName : alignment, bottomLeftXcoord, bottomLeftYcoord, 0, font, fontSize, _, topRightXcoord, topRightYcoord, spacingBtwnLines
 *
 *NOTE: When working on these forms in linux, it helps to load the PDF file into gimp, switch to pt. coordinate system and use the mouse to find the coordinates.
 *Prepare to be bored!
 *
 *
 * @throws Exception 
 */
protected ByteArrayOutputStream generatePDFDocumentBytes(final HttpServletRequest req, final ServletContext ctx,
        int multiple) throws Exception {

    // added by vic, hsfo
    if (HSFO_RX_DATA_KEY.equals(req.getParameter("__title")))
        return generateHsfoRxPDF(req);

    String suffix = (multiple > 0) ? String.valueOf(multiple) : "";

    ByteArrayOutputStream baosPDF = new ByteArrayOutputStream();
    Document document = new Document();
    PdfWriter writer = null;
    try {
        writer = PdfWriter.getInstance(document, baosPDF);

        String title = req.getParameter("__title" + suffix) != null ? req.getParameter("__title" + suffix)
                : "Unknown";
        String template = req.getParameter("__template" + suffix) != null
                ? req.getParameter("__template" + suffix) + ".pdf"
                : "";

        int numPages = 1;
        String pages = req.getParameter("__numPages" + suffix);
        if (pages != null) {
            numPages = Integer.parseInt(pages);
        }

        //load config files
        Properties[] printCfg = loadPrintCfg(req, suffix);
        Properties[][] graphicCfg = loadGraphicCfg(req, suffix, numPages);
        int cfgFileNo = printCfg == null ? 0 : printCfg.length;

        Properties props = new Properties();
        getPrintPropValues(props, req, suffix);

        Properties measurements = new Properties();

        //initialise measurement collections = a list of pages sections measurements
        List<List<List<String>>> xMeasurementValues = new ArrayList<List<List<String>>>();
        List<List<List<String>>> yMeasurementValues = new ArrayList<List<List<String>>>();
        for (int idx = 0; idx < numPages; ++idx) {
            MiscUtils.getLogger().debug("Adding page " + idx);
            xMeasurementValues.add(new ArrayList<List<String>>());
            yMeasurementValues.add(new ArrayList<List<String>>());
        }

        saveMeasurementValues(measurements, props, req, numPages, xMeasurementValues, yMeasurementValues);
        addDocumentProps(document, title, props);

        // create a reader for a certain document
        String propFilename = OscarProperties.getInstance().getProperty("eform_image", "") + "/" + template;
        PdfReader reader = null;

        try {
            reader = new PdfReader(propFilename);
            log.debug("Found template at " + propFilename);
        } catch (Exception dex) {
            log.warn("Cannot find template at : " + propFilename);
        }

        // retrieve the total number of pages
        int n = reader.getNumberOfPages();
        // retrieve the size of the first page
        Rectangle pSize = reader.getPageSize(1);
        float height = pSize.getHeight();

        PdfContentByte cb = writer.getDirectContent();
        int i = 0;

        while (i < n) {
            document.newPage();

            i++;
            PdfImportedPage page1 = writer.getImportedPage(reader, i);
            cb.addTemplate(page1, 1, 0, 0, 1, 0, 0);

            cb.setRGBColorStroke(0, 0, 255);
            // LEFT/CENTER/RIGHT, X, Y,

            if (i <= cfgFileNo) {
                writeContent(printCfg[i - 1], props, measurements, height, cb);
            } //end if there are print properties

            //graphic
            Properties[] tempPropertiesArray;
            if (i <= graphicCfg.length) {
                tempPropertiesArray = graphicCfg[i - 1];
                MiscUtils.getLogger().debug("Plotting page " + i);
            } else {
                tempPropertiesArray = null;
                MiscUtils.getLogger().debug("Skipped Plotting page " + i);
            }

            //if there are properties to plot
            if (tempPropertiesArray != null) {
                MiscUtils.getLogger().debug("TEMP PROP LENGTH " + tempPropertiesArray.length);
                for (int k = 0; k < tempPropertiesArray.length; k++) {

                    //initialise with measurement values which are mapped to config file by form get graphic function
                    List<String> xDate, yHeight;
                    if (xMeasurementValues.get(i - 1).size() > k && yMeasurementValues.get(i - 1).size() > k) {
                        xDate = new ArrayList<String>(xMeasurementValues.get(i - 1).get(k));
                        yHeight = new ArrayList<String>(yMeasurementValues.get(i - 1).get(k));
                    } else {
                        xDate = new ArrayList<String>();
                        yHeight = new ArrayList<String>();
                    }
                    plotProperties(tempPropertiesArray[k], props, xDate, yHeight, height, cb, (k % 2 == 0));
                }
            } //end: if there are properties to plot
        }
    } finally {
        if (document.isOpen())
            document.close();
        if (writer != null)
            writer.close();
    }
    return baosPDF;
}

From source file:oscar.oscarLab.ca.all.upload.handlers.PDFHandler.java

License:Open Source License

@Override
public String parse(LoggedInInfo loggedInInfo, String serviceName, String fileName, int fileId, String ipAddr) {

    String providerNo = "-1";
    String filePath = fileName;/* ww  w .  j a v a2 s  . c  o  m*/
    if (!(fileName.endsWith(".pdf") || fileName.endsWith(".PDF"))) {
        logger.error("Document " + fileName + "does not have pdf extension");
        return null;
    } else {
        int fileNameIdx = fileName.lastIndexOf("/");
        fileName = fileName.substring(fileNameIdx + 1);
    }

    EDoc newDoc = new EDoc("", "", fileName, "", providerNo, providerNo, "", 'A',
            oscar.util.UtilDateUtilities.getToday("yyyy-MM-dd"), "", "", "demographic", "-1", false);

    newDoc.setDocPublic("0");

    InputStream fis = null;

    try {
        fis = new FileInputStream(filePath);
        newDoc.setContentType("application/pdf");

        //Find the number of pages
        PdfReader reader = new PdfReader(filePath);
        int numPages = reader.getNumberOfPages();
        reader.close();
        newDoc.setNumberOfPages(numPages);

        String doc_no = EDocUtil.addDocumentSQL(newDoc);

        LogAction.addLog(providerNo, LogConst.ADD, LogConst.CON_DOCUMENT, doc_no, ipAddr, "", "DocUpload");

        //Get provider to route document to
        String batchPDFProviderNo = OscarProperties.getInstance().getProperty("batch_pdf_provider_no");
        if ((batchPDFProviderNo != null) && !batchPDFProviderNo.isEmpty()) {

            ProviderInboxRoutingDao providerInboxRoutingDao = (ProviderInboxRoutingDao) SpringUtils
                    .getBean("providerInboxRoutingDAO");
            providerInboxRoutingDao.addToProviderInbox(batchPDFProviderNo, Integer.parseInt(doc_no), "DOC");

            //Add to default queue for now, not sure how or if any other queues can be used anyway (MAB)                 
            QueueDocumentLinkDao queueDocumentLinkDAO = (QueueDocumentLinkDao) SpringUtils
                    .getBean("queueDocumentLinkDAO");
            Integer did = Integer.parseInt(doc_no.trim());
            queueDocumentLinkDAO.addToQueueDocumentLink(1, did);
        }
    } catch (FileNotFoundException e) {
        logger.info("An unexpected error has occurred:" + e.toString());
        return null;
    } catch (Exception e) {
        logger.info("An unexpected error has occurred:" + e.toString());
        return null;
    } finally {
        try {
            if (fis != null) {
                fis.close();
            }
        } catch (IOException e1) {
            logger.info("An unexpected error has occurred:" + e1.toString());
            return null;
        }
    }

    return "success";
}

From source file:oscar.util.ConcatPDF.java

License:Open Source License

/**
 * This class can be used to concatenate existing PDF files.
 * (This was an example known as PdfCopy.java)
 * @param args the command line arguments
 *//*  w ww  .  j  a v a2s . c o  m*/
public static void concat(List<Object> alist, OutputStream out) {

    try {
        int pageOffset = 0;
        ArrayList master = new ArrayList();
        int f = 0;
        Document document = null;
        PdfCopy writer = null;
        boolean fileAsStream = false;
        PdfReader reader = null;
        String name = "";

        MiscUtils.getLogger().debug("Size of list = " + alist.size());

        while (f < alist.size()) {
            // we create a reader for a certain document
            Object o = alist.get(f);

            if (o instanceof InputStream) {
                name = "";
                fileAsStream = true;
            } else {
                name = (String) alist.get(f);
                fileAsStream = false;
            }

            if (fileAsStream) {
                reader = new PdfReader((InputStream) alist.get(f));
            } else {
                reader = new PdfReader(name);
            }

            reader.consolidateNamedDestinations();
            // we retrieve the total number of pages
            int n = reader.getNumberOfPages();
            List bookmarks = SimpleBookmark.getBookmark(reader);
            if (bookmarks != null) {
                if (pageOffset != 0)
                    SimpleBookmark.shiftPageNumbers(bookmarks, pageOffset, null);
                master.addAll(bookmarks);
            }
            pageOffset += n;
            MiscUtils.getLogger().debug("There are " + n + " pages in " + name);

            if (f == 0) {
                // step 1: creation of a document-object
                document = new Document(reader.getPageSizeWithRotation(1));
                // step 2: we create a writer that listens to the document
                writer = new PdfCopy(document, out);
                // step 3: we open the document
                document.open();
            }
            // step 4: we add content
            PdfImportedPage page;
            for (int i = 0; i < n;) {
                ++i;
                page = writer.getImportedPage(reader, i);
                writer.addPage(page);
                MiscUtils.getLogger().debug("Processed page " + i);
            }
            PRAcroForm form = reader.getAcroForm();
            if (form != null)
                writer.copyAcroForm(reader);
            f++;
        }
        if (master.size() > 0)
            writer.setOutlines(master);
        // step 5: we close the document
        document.close();
    } catch (Exception e) {
        MiscUtils.getLogger().error("Error", e);
    }
}