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:net.sqs2.omr.master.sqm.PDFAttachmentToSQMTranslator.java

License:Apache License

public void execute(InputStream pdfInputStream, String systemId, OutputStream sqmOutputStream)
        throws TranslatorException {
    try {//  ww  w.j  a  v a2 s.co  m
        PdfReader reader = new PdfReader(pdfInputStream);
        byte[] sqmBytes = extractAttachmentFiles(reader, ".sqm");
        reader.close();
        if (sqmBytes == null || sqmBytes.length == 0) {
            throw new TranslatorException("no attachment file.");
        }
        sqmOutputStream.write(sqmBytes);
        sqmOutputStream.flush();
    } catch (IOException ex) {
        throw new TranslatorException(ex);
    } finally {
        try {
            sqmOutputStream.close();
        } catch (Exception ignore) {
        }
    }
}

From source file:net.sqs2.translator.impl.SQSToPDFTranslator.java

License:Apache License

private void combinePDFData(FOUserAgent userAgent, byte[] sqsSourceBytes, byte[] pdfRawDataBytes,
        OutputStream pdfOutputStream, String basename) throws IOException {
    try {/*from w w w . j a v  a2  s. c o m*/
        PdfReader reader = new PdfReader(pdfRawDataBytes);
        int numPages = reader.getNumberOfPages();
        userAgent.getRendererOptions().get("pageWidth");
        byte[] svgBytes = createSVGPrint(userAgent, numPages);
        PdfStamper stamp = new PdfStamper(reader, pdfOutputStream);
        stamp.addFileAttachment("SQS Source", sqsSourceBytes, null, basename + ".sqs");
        stamp.addFileAttachment("SQS Master", svgBytes, null, basename + ".sqm");
        stamp.close();
        reader.close();
    } catch (DocumentException ex) {
        ex.printStackTrace();
    }
}

From source file:org.allcolor.yahp.cl.converter.CDocumentReconstructor.java

License:Open Source License

/**
 * construct a pdf document from pdf parts.
 * //from  w w w .ja  v a2  s.c  o m
 * @param files
 *            list containing the pdf to assemble
 * @param properties
 *            converter properties
 * @param fout
 *            outputstream to write the new pdf
 * @param base_url
 *            base url of the document
 * @param producer
 *            producer of the pdf
 * 
 * @throws CConvertException
 *             if an error occured while reconstruct.
 */
