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

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

Introduction

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

Prototype

public void close() 

Source Link

Document

Closes the reader

Usage

From source file:org.lucee.extension.pdf.tag.PDF.java

License:Open Source License

private void doActionSetInfo() throws PageException, IOException, DocumentException {
    required("pdf", "setInfo", "info", info);
    required("pdf", "getInfo", "source", source);

    PDFStruct doc = toPDFDocument(source, password, null);
    PdfReader pr = doc.getPdfReader();
    OutputStream os = null;//from  w ww. jav  a2s  .c om
    try {
        if (destination == null) {
            if (doc.getResource() == null)
                throw engine.getExceptionUtil().createApplicationException(
                        "source is not based on a resource, destination file is required");
            destination = doc.getResource();
        } else if (destination.exists() && !overwrite)
            throw engine.getExceptionUtil()
                    .createApplicationException("destination file [" + destination + "] already exists");

        PdfStamper stamp = new PdfStamper(pr, os = destination.getOutputStream());
        HashMap moreInfo = new HashMap();

        // Key[] keys = info.keys();
        Iterator<Entry<Key, Object>> it = info.entryIterator();
        Entry<Key, Object> e;
        while (it.hasNext()) {
            e = it.next();
            moreInfo.put(engine.getStringUtil().ucFirst(e.getKey().getLowerString()),
                    engine.getCastUtil().toString(e.getValue()));
        }
        // author
        Object value = info.get("author", null);
        if (value != null)
            moreInfo.put("Author", engine.getCastUtil().toString(value));
        // keywords
        value = info.get("keywords", null);
        if (value != null)
            moreInfo.put("Keywords", engine.getCastUtil().toString(value));
        // title
        value = info.get("title", null);
        if (value != null)
            moreInfo.put("Title", engine.getCastUtil().toString(value));
        // subject
        value = info.get("subject", null);
        if (value != null)
            moreInfo.put("Subject", engine.getCastUtil().toString(value));
        // creator
        value = info.get("creator", null);
        if (value != null)
            moreInfo.put("Creator", engine.getCastUtil().toString(value));
        // trapped
        value = info.get("Trapped", null);
        if (value != null)
            moreInfo.put("Trapped", engine.getCastUtil().toString(value));
        // Created
        value = info.get("Created", null);
        if (value != null)
            moreInfo.put("Created", engine.getCastUtil().toString(value));
        // Language
        value = info.get("Language", null);
        if (value != null)
            moreInfo.put("Language", engine.getCastUtil().toString(value));

        stamp.setMoreInfo(moreInfo);
        stamp.close();

    } finally {
        Util.closeEL(os);
        pr.close();
    }
}

From source file:org.mnsoft.pdfocr.CreatorSetter.java

License:Open Source License

/**
 * @param args/*from  w ww . ja  v a2 s  .  c o m*/
 * @throws DocumentException
 * @throws IOException
 * @throws IOException
 * @throws BadPdfFormatException
 */
