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

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

Introduction

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

Prototype

public PdfReader(PdfReader reader) 

Source Link

Document

Creates an independent duplicate.

Usage

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

License:Apache License

public void verifyDocumentSignature(byte[] indoc) throws IOException {
    try {/* ww w.ja va 2s. c o m*/
        PdfReader reader = new PdfReader(indoc);
        AcroFields af = reader.getAcroFields();
        ArrayList<?> names = af.getSignatureNames();
        for (int k = 0; k < names.size(); ++k) {
            String name = (String) names.get(k);
            whole_doc_signature = af.signatureCoversWholeDocument(name);
            if ((stop_on_index && k == stop_index) || (!stop_on_index && whole_doc_signature)) {
                signature_name = name;
                document_revision = af.getRevision(name);
                ByteArrayOutputStream bout = new ByteArrayOutputStream(8192);
                byte buffer[] = new byte[8192];
                InputStream ip = af.extractRevision(name);
                int n = 0;
                while ((n = ip.read(buffer)) > 0) {
                    bout.write(buffer, 0, n);
                }
                bout.close();
                ip.close();
                file_data = bout.toByteArray();
                PdfPKCS7 pk = af.verifySignature(name);
                signing_time = pk.getSignDate().getTime();
                X509Certificate pkc[] = (X509Certificate[]) pk.getCertificates();
                is_modified = !pk.verify();
                X509Certificate cert = pk.getSigningCertificate();
                for (int q = 0; q < pkc.length; q++) {
                    if (cert.equals(pkc[q])) {
                        verifier.verifyCertificatePath(CertificateUtil.getSortedPath(pkc));
                        return;
                    }
                }
                throw new IOException("Signature certificate not found in path");
            }
        }
        if (stop_on_index) {
            throw new IOException("Signature with index " + stop_index + " not found");
        }
        throw new IOException("No whole-document signature found");
    } catch (GeneralSecurityException gse) {
        throw new IOException(gse.getMessage());
    }
}

From source file:org.xhtmlrenderer.pdf.ITextOutputDevice.java

License:Open Source License

public PdfReader getReader(URI uri) throws IOException {
    PdfReader result = (PdfReader) _readerCache.get(uri);
    if (result == null) {
        result = new PdfReader(getSharedContext().getUserAgentCallback().getBinaryResource(uri.toString()));
        _readerCache.put(uri, result);/*from w  ww  .  j  a  va2 s . c  o m*/
    }
    return result;
}

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 {/*w  w  w.j av a  2  s .  com*/
        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/*w w w .  ja  v a 2  s.co  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://from   w w w . ja  va2  s  .co  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.form.pharmaForms.formBPMH.pdf.PDFController.java

License:Open Source License

private void setReader(PdfReader reader) {

    try {//w  w w  . ja va2 s.c  om
        if (reader == null) {
            this.pdfreader = new PdfReader(filePath.getAbsolutePath());
        } else {
            this.pdfreader = reader;
        }
    } catch (IOException e) {
        _Logger.log(Level.FATAL, null, e);
    }

}

From source file:oscar.oscarEncounter.oscarConsultationRequest.pageUtil.EctConsultationFormRequestPrintPdf.java

License:Open Source License

public void printPdf() throws IOException, DocumentException {

    EctConsultationFormRequestUtil reqForm = new EctConsultationFormRequestUtil();
    reqForm.estRequestFromId((String) request.getAttribute("reqId"));

    //make sure we have data to print
    if (reqForm == null)
        throw new DocumentException();

    // init req form info
    reqForm.specAddr = request.getParameter("address");
    if (reqForm.specAddr == null) {
        reqForm.specAddr = new String();
    }/* w w w.  ja v a2  s .c om*/
    reqForm.specPhone = request.getParameter("phone");
    if (reqForm.specPhone == null) {
        reqForm.specPhone = "";
    }
    reqForm.specFax = request.getParameter("fax");
    if (reqForm.specFax == null) {
        reqForm.specFax = "";
    }

    //Create new file to save form to
    String path = OscarProperties.getInstance().getProperty("DOCUMENT_DIR");
    String fileName = path + "ConsultationRequestForm-" + UtilDateUtilities.getToday("yyyy-MM-dd.hh.mm.ss")
            + ".pdf";
    FileOutputStream out = new FileOutputStream(fileName);

    //Create the document we are going to write to
    document = new Document();
    writer = PdfWriter.getInstance(document, out);

    //Use the template located at '/oscar/oscarEncounter/oscarConsultationRequest/props'
    reader = new PdfReader("/oscar/oscarEncounter/oscarConsultationRequest/props/consultationFormRequest.pdf");
    Rectangle pSize = reader.getPageSize(1);
    width = pSize.getWidth();
    height = pSize.getHeight();
    document.setPageSize(pSize);

    document.addTitle("Consultation Form Request");
    document.addCreator("OSCAR");
    document.open();

    //Create the font we are going to print to
    bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);

    cb = writer.getDirectContent();
    ct = new ColumnText(cb);
    cb.setColorStroke(new Color(0, 0, 0));

    // start writing the pdf document
    PdfImportedPage page1 = writer.getImportedPage(reader, 1);
    cb.addTemplate(page1, 1, 0, 0, 1, 0, 0);
    addFooter();
    setAppointmentInfo(reqForm);

    // add the dynamically positioned text elements
    float dynamicHeight = 0;
    dynamicHeight = addDynamicPositionedText("Reason For Consultation: ", reqForm.reasonForConsultation,
            dynamicHeight, reqForm);
    dynamicHeight = addDynamicPositionedText("Pertinent Clinical Information: ", reqForm.clinicalInformation,
            dynamicHeight, reqForm);
    dynamicHeight = addDynamicPositionedText("Significant Concurrent Problems: ", reqForm.concurrentProblems,
            dynamicHeight, reqForm);
    dynamicHeight = addDynamicPositionedText("Current Medications: ", reqForm.currentMedications, dynamicHeight,
            reqForm);
    dynamicHeight = addDynamicPositionedText("Allergies: ", reqForm.allergies, dynamicHeight, reqForm);

    document.close();
    reader.close();
    writer.close();
    out.close();

    // combine the recently created pdf with any pdfs that were added to the consultation request form
    combinePDFs(fileName);

}

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;//from  w  w  w  . jav  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
 *///from  www  .  ja v a2  s  .  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);
    }
}

From source file:papertoolkit.paper.bundles.PDFBundle.java

License:BSD License

/**
 * Reads the PDF file. For each page, create a new PDFSheet referencing that page. Add that
 * sheet to this bundle.//from   ww w  .j  a  v a  2  s.c  o  m
 */
private void addPDFSheetsFromFile() {
    try {
        final PdfReader reader = new PdfReader(new FileInputStream(file));
        numSheets = reader.getNumberOfPages();
        reader.close();
        for (int i = 0; i < numSheets; i++) {
            // (i+1) because Page Numbers start from 1
            addSheets(new PDFSheet(file, i + 1));
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}