public static void reconstruct(final List files, final Map properties, final OutputStream fout,
        final String base_url, final String producer, final PageSize[] size, final List hf)
        throws CConvertException {
    OutputStream out = fout;
    OutputStream out2 = fout;
    boolean signed = false;
    OutputStream oldOut = null;
    File tmp = null;
    File tmp2 = null;
    try {
        tmp = File.createTempFile("yahp", "pdf");
        tmp2 = File.createTempFile("yahp", "pdf");
        oldOut = out;
        if ("true".equals(properties.get(IHtmlToPdfTransformer.USE_PDF_SIGNING))) {
            signed = true;
            out2 = new FileOutputStream(tmp2);
        } // end if
        else {
            out2 = oldOut;
        }
        out = new FileOutputStream(tmp);
        com.lowagie.text.Document document = null;
        PdfCopy writer = null;
        boolean first = true;

        Map mapSizeDoc = new HashMap();

        int totalPage = 0;

        for (int i = 0; i < files.size(); i++) {
            final File fPDF = (File) files.get(i);
            final PdfReader reader = new PdfReader(fPDF.getAbsolutePath());
            reader.consolidateNamedDestinations();

            final int n = reader.getNumberOfPages();

            if (first) {
                first = false;
                // step 1: creation of a document-object
                // set title/creator/author
                document = new com.lowagie.text.Document(reader.getPageSizeWithRotation(1));
                // step 2: we create a writer that listens to the document
                writer = new PdfCopy(document, out);
                // use pdf version 1.5
                writer.setPdfVersion(PdfWriter.VERSION_1_3);
                // compress the pdf
                writer.setFullCompression();

                // check if encryption is needed
                if ("true".equals(properties.get(IHtmlToPdfTransformer.USE_PDF_ENCRYPTION))) {
                    final String password = (String) properties
                            .get(IHtmlToPdfTransformer.PDF_ENCRYPTION_PASSWORD);
                    final int securityType = CDocumentReconstructor.getSecurityFlags(properties);
                    writer.setEncryption(PdfWriter.STANDARD_ENCRYPTION_128, password, null, securityType);
                } // end if

                final String title = (String) properties.get(IHtmlToPdfTransformer.PDF_TITLE);

                if (title != null) {
                    document.addTitle(title);
                } // end if
                else if (base_url != null) {
                    document.addTitle(base_url);
                } // end else if

                final String creator = (String) properties.get(IHtmlToPdfTransformer.PDF_CREATOR);

                if (creator != null) {
                    document.addCreator(creator);
                } // end if
                else {
                    document.addCreator(IHtmlToPdfTransformer.VERSION);
                } // end else

                final String author = (String) properties.get(IHtmlToPdfTransformer.PDF_AUTHOR);

                if (author != null) {
                    document.addAuthor(author);
                } // end if

                final String sproducer = (String) properties.get(IHtmlToPdfTransformer.PDF_PRODUCER);

                if (sproducer != null) {
                    document.add(new Meta("Producer", sproducer));
                } // end if
                else {
                    document.add(new Meta("Producer", (IHtmlToPdfTransformer.VERSION
                            + " - http://www.allcolor.org/YaHPConverter/ - " + producer)));
                } // end else

                // step 3: we open the document
                document.open();
            } // end if

            PdfImportedPage page;

            for (int j = 0; j < n;) {
                ++j;
                totalPage++;
                mapSizeDoc.put("" + totalPage, "" + i);
                page = writer.getImportedPage(reader, j);
                writer.addPage(page);
            } // end for
        } // end for

        document.close();
        out.flush();
        out.close();
        {
            final PdfReader reader = new PdfReader(tmp.getAbsolutePath());
            ;
            final int n = reader.getNumberOfPages();
            final PdfStamper stp = new PdfStamper(reader, out2);
            int i = 0;
            BaseFont.createFont(BaseFont.HELVETICA, BaseFont.WINANSI, BaseFont.EMBEDDED);
            final CHtmlToPdfFlyingSaucerTransformer trans = new CHtmlToPdfFlyingSaucerTransformer();
            while (i < n) {
                i++;
                int indexSize = Integer.parseInt((String) mapSizeDoc.get("" + i));
                final int[] dsize = size[indexSize].getSize();
                final int[] dmargin = size[indexSize].getMargin();
                for (final Iterator it = hf.iterator(); it.hasNext();) {
                    final CHeaderFooter chf = (CHeaderFooter) it.next();
                    if (chf.getSfor().equals(CHeaderFooter.ODD_PAGES) && (i % 2 == 0)) {
                        continue;
                    } else if (chf.getSfor().equals(CHeaderFooter.EVEN_PAGES) && (i % 2 != 0)) {
                        continue;
                    }
                    final String text = chf.getContent().replaceAll("<pagenumber>", "" + i)
                            .replaceAll("<pagecount>", "" + n);
                    // text over the existing page
                    final PdfContentByte over = stp.getOverContent(i);
                    final ByteArrayOutputStream bbout = new ByteArrayOutputStream();
                    if (chf.getType().equals(CHeaderFooter.HEADER)) {
                        trans.transform(new ByteArrayInputStream(text.getBytes("utf-8")), base_url,
                                new PageSize(dsize[0] - (dmargin[0] + dmargin[1]), dmargin[3]), new ArrayList(),
                                properties, bbout);
                    } else if (chf.getType().equals(CHeaderFooter.FOOTER)) {
                        trans.transform(new ByteArrayInputStream(text.getBytes("utf-8")), base_url,
                                new PageSize(dsize[0] - (dmargin[0] + dmargin[1]), dmargin[2]), new ArrayList(),
                                properties, bbout);
                    }
                    final PdfReader readerHF = new PdfReader(bbout.toByteArray());
                    if (chf.getType().equals(CHeaderFooter.HEADER)) {
                        over.addTemplate(stp.getImportedPage(readerHF, 1), dmargin[0], dsize[1] - dmargin[3]);
                    } else if (chf.getType().equals(CHeaderFooter.FOOTER)) {
                        over.addTemplate(stp.getImportedPage(readerHF, 1), dmargin[0], 0);
                    }
                    readerHF.close();
                }
            }
            stp.close();
        }
        try {
            out2.flush();
        } catch (Exception ignore) {
        } finally {
            try {
                out2.close();
            } catch (Exception ignore) {
            }
        }
        if (signed) {

            final String keypassword = (String) properties
                    .get(IHtmlToPdfTransformer.PDF_SIGNING_PRIVATE_KEY_PASSWORD);
            final String password = (String) properties.get(IHtmlToPdfTransformer.PDF_ENCRYPTION_PASSWORD);
            final String keyStorepassword = (String) properties
                    .get(IHtmlToPdfTransformer.PDF_SIGNING_KEYSTORE_PASSWORD);
            final String privateKeyFile = (String) properties
                    .get(IHtmlToPdfTransformer.PDF_SIGNING_PRIVATE_KEY_FILE);
            final String reason = (String) properties.get(IHtmlToPdfTransformer.PDF_SIGNING_REASON);
            final String location = (String) properties.get(IHtmlToPdfTransformer.PDF_SIGNING_LOCATION);
            final boolean selfSigned = !"false"
                    .equals(properties.get(IHtmlToPdfTransformer.USE_PDF_SELF_SIGNING));
            PdfReader reader = null;

            if (password != null) {
                reader = new PdfReader(tmp2.getAbsolutePath(), password.getBytes());
            } // end if
            else {
                reader = new PdfReader(tmp2.getAbsolutePath());
            } // end else

            final KeyStore ks = selfSigned ? KeyStore.getInstance(KeyStore.getDefaultType())
                    : KeyStore.getInstance("pkcs12");
            ks.load(new FileInputStream(privateKeyFile), keyStorepassword.toCharArray());

            final String alias = (String) ks.aliases().nextElement();
            final PrivateKey key = (PrivateKey) ks.getKey(alias, keypassword.toCharArray());
            final Certificate chain[] = ks.getCertificateChain(alias);
            final PdfStamper stp = PdfStamper.createSignature(reader, oldOut, '\0');

            if ("true".equals(properties.get(IHtmlToPdfTransformer.USE_PDF_ENCRYPTION))) {
                stp.setEncryption(PdfWriter.STANDARD_ENCRYPTION_128, password, null,
                        CDocumentReconstructor.getSecurityFlags(properties));
            } // end if

            final PdfSignatureAppearance sap = stp.getSignatureAppearance();

            if (selfSigned) {
                sap.setCrypto(key, chain, null, PdfSignatureAppearance.SELF_SIGNED);
            } // end if
            else {
                sap.setCrypto(key, chain, null, PdfSignatureAppearance.WINCER_SIGNED);
            } // end else

            if (reason != null) {
                sap.setReason(reason);
            } // end if

            if (location != null) {
                sap.setLocation(location);
            } // end if

            stp.close();
            oldOut.flush();
        } // end if
    } // end try
    catch (final Exception e) {
        throw new CConvertException(
                "ERROR: An Exception occured while reconstructing the pdf document: " + e.getMessage(), e);
    } // end catch
    finally {
        try {
            tmp.delete();
        } // end try
        catch (final Exception ignore) {
        }
        try {
            tmp2.delete();
        } // end try
        catch (final Exception ignore) {
        }
    } // end finally
}