@SuppressWarnings("rawtypes")
public static void main(String[] args) throws DocumentException, IOException {
    /*
     * Verify arguments
     */
    if ((args == null) || (args.length < 2)) {
        System.err.println("Usage: first parameter: Creator to set, following parameters: Files to work on.");
        System.exit(1);
    }

    final String creator = args[0];

    for (int i = 1; i < args.length; i++) {
        final File f = new File(args[i]);

        if ((f == null) || !f.exists() || !f.isFile() || !f.getName().endsWith(".pdf")) {
            System.err.println("! ERROR: Could not read " + args[i] + " or this is not a .pdf");

            continue;
        }

        final String p = f.getAbsolutePath();

        /*
         * Open the reader
         */
        PdfReader reader;

        try {
            reader = new PdfReader(p);
        } catch (Exception e) {
            System.err.println("! ERROR: " + e.getMessage() + " File: " + p);

            continue;
        }

        /*
         * Get the document information
         */
        Map info = reader.getInfo();

        /*
         * Get the document creator. If the document
         * has already been worked on, continue with
         * the next document.
         */
        String doc_creator = (String) info.get("Creator");

        if (creator.equals(doc_creator)) {
            System.out.println("+ INFO: File " + p + " had already the right creator.");

            continue;
        }

        /*
         * Get the document time stamp so that we can set it later.
         */
        final Date doc_timestamp = new Date(f.lastModified());

        /*
         * Get the number of pages in the original file
         */
        int nOri = reader.getNumberOfPages();

        System.out.print("+ INFO: Working on: " + p + " (" + nOri + " pages) ... ");

        /*
         * Get the remaining meta data
         */
        String doc_title = ((String) info.get("Title") == null) ? "" : (String) info.get("Title");
        String doc_subject = ((String) info.get("Subject") == null) ? "" : (String) info.get("Subject");
        String doc_keywords = ((String) info.get("Keywords") == null) ? "" : (String) info.get("Keywords");
        String doc_author = ((String) info.get("Author") == null) ? "" : (String) info.get("Author");

        reader.close();

        /*
         * Set the creator to our marker
         */
        doc_creator = creator;

        /*
         * Merge the new document with the meta
         * data from the original document
         */
        try {
            reader = new PdfReader(p);
        } catch (Exception e) {
            System.err.println("! ERROR: " + e.getMessage() + " File: " + p);

            continue;
        }

        /*
         * Get the document information
         */
        info = reader.getInfo();

        /*
         * Get the document creator. If the document
         * has already been worked on, we assume we
         * have had a successful output from the OCR
         * engine
         */
        String doc_creator_copy = (String) info.get("Creator");

        if (creator.equals(doc_creator_copy)) {
            System.out.println();

            continue;
        }

        /*
         * Step 1: creation of a document object
         */
        final Document document = new Document(reader.getPageSizeWithRotation(1));

        /*
         * Step 2: we create a writer that listens to the document
         */
        PdfCopy writer = new PdfCopy(document, new FileOutputStream(p + ".tmp"));

        /*
         * Step 3: we add the meta data
         */
        document.addTitle(doc_title);
        document.addSubject(doc_subject);
        document.addKeywords(doc_keywords);
        document.addCreator(creator);
        document.addAuthor(doc_author);

        /*
         * Step 4: we open the document
         */
        document.open();

        PdfImportedPage page;

        int j = 0;

        /*
         * Step 5: we add content
         */
        while (j < nOri) {
            j++;
            page = writer.getImportedPage(reader, j);
            writer.addPage(page);

            System.out.print("[" + j + "] ");
        }

        PRAcroForm form = reader.getAcroForm();
        if (form != null) {
            writer.copyAcroForm(reader);
        }

        System.out.println();

        /*
         * Step 6: we close the document
         */
        document.close();
        reader.close();

        /*
         * Set the file access time and
         * rename the file.
         */
        File file = new File(p + ".tmp");

        if (file.exists()) {
            deleteFile(p);
            file.setLastModified(doc_timestamp.getTime());
            file.renameTo(new File(p));
        }
    }
}

From source file:org.mnsoft.pdfocr.Wrapper.java

License:Open Source License

/**
 * Run the Wrapper.//  w  w  w  .ja va 2  s. co m
 *
 * @throws IOException
 * @throws InterruptedException
 * @throws DocumentException
 */
