Example usage for org.apache.pdfbox.io IOUtils closeQuietly

List of usage examples for org.apache.pdfbox.io IOUtils closeQuietly

Introduction

In this page you can find the example usage for org.apache.pdfbox.io IOUtils closeQuietly.

Prototype

public static void closeQuietly(Closeable closeable) 

Source Link

Document

Null safe close of the given Closeable suppressing any exception.

Usage

From source file:TSAClient.java

License:Apache License

private byte[] getTSAResponse(byte[] request) throws IOException {
    LOG.debug("Opening connection to TSA server");

    // todo: support proxy servers
    URLConnection connection = url.openConnection();
    connection.setDoOutput(true);/*from www. ja  v  a  2  s.  com*/
    connection.setDoInput(true);
    connection.setRequestProperty("Content-Type", "application/timestamp-query");

    LOG.debug("Established connection to TSA server");

    if (username != null && password != null && !username.isEmpty() && !password.isEmpty()) {
        connection.setRequestProperty(username, password);
    }

    // read response
    OutputStream output = null;
    try {
        output = connection.getOutputStream();
        output.write(request);
    } finally {
        IOUtils.closeQuietly(output);
    }

    LOG.debug("Waiting for response from TSA server");

    InputStream input = null;
    byte[] response;
    try {
        input = connection.getInputStream();
        response = IOUtils.toByteArray(input);
    } finally {
        IOUtils.closeQuietly(input);
    }

    LOG.debug("Received response from TSA server");

    return response;
}

From source file:CreateVisibleSignature.java

License:Apache License

/**
 * Sign pdf file and create new file that ends with "_signed.pdf".
 *
 * @param inputFile The source pdf document file.
 * @param signedFile The file to be signed.
 * @throws IOException/*www. j a  v a2  s  .  c om*/
 */
public void signPDF(File inputFile, File signedFile) throws IOException {
    if (inputFile == null || !inputFile.exists()) {
        throw new IOException("Document for signing does not exist");
    }

    // creating output document and prepare the IO streams.
    FileOutputStream fos = new FileOutputStream(signedFile);

    // load document
    PDDocument doc = PDDocument.load(inputFile);

    // create signature dictionary
    PDSignature signature = new PDSignature();
    signature.setFilter(PDSignature.FILTER_ADOBE_PPKLITE); // default filter
    // subfilter for basic and PAdES Part 2 signatures
    signature.setSubFilter(PDSignature.SUBFILTER_ADBE_PKCS7_DETACHED);
    signature.setName("signer name");
    signature.setLocation("signer location");
    signature.setReason("reason for signature");

    // the signing date, needed for valid signature
    signature.setSignDate(Calendar.getInstance());

    // register signature dictionary and sign interface
    if (visibleSignatureProperties != null && visibleSignatureProperties.isVisualSignEnabled()) {
        options = new SignatureOptions();
        options.setVisualSignature(visibleSignatureProperties);
        options.setPage(visibleSignatureProperties.getPage() - 1);
        doc.addSignature(signature, this, options);
    } else {
        doc.addSignature(signature, this);
    }

    // write incremental (only for signing purpose)
    doc.saveIncremental(fos);
    doc.close();

    // do not close options before saving, because some COSStream objects within options
    // are transferred to the signed document.
    IOUtils.closeQuietly(options);
}

From source file:dev.ztgnrw.ExtractEmbeddedFiles.java

License:Apache License

private static void extractFile(String filePath, String filename, PDEmbeddedFile embeddedFile)
        throws IOException {
    String embeddedFilename = filePath + filename;
    File file = new File(filePath + filename);
    System.out.println("Writing " + embeddedFilename);
    FileOutputStream fos = null;/*from  ww w. jav a2  s  .c  o  m*/
    try {
        fos = new FileOutputStream(file);
        fos.write(embeddedFile.toByteArray());
    } finally {
        IOUtils.closeQuietly(fos);
    }
}

From source file:io.github.qwefgh90.akka.pdf.PDFUtilWrapper.java

License:Apache License