From source file:org.ghost4j.document.PDFDocument.java

License:LGPL

@Override
public void load(InputStream inputStream) throws IOException {
    super.load(inputStream);

    // check that the file is a PDF
    ByteArrayInputStream bais = null;
    PdfReader reader = null;

    try {/* w w w. j a  v  a  2 s .  c o m*/

        bais = new ByteArrayInputStream(content);
        reader = new PdfReader(bais);

    } catch (Exception e) {
        throw new IOException("PDF document is not valid");
    } finally {
        if (reader != null)
            reader.close();
        IOUtils.closeQuietly(bais);
    }
}

From source file:org.ghost4j.document.PDFDocument.java

License:LGPL

public int getPageCount() throws DocumentException {

    int pageCount = 0;

    if (content == null) {
        return pageCount;
    }//  w  w w .j  a  v  a  2 s.  c  o  m

    ByteArrayInputStream bais = null;
    PdfReader reader = null;

    try {

        bais = new ByteArrayInputStream(content);
        reader = new PdfReader(bais);
        pageCount = reader.getNumberOfPages();

    } catch (Exception e) {
        throw new DocumentException(e);
    } finally {
        if (reader != null)
            reader.close();
        IOUtils.closeQuietly(bais);
    }

    return pageCount;

}

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

License:Apache License

/**
 * Junta varios arquivos pdf em um s.//from  w w w . j av  a 2s  .  c om
 * 
 * @param pdfFiles
 *            Coleo de array de bytes
 * @param info
 *            Usa somente as informaes
 *            (title,subject,keywords,author,creator)
 * 
 * @return Arquivo PDF em forma de byte
 * 
 * @since 0.2
 */