@SuppressWarnings("rawtypes")
public void run() throws IOException, InterruptedException, DocumentException {
    RecursiveFileListIterator it = new RecursiveFileListIterator(new File(wd), new FileFilter(".pdf"));

    while (it.hasNext()) {
        final File originalFile = it.next();
        final String originalFilePath = originalFile.getAbsolutePath();

        /*
         * Open the reader on the original File
         */
        PdfReader readerOnOriginalFile;

        try {
            readerOnOriginalFile = new PdfReader(originalFilePath);
        } catch (Exception e) {
            log.error("! ERROR: " + e.getMessage() + " File: " + originalFilePath);

            continue;
        }

        /*
         * Get the document information
         */
        Map info = readerOnOriginalFile.getInfo();

        /*
         * Get the document creator. If the document
         * has already been worked on, continue with
         * the next document.
         */
        String doc_creator = (String) info.get("Creator");

        if (this.OCR_CREATOR.equals(doc_creator)) {
            log.debug(
                    "+ INFO: File " + originalFilePath + " had already been run trough OCR engine. Skipping.");

            continue;
        }

        /*
         * Get the document time stamp so that we can set it later.
         */
        final Date doc_timestamp = new Date(originalFile.lastModified());

        /*
         * Get the number of pages in the original file
         */
        int nOri = readerOnOriginalFile.getNumberOfPages();

        log.debug("+ Working on: " + originalFilePath + " (" + nOri + " pages).");

        final StringBuffer sb = new StringBuffer();

        sb.append(originalFilePath + " ... ");

        /*
         * Get the remaining meta data
         */
        String doc_title = ((String) info.get("Title") == null) ? "" : (String) info.get("Title");
        String doc_subject = ((String) info.get("Subject") == null) ? "" : (String) info.get("Subject");
        String doc_keywords = ((String) info.get("Keywords") == null) ? "" : (String) info.get("Keywords");
        String doc_author = ((String) info.get("Author") == null) ? "" : (String) info.get("Author");

        readerOnOriginalFile.close();

        /*
         * Set the creator to our marker
         */
        doc_creator = this.OCR_CREATOR;

        /*
         * Run the OCR Engine
         */
        File outputFileFromOCR = null;
        try {
            outputFileFromOCR = ocr(originalFile);
        } catch (Exception e) {
            log.error("! ERROR: " + e.getMessage());

            continue;
        }

        /*
         * Check for the result of the OCR Engine
         */
        if ((outputFileFromOCR == null) || !outputFileFromOCR.exists()) {
            continue;
        }

        log.debug("+ " + outputFileFromOCR.getAbsolutePath() + " has come out of the OCR engine.");

        /*
         * Create final output
         */

        /*
         * Create a temporary file and copy the source
         * file to it, to avoid UTF-8 encoding problems
         * on the filename confusing the OCR engine
         */
        final File temp = File.createTempFile("ocr", ".pdf", new File(this.TMP_DIR));
        temp.deleteOnExit();

        mergePDFs(originalFile, outputFileFromOCR, temp, doc_title, doc_subject, doc_keywords, doc_author,
                doc_creator);

        FileUtils.deleteQuietly(originalFile);

        FileUtils.moveFile(temp, new File(originalFilePath));

        /*
         * Set the file access time
         */
        if ("true".equals(getAttribute("KEEPTS"))) {
            if (originalFile.exists()) {
                originalFile.setLastModified(doc_timestamp.getTime() + 1000);
            }
        }

        /*
         * Finally, remove the temporary document
         */
        FileUtils.deleteQuietly(temp);
        FileUtils.deleteQuietly(outputFileFromOCR);
    }
}

From source file:org.obiba.onyx.marble.core.service.FdfProducer.java

License:Open Source License

/**
 * Builds a FDF file that can be used to merge with the a consent PDF template.
 * /* w w w  .j ava 2s.co m*/
 * @param pdfUrl the URL of the PDF file
 * @param acceptUrl the URL to submit the PDF when the consent is accepted
 * @param refuseUrl the URL to submit the PDF when the consent is refused
 * @return a FDF formated byte array.
 * @throws IOException when an unexpected error occurs
 */
public byte[] buildFdf(String pdfUrl, String acceptUrl, String refuseUrl) throws IOException {

    buildReplaceContext(acceptUrl, refuseUrl);

    PdfReader pdfReader = new PdfReader(getPdfTemplate());
    log.debug("PDF template has {} fields.", pdfReader.getAcroFields().getFields().size());

    CustomFdfWriter fdf = new CustomFdfWriter();
    // Initialize the FDF with fields that already have a value.
    fdf.setFields(pdfReader);
    fdf.setFile(pdfUrl);

    try {
        setFields(pdfReader.getAcroFields(), fdf);
    } catch (DocumentException e) {
        log.error("An error occurred during FDF file generation.", e);
        throw new RuntimeException(e);
    }

    ByteArrayOutputStream output = new ByteArrayOutputStream();
    fdf.writeTo(output);
    output.close();
    pdfReader.close();

    return output.toByteArray();
}

From source file:org.obiba.onyx.print.impl.DefaultPdfTemplateEngine.java

License:Open Source License

public InputStream applyTemplate(Locale locale, Map<String, String> fieldToVariableMap,
        LocalizedResourceLoader reportTemplateLoader, ActiveInterviewService activeInterviewService) {

    // Get report template
    Resource resource = reportTemplateLoader.getLocalizedResource(locale);

    // Read report template
    PdfReader pdfReader;
    try {/*from   w  w w.  j  a v a  2  s  .c om*/
        pdfReader = new PdfReader(resource.getInputStream());
    } catch (Exception ex) {
        throw new RuntimeException("Report to participant template cannot be read", ex);
    }

    ByteArrayOutputStream output = new ByteArrayOutputStream();
    PdfStamper stamper = null;

    // Set the values in the report data fields
    try {
        stamper = new PdfStamper(pdfReader, output);
        stamper.setFormFlattening(true);

        AcroFields form = stamper.getAcroFields();
        Participant participant = activeInterviewService.getParticipant();

        setVariableDataFields(participant, form, fieldToVariableMap, locale);
        setAdditionalDataFields(form);

    } catch (Exception ex) {
        throw new RuntimeException("An error occured while preparing the report to participant", ex);
    } finally {
        try {
            stamper.close();
        } catch (Exception e) {
            log.warn("Could not close PdfStamper", e);
        }
        try {
            output.close();
        } catch (IOException e) {
            log.warn("Could not close OutputStream", e);
        }
        pdfReader.close();
    }

    return new ByteArrayInputStream(output.toByteArray());
}