public static InputStream merge(final List<InputStream> sources, String _title, String _creator,
        String _subject) throws IOException {
    String title = _title == null ? "" : _title;
    String creator = _creator == null ? "" : _creator;
    String subject = _subject == null ? "" : _subject;

    ByteArrayOutputStream mergedPDFOutputStream = null;
    COSStream cosStream = null;/*from w  w  w  . ja  v  a 2s  .c  om*/
    try {
        // If you're merging in a servlet, you can modify this example to use the outputStream only
        // as the response as shown here: http://stackoverflow.com/a/36894346/535646
        mergedPDFOutputStream = new ByteArrayOutputStream();
        cosStream = new COSStream();

        PDFMergerUtility pdfMerger = createPDFMergerUtility(sources, mergedPDFOutputStream);

        // PDF and XMP properties must be identical, otherwise document is not PDF/A compliant
        PDDocumentInformation pdfDocumentInfo = createPDFDocumentInfo(title, creator, subject);
        PDMetadata xmpMetadata = createXMPMetadata(cosStream, title, creator, subject);
        pdfMerger.setDestinationDocumentInformation(pdfDocumentInfo);
        pdfMerger.setDestinationMetadata(xmpMetadata);

        LOG.info("Merging " + sources.size() + " source documents into one PDF");
        pdfMerger.mergeDocuments(MemoryUsageSetting.setupMainMemoryOnly());
        LOG.info("PDF merge successful, size = {" + mergedPDFOutputStream.size() + "} bytes");

        return new ByteArrayInputStream(mergedPDFOutputStream.toByteArray());
    } catch (BadFieldValueException e) {
        throw new IOException("PDF merge problem", e);
    } catch (TransformerException e) {
        throw new IOException("PDF merge problem", e);
    } finally {
        for (InputStream source : sources) {
            IOUtils.closeQuietly(source);
        }
        IOUtils.closeQuietly(cosStream);
        IOUtils.closeQuietly(mergedPDFOutputStream);
    }
}

From source file:io.github.qwefgh90.akka.pdf.PDFUtilWrapper.java

License:Apache License

private static PDMetadata createXMPMetadata(COSStream cosStream, String title, String creator, String subject)
        throws BadFieldValueException, TransformerException, IOException {
    LOG.info("Setting XMP metadata (title, author, subject) for merged PDF");
    XMPMetadata xmpMetadata = XMPMetadata.createXMPMetadata();

    // PDF/A-1b properties
    PDFAIdentificationSchema pdfaSchema = xmpMetadata.createAndAddPFAIdentificationSchema();
    pdfaSchema.setPart(1);/* www. j  av a  2 s.  c  o m*/
    pdfaSchema.setConformance("B");

    // Dublin Core properties
    DublinCoreSchema dublinCoreSchema = xmpMetadata.createAndAddDublinCoreSchema();
    dublinCoreSchema.setTitle(title);
    dublinCoreSchema.addCreator(creator);
    dublinCoreSchema.setDescription(subject);

    // XMP Basic properties
    XMPBasicSchema basicSchema = xmpMetadata.createAndAddXMPBasicSchema();
    Calendar creationDate = Calendar.getInstance();
    basicSchema.setCreateDate(creationDate);
    basicSchema.setModifyDate(creationDate);
    basicSchema.setMetadataDate(creationDate);
    basicSchema.setCreatorTool(creator);

    // Create and return XMP data structure in XML format
    ByteArrayOutputStream xmpOutputStream = null;
    OutputStream cosXMPStream = null;
    try {
        xmpOutputStream = new ByteArrayOutputStream();
        cosXMPStream = cosStream.createOutputStream();
        new XmpSerializer().serialize(xmpMetadata, xmpOutputStream, true);
        cosXMPStream.write(xmpOutputStream.toByteArray());
        return new PDMetadata(cosStream);
    } finally {
        IOUtils.closeQuietly(xmpOutputStream);
        IOUtils.closeQuietly(cosXMPStream);
    }
}

From source file:io.konik.carriage.pdfbox.PDFBoxInvoiceExtractor.java

License:Open Source License

@Override
public byte[] extract(InputStream pdfInput) {
    InputStream attachmentFile = null;
    try {/*from  w  w  w.j ava 2  s. co m*/
        attachmentFile = extractToStream(pdfInput);
        return IOUtils.toByteArray(attachmentFile);
    } catch (IOException e) {
        throw new InvoiceExtractionError("Error extracting content from PDF", e);
    } finally {
        IOUtils.closeQuietly(attachmentFile);
    }
}

From source file:latexstudio.editor.DropboxRevisionsTopComponent.java