public static byte[] mergeFiles(Collection<byte[]> pdfFiles, PdfDocInfo info) {

    try {

        ByteArrayOutputStream byteOS = new ByteArrayOutputStream();

        Document document = new Document();

        PdfCopy copy = new PdfCopy(document, byteOS);

        document.open();

        for (byte[] f : pdfFiles) {

            PdfReader reader = new PdfReader(f);

            for (int page = 1; page <= reader.getNumberOfPages(); page++) {

                copy.addPage(copy.getImportedPage(reader, page));
            }

            reader.close();
        }

        document.addCreationDate();

        if (info != null) {

            document.addAuthor(info.author());
            document.addCreator(info.creator());
            document.addTitle(info.title());
            document.addSubject(info.subject());
            document.addKeywords(info.keywords());
        }

        copy.close();
        document.close();
        byteOS.close();

        return byteOS.toByteArray();

    } catch (Exception e) {
        return Exceptions.throwIllegalStateException(e);
    }
}

From source file:org.kuali.coeus.propdev.impl.s2s.S2sUserAttachedFormServiceImpl.java

License:Open Source License

@Override
@SuppressWarnings({ "rawtypes", "unchecked" })
public List<S2sUserAttachedForm> extractNSaveUserAttachedForms(ProposalDevelopmentDocument developmentProposal,
        S2sUserAttachedForm s2sUserAttachedForm) throws Exception {
    PdfReader reader = null;
    List<S2sUserAttachedForm> formBeans = new ArrayList<S2sUserAttachedForm>();
    try {//from  ww  w .jav a2 s  . c om
        byte pdfFileContents[] = s2sUserAttachedForm.getNewFormFileBytes();
        if (pdfFileContents == null || pdfFileContents.length == 0) {
            S2SException s2sException = new S2SException(KeyConstants.S2S_USER_ATTACHED_FORM_EMPTY,
                    "Uploaded file is empty");
            s2sException.setTabErrorKey("userAttachedFormsErrors");
            throw s2sException;
        } else {
            try {
                reader = new PdfReader(pdfFileContents);
            } catch (IOException ioex) {
                S2SException s2sException = new S2SException(KeyConstants.S2S_USER_ATTACHED_FORM_NOT_PDF,
                        "Uploaded file is not Grants.Gov fillable form", ioex.getMessage());
                s2sException.setTabErrorKey("userAttachedFormsErrors");
                throw s2sException;
            }
            Map attachments = extractAttachments(reader);
            formBeans = extractAndPopulateXml(developmentProposal, reader, s2sUserAttachedForm, attachments);
        }
        resetFormsAvailability(developmentProposal, formBeans);
    } finally {
        if (reader != null)
            reader.close();
    }
    return formBeans;
}

From source file:org.kuali.kra.s2s.service.impl.S2SUserAttachedFormServiceImpl.java

License:Educational Community License

@Override
@SuppressWarnings({ "rawtypes", "unchecked" })
public List<S2sUserAttachedForm> extractNSaveUserAttachedForms(DevelopmentProposal developmentProposal,
        S2sUserAttachedForm s2sUserAttachedForm) throws Exception {
    PdfReader reader = null;
    List<S2sUserAttachedForm> formBeans = new ArrayList<S2sUserAttachedForm>();
    try {/*from  ww  w.  j a  v a2 s  .c o m*/
        byte pdfFileContents[] = s2sUserAttachedForm.getNewFormFileBytes();
        if (pdfFileContents == null || pdfFileContents.length == 0) {
            S2SException s2sException = new S2SException(KeyConstants.S2S_USER_ATTACHED_FORM_EMPTY,
                    "Uploaded file is empty");
            s2sException.setTabErrorKey("userAttachedFormsErrors");
            throw s2sException;
        } else {
            try {
                reader = new PdfReader(pdfFileContents);
            } catch (IOException ioex) {
                S2SException s2sException = new S2SException(KeyConstants.S2S_USER_ATTACHED_FORM_NOT_PDF,
                        "Uploaded file is not Grants.Gov fillable form", ioex.getMessage());
                s2sException.setTabErrorKey("userAttachedFormsErrors");
                throw s2sException;
            }
            Map attachments = extractAttachments(reader);
            formBeans = extractAndPopulateXml(developmentProposal, reader, s2sUserAttachedForm, attachments);
        }
        resetFormsAvailability(developmentProposal, formBeans);
    } finally {
        if (reader != null)
            reader.close();
    }
    return formBeans;
}

From source file:org.lucee.extension.pdf.PDFStruct.java

License:Open Source License