From source file:org.openconcerto.erp.core.finance.accounting.report.PdfGenerator.java

License:Open Source License

private void init() throws FileNotFoundException {

    // we create a reader for a certain document
    PdfReader reader = null;
    PdfWriter writer = null;//from  w  w w  .j ava 2s  .c om
    try {
        reader = new PdfReader(getStreamStatic(this.fileNameIn));

        // we retrieve the total number of pages
        int n = reader.getNumberOfPages();
        // we retrieve the size of the first page
        Rectangle psize = reader.getPageSize(1);

        psize.setRight(psize.getRight() - this.templateOffsetX);
        psize.setTop(psize.getTop() - this.templateOffsetY);

        this.width = (int) psize.getWidth();
        float height = psize.getHeight();

        // step 1: creation of a document-object
        int MARGIN = 32;
        this.document = new Document(psize, MARGIN, MARGIN, MARGIN, MARGIN);
        // step 2: we create a writer that listens to the document
        if (!this.directoryOut.exists()) {
            this.directoryOut.mkdirs();
        }
        System.err.println("Directory out " + this.directoryOut.getAbsolutePath());
        File f = new File(this.directoryOut, this.fileNameOut);
        if (f.exists()) {
            f.renameTo(new File(this.directoryOut, "Old" + this.fileNameOut));
            f = new File(this.directoryOut, this.fileNameOut);
        }

        System.err.println("Creation du fichier " + f.getAbsolutePath());

        writer = PdfWriter.getInstance(this.document, new FileOutputStream(f));

        this.document.open();
        // step 4: we add content
        this.cb = writer.getDirectContent();

        System.out.println("There are " + n + " pages in the document.");

        this.document.newPage();

        PdfImportedPage page1 = writer.getImportedPage(reader, 1);

        this.cb.addTemplate(page1, -this.templateOffsetX, -this.templateOffsetY);

        this.bf = BaseFont.createFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, BaseFont.EMBEDDED);
        this.bfb = BaseFont.createFont(BaseFont.TIMES_BOLD, BaseFont.CP1252, BaseFont.EMBEDDED);

    } catch (FileNotFoundException fE) {
        throw fE;
    } catch (IOException e) {
        e.printStackTrace();
    } catch (DocumentException e) {
        e.printStackTrace();
    } finally {
        if (reader != null) {
            reader.close();
        }
    }
}

From source file:org.openelis.bean.WorksheetPrintReportBean.java

License:Open Source License