private void jTable1MousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTable1MousePressed
    if (evt.getClickCount() == 2) {
        // Resolving which row has been double-clicked
        Point point = evt.getPoint();
        JTable table = (JTable) evt.getSource();
        int row = table.rowAtPoint(point);
        // Finding revision using information from the clicked row
        String revisionNumber = table.getValueAt(row, REVISION_COLUMN).toString();
        DbxEntryRevision entry = null;/* w w w  . j  a v  a2  s .  c o m*/
        DbxClient client = DbxUtil.getDbxClient();
        for (int i = 0; i < dlm.size(); i++) {
            if (revisionNumber.equals(dlm.get(i).getRevision())) {
                entry = dlm.get(i);
                break;
            }
        }

        FileOutputStream outputStream = null;

        if (entry != null) {
            File outputFile = new File(ApplicationUtils.getAppDirectory() + File.separator + entry.getName()
                    + entry.getRevision());

            try {
                outputStream = new FileOutputStream(outputFile);
                client.getFile(entry.getPath(), entry.getRevision(), outputStream);
                LOGGER.log("Loaded revision " + entry.getRevision() + " from Dropbox");
            } catch (Throwable e) {
                Exceptions.printStackTrace(e);
            } finally {
                IOUtils.closeQuietly(outputStream);
            }

            revtc.open();
            revtc.requestActive();
            revtc.setName(entry.getName() + " (rev: " + entry.getRevision() + ")");
            revtc.setDisplayedRevision(new DbxState(entry.getPath(), entry.getRevision()));
            try {
                revtc.setText(FileUtils.readFileToString(outputFile));
            } catch (IOException e) {
                Exceptions.printStackTrace(e);
            }
            updateRevisionsList(entry.getPath());
        }
    }
}

From source file:latexstudio.editor.files.FileService.java

public static String readFromFile(String filename) {
    BufferedReader br = null;/*from   w  w w .j a va 2s . c o  m*/
    String content = "";

    try {
        br = new BufferedReader(new FileReader(filename));
        StringBuilder sb = new StringBuilder();
        String line = br.readLine();

        while (line != null) {
            sb.append(line);
            sb.append(System.lineSeparator());
            line = br.readLine();
        }
        content = sb.toString();
    } catch (IOException ex) {
        Exceptions.printStackTrace(ex);
    } finally {
        IOUtils.closeQuietly(br);
    }

    return content;
}

From source file:latexstudio.editor.remote.DbxUtil.java

public static File downloadRemoteFile(DbxEntryDto remoteEntry, String localPath) {
    DbxClient client = getDbxClient();/*  w  w w .j  a  v a  2s  .  c o m*/

    FileOutputStream outputStream = null;
    File outputFile = new File(localPath);

    try {
        outputStream = new FileOutputStream(outputFile);
        client.getFile(remoteEntry.getPath(), remoteEntry.getRevision(), outputStream);
    } catch (FileNotFoundException ex) {
        Exceptions.printStackTrace(ex);
    } catch (DbxException ex) {
        Exceptions.printStackTrace(ex);
    } catch (IOException ex) {
        Exceptions.printStackTrace(ex);
    } finally {
        IOUtils.closeQuietly(outputStream);
    }

    return outputFile;
}

From source file:no.digipost.print.validate.PdfValidator.java

License:Apache License

/**
 * @param pdfStream the input stream for reading the PDF. It will be closed before returning from
 *                  this method/*from w w  w. j av  a2 s.  c  o m*/
 * @param readStrategy decides if PDF is completely read into memory or not
 */
private PdfValidationResult validerForPrint(InputStream pdfStream,
        PdfValidationSettings printValideringsinnstillinger, PdfValidateStrategy readStrategy) {
    int antallSider = -1;
    try {
        List<PdfValidationError> errors;
        try {
            if (readStrategy == NON_SEQUENTIALLY) {
                try (EnhancedNonSequentialPDFParser dpostNonSequentialPDFParser = new EnhancedNonSequentialPDFParser(
                        pdfStream)) {
                    antallSider = dpostNonSequentialPDFParser.getNumberOfPages();
                    errors = validerStreamForPrint(dpostNonSequentialPDFParser, printValideringsinnstillinger);
                }
            } else if (readStrategy == FULLY_IN_MEMORY) {
                try (PDDocument pdDoc = PDDocument.load(pdfStream)) {
                    antallSider = pdDoc.getNumberOfPages();
                    errors = validerDokumentForPrint(pdDoc, printValideringsinnstillinger);
                }
            } else {
                throw new IllegalArgumentException(
                        "Unknown " + PdfValidateStrategy.class.getSimpleName() + ": " + readStrategy);
            }
        } catch (Exception e) {
            errors = asList(PdfValidationError.PDF_PARSE_ERROR);
            LOG.info("PDF-en kunne ikke parses. (" + e.getMessage() + ")");
            LOG.debug(e.getMessage(), e);
        }

        return new PdfValidationResult(errors, antallSider);
    } finally {
        IOUtils.closeQuietly(pdfStream);
    }
}