public Struct getInfo() {

    PdfReader pr = null;
    try {/*from w w w  .j a  va  2 s . c  om*/
        pr = getPdfReader();
        // PdfDictionary catalog = pr.getCatalog();
        int permissions = pr.getPermissions();
        boolean encrypted = pr.isEncrypted();

        Struct info = CFMLEngineFactory.getInstance().getCreationUtil().createStruct();
        info.setEL("FilePath", getFilePath());

        // access
        info.setEL("ChangingDocument", allowed(encrypted, permissions, PdfWriter.ALLOW_MODIFY_CONTENTS));
        info.setEL("Commenting", allowed(encrypted, permissions, PdfWriter.ALLOW_MODIFY_ANNOTATIONS));
        info.setEL("ContentExtraction", allowed(encrypted, permissions, PdfWriter.ALLOW_SCREENREADERS));
        info.setEL("CopyContent", allowed(encrypted, permissions, PdfWriter.ALLOW_COPY));
        info.setEL("DocumentAssembly",
                allowed(encrypted, permissions, PdfWriter.ALLOW_ASSEMBLY + PdfWriter.ALLOW_MODIFY_CONTENTS));
        info.setEL("FillingForm",
                allowed(encrypted, permissions, PdfWriter.ALLOW_FILL_IN + PdfWriter.ALLOW_MODIFY_ANNOTATIONS));
        info.setEL("Printing", allowed(encrypted, permissions, PdfWriter.ALLOW_PRINTING));
        info.setEL("Secure", "");
        info.setEL("Signing", allowed(encrypted, permissions, PdfWriter.ALLOW_MODIFY_ANNOTATIONS
                + PdfWriter.ALLOW_MODIFY_CONTENTS + PdfWriter.ALLOW_FILL_IN));

        info.setEL("Encryption", encrypted ? "Password Security" : "No Security");// MUST
        info.setEL("TotalPages", CFMLEngineFactory.getInstance().getCastUtil().toDouble(pr.getNumberOfPages()));
        info.setEL("Version", "1." + pr.getPdfVersion());
        info.setEL("permissions", "" + permissions);
        info.setEL("permiss", "" + PdfWriter.ALLOW_FILL_IN);

        info.setEL("Application", "");
        info.setEL("Author", "");
        info.setEL("CenterWindowOnScreen", "");
        info.setEL("Created", "");
        info.setEL("FitToWindow", "");
        info.setEL("HideMenubar", "");
        info.setEL("HideToolbar", "");
        info.setEL("HideWindowUI", "");
        info.setEL("Keywords", "");
        info.setEL("Language", "");
        info.setEL("Modified", "");
        info.setEL("PageLayout", "");
        info.setEL("Producer", "");
        info.setEL("Properties", "");
        info.setEL("ShowDocumentsOption", "");
        info.setEL("ShowWindowsOption", "");
        info.setEL("Subject", "");
        info.setEL("Title", "");
        info.setEL("Trapped", "");

        // info
        HashMap imap = pr.getInfo();
        Iterator it = imap.entrySet().iterator();
        Map.Entry entry;
        while (it.hasNext()) {
            entry = (Entry) it.next();
            info.setEL(CFMLEngineFactory.getInstance().getCastUtil().toString(entry.getKey(), null),
                    entry.getValue());
        }
        return info;
    } catch (PageException pe) {
        throw CFMLEngineFactory.getInstance().getExceptionUtil().createPageRuntimeException(pe);
    } finally {
        if (pr != null)
            pr.close();
    }
}

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

License:Open Source License

private void doActionThumbnail() throws PageException, IOException, DocumentException {
    required("pdf", "thumbnail", "source", source);

    PDFStruct doc = toPDFDocument(source, password, null);
    PdfReader pr = doc.getPdfReader();
    boolean isEnc = pr.isEncrypted();
    pr.close();
    if (isEnc) {//from w  w w .  j ava 2s. co m
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        // PDFUtil.concat(new PDFDocument[]{doc}, baos, true, true, true, (char)0);
        PDFUtil.encrypt(doc, baos, null, null, 0, PDFUtil.ENCRYPT_NONE);
        baos.close();
        doc = new PDFStruct(baos.toByteArray(), doc.getResource(), null);
    }

    doc.setPages(pages);

    // scale
    if (scale < 1)
        throw engine.getExceptionUtil()
                .createApplicationException("value of attribute scale [" + scale + "] should be at least 1");

    // destination
    if (destination == null)
        destination = engine.getResourceUtil().toResourceNotExisting(pageContext, "thumbnails");

    // imagePrefix
    if (imagePrefix == null) {
        Resource res = doc.getResource();
        if (res != null) {
            String n = res.getName();
            int index = n.lastIndexOf('.');
            if (index != -1)
                imagePrefix = n.substring(0, index);
            else
                imagePrefix = n;
        } else
            imagePrefix = "memory";
    }

    // MUST password
    PDFUtil.writeImages(doc.getRaw(), doc.getPages(), destination, imagePrefix, format, scale, overwrite,
            resolution == RESOLUTION_HIGH, transparent);

}