private Path fillPDFWorksheet(Integer worksheetId, String templateName, String userName) throws Exception {
    int i, j, formCapacity, diagramCapacity, pageNumber;
    AcroFields form;//from w w  w .j  av a  2  s .c o m
    AnalysisViewDO aVDO;
    ArrayList<AnalysisQaEventViewDO> aqeVDOs;
    ArrayList<Integer> analysisIds, qcLotIds;
    ArrayList<NoteViewDO> nVDOs;
    ArrayList<QcAnalyteViewDO> qaVDOs;
    ArrayList<QcLotViewDO> qlVDOs;
    ArrayList<SampleManager1> sMans;
    ArrayList<SampleOrganizationViewDO> sOrgs;
    ArrayList<SampleQaEventViewDO> sqeVDOs;
    ArrayList<SystemVariableDO> sysVars;
    ArrayList<WorksheetAnalysisViewDO> waVDOs;
    ByteArrayOutputStream page;
    Document doc;
    HashMap<Integer, ArrayList<QcAnalyteViewDO>> qaVDOMap;
    HashMap<Integer, ArrayList<WorksheetAnalysisViewDO>> waVDOMap;
    HashMap<Integer, QcLotViewDO> qlMap;
    HashMap<Integer, SampleManager1> sMap;
    OutputStream out;
    Path path;
    PatientDO patDO;
    PdfCopy writer;
    PdfReader reader;
    PdfStamper stamper;
    ProviderDO proDO;
    QcLotViewDO qlVDO;
    RandomAccessFileOrArray original;
    SampleEnvironmentalDO seDO;
    SampleDO sDO;
    SampleItemViewDO siVDO;
    SampleManager1 sMan;
    String collectionDateTime, dirName, now, qcLink;
    StringBuilder aNotes, aQaevents, sNotes, sQaevents;
    WorksheetAnalysisDO waDO1;
    WorksheetItemDO wiDO1;
    WorksheetManager1 wMan;
    WorksheetViewDO wVDO;

    now = ReportUtil.toString(new Date(), Messages.get().dateTimePattern());

    dirName = "";
    try {
        sysVars = systemVariable.fetchByName("worksheet_template_directory", 1);
        if (sysVars.size() > 0)
            dirName = ((SystemVariableDO) sysVars.get(0)).getValue();
    } catch (Exception anyE) {
        throw new Exception("Error retrieving temp directory variable: " + anyE.getMessage());
    }

    analysisIds = new ArrayList<Integer>();
    qcLotIds = new ArrayList<Integer>();
    waVDOMap = new HashMap<Integer, ArrayList<WorksheetAnalysisViewDO>>();
    wMan = worksheetManager.fetchById(worksheetId, WorksheetManager1.Load.DETAIL,
            WorksheetManager1.Load.REAGENT);
    for (WorksheetAnalysisViewDO data : WorksheetManager1Accessor.getAnalyses(wMan)) {
        waVDOs = waVDOMap.get(data.getWorksheetItemId());
        if (waVDOs == null) {
            waVDOs = new ArrayList<WorksheetAnalysisViewDO>();
            waVDOMap.put(data.getWorksheetItemId(), waVDOs);
        }
        waVDOs.add(data);

        if (data.getAnalysisId() != null)
            analysisIds.add(data.getAnalysisId());
        else if (data.getQcLotId() != null)
            qcLotIds.add(data.getQcLotId());
    }

    sMap = new HashMap<Integer, SampleManager1>();
    if (analysisIds.size() > 0) {
        sMans = sampleManager.fetchByAnalyses(analysisIds, SampleManager1.Load.ORGANIZATION,
                SampleManager1.Load.QA, SampleManager1.Load.NOTE, SampleManager1.Load.SINGLEANALYSIS,
                SampleManager1.Load.PROVIDER);
        for (SampleManager1 data : sMans) {
            for (AnalysisViewDO data1 : SampleManager1Accessor.getAnalyses(data))
                sMap.put(data1.getId(), data);
        }
    }

    qaVDOMap = new HashMap<Integer, ArrayList<QcAnalyteViewDO>>();
    qlMap = new HashMap<Integer, QcLotViewDO>();
    if (qcLotIds.size() > 0) {
        qlVDOs = qcLot.fetchByIds(qcLotIds);
        for (QcLotViewDO data : qlVDOs) {
            qlMap.put(data.getId(), data);
            try {
                qaVDOs = qcAnalyte.fetchByQcId(data.getQcId());
                qaVDOMap.put(data.getQcId(), qaVDOs);
            } catch (NotFoundException nfE) {
                // ignore this error as leaving the hash record blank will not
                // cause an error due to a null check later on in the code
            }
        }
    }

    formCapacity = 1;
    out = null;
    try {
        path = ReportUtil.createTempFile("worksheetPrint", ".pdf", null);
        out = Files.newOutputStream(path);

        reader = new PdfReader(dirName + "OEWorksheet" + templateName + ".pdf");
        original = reader.getSafeFile();

        form = reader.getAcroFields();
        if (form.getField("capacity") != null)
            formCapacity = Integer.parseInt(form.getField("capacity"));
        if (form.getField("diagram_capacity") != null)
            diagramCapacity = Integer.parseInt(form.getField("diagram_capacity"));
        else
            diagramCapacity = formCapacity;

        doc = new Document(reader.getPageSizeWithRotation(1));
        writer = new PdfCopy(doc, out);
        doc.open();
        reader.close();

        i = -1;
        pageNumber = -1;
        form = null;
        page = null;
        stamper = null;
        wVDO = wMan.getWorksheet();
        for (WorksheetItemDO wiDO : WorksheetManager1Accessor.getItems(wMan)) {
            j = wiDO.getPosition() % diagramCapacity;
            if (j == 0)
                j = diagramCapacity;
            for (WorksheetAnalysisViewDO waVDO : waVDOMap.get(wiDO.getId())) {
                if (i == -1 || i > formCapacity || j > diagramCapacity) {
                    if (i != -1) {
                        fillReagentFields(form, wMan);
                        stamper.setFormFlattening(true);
                        renameFields(form, pageNumber);
                        flattenFilledFields(stamper, form, formCapacity, pageNumber);
                        stamper.close();
                        reader.close();
                        reader = new PdfReader(page.toByteArray());
                        writer.addPage(writer.getImportedPage(reader, 1));
                        reader.close();
                    }
                    reader = new PdfReader(original, null);
                    page = new ByteArrayOutputStream();
                    stamper = new PdfStamper(reader, page);
                    form = stamper.getAcroFields();
                    i = 1;
                    pageNumber++;

                    form.setField("current_date_time", now);
                    form.setField("username", userName);
                    form.setField("worksheet_description_1", wVDO.getDescription());
                }

                qcLink = "";
                if (waVDO.getWorksheetAnalysisId() != null) {
                    try {
                        waDO1 = worksheetAnalysis.fetchById(waVDO.getWorksheetAnalysisId());
                        wiDO1 = worksheetItem.fetchById(waDO1.getWorksheetItemId());
                        qcLink = waDO1.getAccessionNumber() + " (" + wiDO1.getPosition() + ")";
                    } catch (Exception anyE) {
                        log.log(Level.SEVERE, anyE.getMessage(), anyE);
                    }
                }

                form.setField("worksheet_id_" + (i), wVDO.getId().toString());
                form.setField("created_date_" + (i),
                        ReportUtil.toString(wVDO.getCreatedDate(), Messages.get().dateTimePattern()));
                if (waVDOMap.get(wiDO.getId()).indexOf(waVDO) == 0)
                    form.setField("position_" + (i), wiDO.getPosition().toString());

                if (waVDO.getAnalysisId() != null) {
                    sMan = sMap.get(waVDO.getAnalysisId());
                    sDO = sMan.getSample();
                    patDO = null;
                    proDO = null;
                    seDO = null;
                    if (Constants.domain().CLINICAL.equals(sDO.getDomain())) {
                        patDO = sMan.getSampleClinical().getPatient();
                        proDO = sMan.getSampleClinical().getProvider();
                    } else if (Constants.domain().NEONATAL.equals(sDO.getDomain())) {
                        patDO = sMan.getSampleNeonatal().getPatient();
                        proDO = sMan.getSampleNeonatal().getProvider();
                    } else if (Constants.domain().ENVIRONMENTAL.equals(sDO.getDomain())) {
                        seDO = sMan.getSampleEnvironmental();
                    }
                    sOrgs = SampleManager1Accessor.getOrganizations(sMan);
                    aVDO = (AnalysisViewDO) sMan.getObject(Constants.uid().getAnalysis(waVDO.getAnalysisId()));
                    siVDO = (SampleItemViewDO) sMan
                            .getObject(Constants.uid().getSampleItem(aVDO.getSampleItemId()));

                    sQaevents = new StringBuilder();
                    sqeVDOs = SampleManager1Accessor.getSampleQAs(sMan);
                    if (sqeVDOs != null && sqeVDOs.size() > 0) {
                        for (SampleQaEventViewDO sqeVDO : sqeVDOs) {
                            if (sQaevents.length() > 0)
                                sQaevents.append(" | ");
                            sQaevents.append(sqeVDO.getQaEventName());
                        }
                    }

                    aQaevents = new StringBuilder();
                    aqeVDOs = SampleManager1Accessor.getAnalysisQAs(sMan);
                    if (aqeVDOs != null && aqeVDOs.size() > 0) {
                        for (AnalysisQaEventViewDO aqeVDO : aqeVDOs) {
                            if (!waVDO.getAnalysisId().equals(aqeVDO.getAnalysisId()))
                                continue;
                            if (aQaevents.length() > 0)
                                aQaevents.append(" | ");
                            aQaevents.append(aqeVDO.getQaEventName());
                        }
                    }

                    sNotes = new StringBuilder();
                    nVDOs = new ArrayList<NoteViewDO>();
                    if (SampleManager1Accessor.getSampleInternalNotes(sMan) != null)
                        nVDOs.addAll(SampleManager1Accessor.getSampleInternalNotes(sMan));
                    if (SampleManager1Accessor.getSampleExternalNote(sMan) != null)
                        nVDOs.add(SampleManager1Accessor.getSampleExternalNote(sMan));
                    if (nVDOs != null && nVDOs.size() > 0) {
                        for (NoteViewDO nVDO : nVDOs) {
                            if (sNotes.length() > 0)
                                sNotes.append(" | ");
                            sNotes.append(nVDO.getText());
                        }
                    }

                    aNotes = new StringBuilder();
                    nVDOs = new ArrayList<NoteViewDO>();
                    if (SampleManager1Accessor.getAnalysisInternalNotes(sMan) != null)
                        nVDOs.addAll(SampleManager1Accessor.getAnalysisInternalNotes(sMan));
                    if (SampleManager1Accessor.getAnalysisExternalNotes(sMan) != null)
                        nVDOs.addAll(SampleManager1Accessor.getAnalysisExternalNotes(sMan));
                    if (nVDOs != null && nVDOs.size() > 0) {
                        for (NoteViewDO nVDO : nVDOs) {
                            if (!waVDO.getAnalysisId().equals(nVDO.getReferenceId()))
                                continue;
                            if (aNotes.length() > 0)
                                aNotes.append(" | ");
                            aNotes.append(nVDO.getText());
                        }
                    }

                    if (waVDOMap.get(wiDO.getId()).size() > 1)
                        form.setField("well_label_" + (j), wiDO.getPosition().toString());
                    else
                        form.setField("well_label_" + (j), sDO.getAccessionNumber().toString());
                    form.setField("accession_number_" + (i), sDO.getAccessionNumber().toString());
                    form.setField("qc_link_" + (i), qcLink);
                    if (sDO.getCollectionDate() != null) {
                        collectionDateTime = ReportUtil.toString(sDO.getCollectionDate(),
                                Messages.get().datePattern());
                        if (sDO.getCollectionTime() != null) {
                            collectionDateTime += " ";
                            collectionDateTime += ReportUtil.toString(sDO.getCollectionTime(),
                                    Messages.get().timePattern());
                        }
                        form.setField("collection_date_" + (i), collectionDateTime);
                    }
                    form.setField("received_date_" + (i),
                            ReportUtil.toString(sDO.getReceivedDate(), Messages.get().dateTimePattern()));
                    if (patDO != null) {
                        form.setField("patient_last_" + (i), patDO.getLastName());
                        form.setField("patient_first_" + (i), patDO.getFirstName());
                    }
                    if (proDO != null) {
                        form.setField("provider_last_" + (i), proDO.getLastName());
                        form.setField("provider_first_" + (i), proDO.getFirstName());
                    }
                    if (seDO != null) {
                        form.setField("env_location_" + (i), seDO.getLocation());
                        form.setField("env_description_" + (i), seDO.getDescription());
                    }
                    if (sOrgs != null && sOrgs.size() > 0) {
                        for (SampleOrganizationViewDO soVDO : sOrgs) {
                            if (Constants.dictionary().ORG_REPORT_TO.equals(soVDO.getTypeId()))
                                form.setField("organization_name_" + (i), soVDO.getOrganizationName());
                            else if (Constants.dictionary().ORG_BILL_TO.equals(soVDO.getTypeId()))
                                form.setField("bill_to_name_" + (i), soVDO.getOrganizationName());
                        }
                    }
                    form.setField("type_of_sample_" + (i), siVDO.getTypeOfSample());
                    form.setField("source_of_sample_" + (i), siVDO.getSourceOfSample());
                    form.setField("source_other_" + (i), siVDO.getSourceOther());
                    form.setField("container_reference_" + (i), siVDO.getContainerReference());
                    form.setField("test_" + (i), aVDO.getTestName());
                    form.setField("method_" + (i), aVDO.getMethodName());
                    form.setField("sample_qaevent_" + (i), sQaevents.toString());
                    form.setField("analysis_qaevent_" + (i), aQaevents.toString());
                    form.setField("sample_note_" + (i), sNotes.toString());
                    form.setField("analysis_note_" + (i), aNotes.toString());
                } else if (waVDO.getQcLotId() != null) {
                    qlVDO = qlMap.get(waVDO.getQcLotId());
                    form.setField("well_label_" + (j), qlVDO.getQcName());
                    form.setField("qc_link_" + (i), qcLink);
                    form.setField("qc_name_" + (i), qlVDO.getQcName());
                    form.setField("qc_lot_" + (i), qlVDO.getLotNumber());
                    form.setField("qc_usable_" + (i),
                            ReportUtil.toString(qlVDO.getUsableDate(), Messages.get().dateTimePattern()));
                    form.setField("qc_expiration_" + (i),
                            ReportUtil.toString(qlVDO.getExpireDate(), Messages.get().dateTimePattern()));
                    qaVDOs = qaVDOMap.get(qlVDO.getQcId());
                    if (qaVDOs != null && !qaVDOs.isEmpty())
                        form.setField("qc_expected_value_" + (i), qaVDOs.get(0).getValue());
                }
                i++;
            }
        }
        fillReagentFields(form, wMan);
        stamper.setFormFlattening(true);
        renameFields(form, pageNumber);
        flattenFilledFields(stamper, form, formCapacity, pageNumber);
        stamper.close();
        reader.close();

        reader = new PdfReader(page.toByteArray());
        writer.addPage(writer.getImportedPage(reader, 1));
        doc.close();
        reader.close();
    } finally {
        try {
            if (out != null)
                out.close();
        } catch (Exception e) {
            log.severe("Could not close output stream for worksheet print report");
        }
    }
    return path;
}

From source file:org.opensignature.opensignpdf.PDFSigner.java

License:Open Source License

/**
 * //w w w . j a  va 2 s .  co m
 * @param pdfFile
 * @return
 * @throws IOException
 * @throws DocumentException
 * @throws FileNotFoundException
 */
private PdfReader createPDFReader(File pdfFile) throws IOException, DocumentException, FileNotFoundException {

    logger.info("[createPDFReader.in]:: " + Arrays.asList(new Object[] { pdfFile }));

    PdfReader reader;

    if ("true".equals(openOfficeSelected)) {
        String fileName = pdfFile.getPath();
        String tempFileName = fileName + ".temp";
        PdfReader documentPDF = new PdfReader(fileName);

        PdfStamperOSP stamperTemp = new PdfStamperOSP(documentPDF, new FileOutputStream(tempFileName));
        AcroFields af = stamperTemp.getAcroFields();
        af.setGenerateAppearances(true);
        PdfDictionary acro = (PdfDictionary) PdfReader
                .getPdfObject(documentPDF.getCatalog().get(PdfName.ACROFORM));
        acro.remove(PdfName.DR);
        HashMap fields = af.getFields();
        String key;
        for (Iterator it = fields.keySet().iterator(); it.hasNext();) {
            key = (String) it.next();
            int a = af.getFieldType(key);
            if (a == 4) {
                ArrayList widgets = af.getFieldItem(key).widgets;
                PdfDictionary widget = (PdfDictionary) widgets.get(0);
                widget.put(PdfName.FT, new PdfName("Sig"));
                widget.remove(PdfName.V);
                widget.remove(PdfName.DV);
                widget.remove(PdfName.TU);
                widget.remove(PdfName.FF);
                widget.remove(PdfName.DA);
                widget.remove(PdfName.DR);
                widget.remove(PdfName.AP);
            }
        }

        stamperTemp.close();
        documentPDF.close();
        reader = new PdfReader(pdfFile.getPath() + ".temp");

    } else {
        reader = new PdfReader(pdfFile.getPath());

    }

    logger.info("[createPDFReader.retorna]:: ");
    return reader;

}

From source file:org.oscarehr.common.printing.HtmlToPdfServlet.java

License:Open Source License

public static byte[] stamp(byte[] content) throws Exception {
    PdfReader reader = null;
    ByteArrayOutputStream os = null;
    PdfStamper stamper = null;// ww  w.  j a  v a 2  s.  c om

    try {
        reader = new PdfReader(content);
        os = new ByteArrayOutputStream(content.length);
        stamper = new PdfStamper(reader, os);

        for (int i = 1; i <= reader.getNumberOfPages(); i++) {
            PdfContentByte over = stamper.getOverContent(i);
            BaseFont font = FontSettings.HELVETICA_6PT.createFont();

            over.setFontAndSize(font, 10);
            float center = reader.getPageSize(i).getWidth() / 2.0f;

            // TODO Consider refactoring this into is own class 
            printText(over, "Page " + i + " of " + reader.getNumberOfPages(), center, 35);
            printText(over, OscarProperties.getConfidentialityStatement(), center, 25);
        }

        // this is ugly, but there is no flush method for readers in itext....
        stamper.close();
        reader.close();
        os.flush();

        return os.toByteArray();
    } finally {
        if (os != null)
            IOUtils.closeQuietly(os);
    }
}

From source file:org.oscarehr.common.printing.HtmlToPdfServlet.java

License:Open Source License

private static void close(PdfReader reader) {
    if (reader != null) {
        try {// w  w  w.j a  va  2  s .co  m
            reader.close();
        } catch (Exception e) {
            MiscUtils.getLogger().error("Unable to close reader", e);
        }
    }
}