Example usage for org.apache.pdfbox.pdmodel PDDocument load

List of usage examples for org.apache.pdfbox.pdmodel PDDocument load

Introduction

In this page you can find the example usage for org.apache.pdfbox.pdmodel PDDocument load.

Prototype

public static PDDocument load(byte[] input) throws IOException 

Source Link

Document

Parses a PDF.

Usage

From source file:eu.europa.esig.dss.pades.signature.PAdESVisibleSignaturePositionTest.java

License:Open Source License

private void checkRotation(InputStream inputStream, int rotate) throws IOException {
    PDDocument document = PDDocument.load(inputStream);

    Assert.assertEquals(rotate, document.getPages().get(0).getRotation());
}

From source file:eu.europa.esig.dss.pades.signature.PAdESVisibleSignaturePositionTest.java

License:Open Source License

private void checkImageSimilarityPdf(String samplePdf, String checkPdf, float similarity) throws IOException {
    DSSDocument document = sign(signablePdfs.get(samplePdf));
    PDDocument sampleDocument = PDDocument.load(document.openStream());
    PDDocument checkDocument = PDDocument
            .load(getClass().getResourceAsStream("/visualSignature/check/" + checkPdf));

    PDPageTree samplePageTree = sampleDocument.getPages();
    PDPageTree checkPageTree = checkDocument.getPages();

    Assert.assertEquals(checkPageTree.getCount(), samplePageTree.getCount());

    PDFRenderer sampleRenderer = new PDFRenderer(sampleDocument);
    PDFRenderer checkRenderer = new PDFRenderer(checkDocument);

    for (int pageNumber = 0; pageNumber < checkPageTree.getCount(); pageNumber++) {
        BufferedImage sampleImage = sampleRenderer.renderImageWithDPI(pageNumber, DPI);
        BufferedImage checkImage = checkRenderer.renderImageWithDPI(pageNumber, DPI);

        float checkSimilarity = checkImageSimilarity(sampleImage, checkImage, CHECK_RESOLUTION);
        float calculatedSimilarity = ((int) (similarity * 100f)) / 100f; // calulate rotated position has about 1
        // pixel position difference
        Assert.assertTrue(checkSimilarity >= calculatedSimilarity);
    }/*from   w  w w  . ja  v a2 s . c o  m*/
}

From source file:eu.europa.esig.dss.pades.signature.PAdESVisibleSignaturePositionTest.java

License:Open Source License

private BufferedImage pdfToBufferedImage(InputStream inputStream) throws IOException {
    PDDocument document = PDDocument.load(inputStream);
    PDFRenderer renderer = new PDFRenderer(document);
    return renderer.renderImageWithDPI(0, DPI);
}

From source file:eu.europa.esig.dss.pdf.pdfbox.PdfBoxSignatureService.java

License:Open Source License

@Override
public byte[] digest(final InputStream toSignDocument, final PAdESSignatureParameters parameters,
        final DigestAlgorithm digestAlgorithm) throws DSSException {

    final byte[] signatureValue = DSSUtils.EMPTY_BYTE_ARRAY;
    File toSignFile = null;/*w  ww  . jav a 2 s  .c om*/
    File signedFile = null;
    PDDocument pdDocument = null;
    try {

        toSignFile = DSSPDFUtils.getFileFromPdfData(toSignDocument);

        pdDocument = PDDocument.load(toSignFile);
        PDSignature pdSignature = createSignatureDictionary(parameters);

        signedFile = File.createTempFile("sd-dss-", "-signed.pdf");
        final FileOutputStream fileOutputStream = DSSPDFUtils.getFileOutputStream(toSignFile, signedFile);

        final byte[] digestValue = signDocumentAndReturnDigest(parameters, signatureValue, signedFile,
                fileOutputStream, pdDocument, pdSignature, digestAlgorithm);
        return digestValue;
    } catch (IOException e) {
        throw new DSSException(e);
    } finally {
        IOUtils.closeQuietly(pdDocument);
        DSSUtils.delete(toSignFile);
        DSSUtils.delete(signedFile);
    }
}

From source file:eu.europa.esig.dss.pdf.pdfbox.PdfBoxSignatureService.java

License:Open Source License

@Override
public void sign(final InputStream pdfData, final byte[] signatureValue, final OutputStream signedStream,
        final PAdESSignatureParameters parameters, final DigestAlgorithm digestAlgorithm) throws DSSException {

    File toSignFile = null;//from  w w  w  . j  a  v a 2s.c  o m
    File signedFile = null;
    FileInputStream fileInputStream = null;
    FileInputStream finalFileInputStream = null;
    PDDocument pdDocument = null;
    try {

        toSignFile = DSSPDFUtils.getFileFromPdfData(pdfData);

        pdDocument = PDDocument.load(toSignFile);
        final PDSignature pdSignature = createSignatureDictionary(parameters);

        signedFile = File.createTempFile("sd-dss-", "-signed.pdf");
        final FileOutputStream fileOutputStream = DSSPDFUtils.getFileOutputStream(toSignFile, signedFile);

        signDocumentAndReturnDigest(parameters, signatureValue, signedFile, fileOutputStream, pdDocument,
                pdSignature, digestAlgorithm);

        finalFileInputStream = new FileInputStream(signedFile);
        IOUtils.copy(finalFileInputStream, signedStream);
    } catch (IOException e) {
        throw new DSSException(e);
    } finally {
        IOUtils.closeQuietly(fileInputStream);
        IOUtils.closeQuietly(finalFileInputStream);
        IOUtils.closeQuietly(pdDocument);
        DSSUtils.delete(toSignFile);
        DSSUtils.delete(signedFile);
    }
}

From source file:eu.europa.esig.dss.pdf.pdfbox.PdfBoxSignatureService.java

License:Open Source License

private List<PdfSignatureOrDocTimestampInfo> getSignatures(CertificatePool validationCertPool,
        byte[] originalBytes) {
    List<PdfSignatureOrDocTimestampInfo> signatures = new ArrayList<PdfSignatureOrDocTimestampInfo>();
    ByteArrayInputStream bais = null;
    PDDocument doc = null;// w  w  w.j  av  a 2 s  .  co  m
    try {

        bais = new ByteArrayInputStream(originalBytes);
        doc = PDDocument.load(bais);

        List<PDSignature> pdSignatures = doc.getSignatureDictionaries();
        if (CollectionUtils.isNotEmpty(pdSignatures)) {
            logger.debug("{} signature(s) found", pdSignatures.size());

            PdfDict catalog = new PdfBoxDict(doc.getDocumentCatalog().getCOSDictionary(), doc);
            PdfDssDict dssDictionary = PdfDssDict.extract(catalog);

            for (PDSignature signature : pdSignatures) {
                String subFilter = signature.getSubFilter();
                byte[] cms = signature.getContents(originalBytes);

                if (StringUtils.isEmpty(subFilter) || ArrayUtils.isEmpty(cms)) {
                    logger.warn("Wrong signature with empty subfilter or cms.");
                    continue;
                }

                byte[] signedContent = signature.getSignedContent(originalBytes);
                int[] byteRange = signature.getByteRange();

                PdfSignatureOrDocTimestampInfo signatureInfo = null;
                if (PdfBoxDocTimeStampService.SUB_FILTER_ETSI_RFC3161.getName().equals(subFilter)) {
                    boolean isArchiveTimestamp = false;

                    // LT or LTA
                    if (dssDictionary != null) {
                        // check is DSS dictionary already exist
                        if (isDSSDictionaryPresentInPreviousRevision(
                                getOriginalBytes(byteRange, signedContent))) {
                            isArchiveTimestamp = true;
                        }
                    }

                    signatureInfo = new PdfBoxDocTimestampInfo(validationCertPool, signature, dssDictionary,
                            cms, signedContent, isArchiveTimestamp);
                } else {
                    signatureInfo = new PdfBoxSignatureInfo(validationCertPool, signature, dssDictionary, cms,
                            signedContent);
                }

                if (signatureInfo != null) {
                    signatures.add(signatureInfo);
                }
            }
            Collections.sort(signatures, new PdfSignatureOrDocTimestampInfoComparator());
            linkSignatures(signatures);

            for (PdfSignatureOrDocTimestampInfo sig : signatures) {
                logger.debug("Signature " + sig.uniqueId() + " found with byteRange "
                        + Arrays.toString(sig.getSignatureByteRange()) + " (" + sig.getSubFilter() + ")");
            }
        }

    } catch (Exception e) {
        logger.warn("Cannot analyze signatures : " + e.getMessage(), e);
    } finally {
        IOUtils.closeQuietly(bais);
        IOUtils.closeQuietly(doc);
    }

    return signatures;
}

From source file:eu.europa.esig.dss.pdf.pdfbox.PdfBoxSignatureService.java

License:Open Source License

private boolean isDSSDictionaryPresentInPreviousRevision(byte[] originalBytes) {
    ByteArrayInputStream bais = null;
    PDDocument doc = null;// ww w  . java 2  s . co  m
    PdfDssDict dssDictionary = null;
    try {
        bais = new ByteArrayInputStream(originalBytes);
        doc = PDDocument.load(bais);
        List<PDSignature> pdSignatures = doc.getSignatureDictionaries();
        if (CollectionUtils.isNotEmpty(pdSignatures)) {
            PdfDict catalog = new PdfBoxDict(doc.getDocumentCatalog().getCOSDictionary(), doc);
            dssDictionary = PdfDssDict.extract(catalog);
        }
    } catch (Exception e) {
        logger.warn("Cannot check in previous revisions if DSS dictionary already exist : " + e.getMessage(),
                e);
    } finally {
        IOUtils.closeQuietly(bais);
        IOUtils.closeQuietly(doc);
    }

    return dssDictionary != null;
}

From source file:eu.europa.esig.dss.pdf.pdfbox.PdfBoxSignatureService.java

License:Open Source License

@Override
public void addDssDictionary(InputStream inputStream, OutputStream outpuStream,
        List<DSSDictionaryCallback> callbacks) {
    File toSignFile = null;//from   ww w  .j a  va 2 s  . c o m
    File signedFile = null;
    FileInputStream fis = null;
    PDDocument pdDocument = null;
    try {
        toSignFile = DSSPDFUtils.getFileFromPdfData(inputStream);
        pdDocument = PDDocument.load(toSignFile);

        signedFile = File.createTempFile("sd-dss-", "-signed.pdf");

        final FileOutputStream fileOutputStream = DSSPDFUtils.getFileOutputStream(toSignFile, signedFile);

        if (CollectionUtils.isNotEmpty(callbacks)) {
            final COSDictionary cosDictionary = pdDocument.getDocumentCatalog().getCOSDictionary();
            cosDictionary.setItem("DSS", buildDSSDictionary(callbacks));
            cosDictionary.setNeedToBeUpdate(true);
        }

        if (pdDocument.getDocumentId() == null) {
            pdDocument.setDocumentId(0L);
        }
        pdDocument.saveIncremental(inputStream, fileOutputStream);

        fis = new FileInputStream(signedFile);
        IOUtils.copy(fis, outpuStream);
    } catch (Exception e) {
        throw new DSSException(e);
    } finally {
        IOUtils.closeQuietly(pdDocument);
        IOUtils.closeQuietly(fis);
        DSSUtils.delete(toSignFile);
        DSSUtils.delete(signedFile);
    }
}

From source file:evadoc_splitter.pdfsplitter.java

public pdfsplitter(String path, HashMap<String, String> caller_id_to_name,
        HashMap<String, String> caller_program_to_div, String root) {

    try {/*from  w  w  w  .  ja v  a2  s . c  o m*/
        this.path = path;
        File file = new File(root + "/..");
        System.out.println();
        this.root = file.getCanonicalPath() + "//";
        this.document = PDDocument.load(this.path);
        this.local_id_to_name = caller_id_to_name;
        this.local_programa_to_division = caller_program_to_div;
        if (local_programa_to_division.size() > 0) {
            this.has_division = true;
        } else {
            this.has_division = false;
        }
    } catch (IOException ex) {
        Logger.getLogger(pdfsplitter.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:evadoc_splitter.pdfsplitter.java

public void split(String current_time) {

    HashMap<String, String> teacher_to_name = new HashMap<String, String>();
    HashMap<String, String> program_to_division = new HashMap<String, String>();
    try {//from   w w w  . jav a 2 s  .  c om

        //open pdf
        this.document = PDDocument.load(this.path);
        this.current_time = current_time;

        //OBTENER EL TIPO DE REPORTE Y CORTAR ESPECIFICAMENTE.
        String type = "";
        if (this.tipo.equals("")) {
            type = get_report_type();
        } else {
            type = this.tipo;
        }

        //::::::::::tipo comentario::::::::::::::::::::::::
        if (type.equals("GZRDEVA")) {//tipo comentario

            //si es pregrado ordenar por dpto, si es postgrado ordenar por programa

            //obtener tipo de evaluaccion:
            Rectangle2D region_eval_tipo = new Rectangle2D.Double(70, 170, 75, 20);
            PDPage page_from = (PDPage) this.document.getDocumentCatalog().getAllPages().get(0);
            String tipo_comentarios = get_text_by_area(region_eval_tipo, page_from, 0);
            //puede que la primera pagina este vacia: CASO 3 documentado, verificar entoces en la segunda  pagina
            if (tipo_comentarios.equals("")) {
                page_from = (PDPage) this.document.getDocumentCatalog().getAllPages().get(1);
                tipo_comentarios = get_text_by_area(region_eval_tipo, page_from, 1);
            }
            if (tipo_comentarios.equals("EVADOCPOS")) {
                //organizar por programa
                Rectangle2D region_programa = new Rectangle2D.Double(390, 155, 250, 20);
                Rectangle2D region_periodo = new Rectangle2D.Double(250, 60, 100, 20);
                Rectangle2D region_id = new Rectangle2D.Double(125, 155, 55, 12);
                Rectangle2D region_nombre = new Rectangle2D.Double(170, 155, 155, 20);
                int numberOfPages = this.document.getNumberOfPages();
                // String regionName = "region_type";
                split_report(region_programa, region_periodo, region_id, region_nombre,
                        "Consolidado Comentarios", numberOfPages);

            } else {
                //en cualquier otro caso (pregrados) organizar por depto
                Rectangle2D region_dpto = new Rectangle2D.Double(90, 110, 500, 20); //ahora es el dpto en ves de programa
                Rectangle2D region_periodo = new Rectangle2D.Double(250, 60, 100, 20);
                Rectangle2D region_id = new Rectangle2D.Double(125, 155, 55, 12);
                Rectangle2D region_nombre = new Rectangle2D.Double(170, 155, 155, 20);
                int numberOfPages = this.document.getNumberOfPages();
                // String regionName = "region_type";
                split_report(region_dpto, region_periodo, region_id, region_nombre, "Consolidado Comentarios",
                        numberOfPages);

            }

        }
        //::::::::::::Catedra:::::::::::::::::::::      

        if (type.equals("GZRDPRP")) {//tipo reporte catedra postgrado
            //organizar por programa
            Rectangle2D region_programa = new Rectangle2D.Double(140, 110, 500, 20);
            Rectangle2D region_periodo = new Rectangle2D.Double(275, 60, 60, 20);
            Rectangle2D region_id = new Rectangle2D.Double(50, 140, 75, 20);
            Rectangle2D region_nombre = new Rectangle2D.Double(120, 140, 155, 20);
            int numberOfPages = this.document.getNumberOfPages();
            // String regionName = "region_type";
            split_report(region_programa, region_periodo, region_id, region_nombre, "Consolidado Catedra",
                    numberOfPages);
        }

        if (type.equals("GZRDEPR")) {//tipo reporte catedra pregrado
            //organizar por dpto
            Rectangle2D region_dpto = new Rectangle2D.Double(120, 100, 500, 20);
            Rectangle2D region_periodo = new Rectangle2D.Double(275, 60, 60, 20);
            Rectangle2D region_id = new Rectangle2D.Double(50, 120, 75, 20);
            Rectangle2D region_nombre = new Rectangle2D.Double(120, 120, 155, 20);
            int numberOfPages = this.document.getNumberOfPages();
            // String regionName = "region_type";
            split_report(region_dpto, region_periodo, region_id, region_nombre, "Consolidado Catedra",
                    numberOfPages);
        }
        //consolidado division postgrado
        if (type.equals("GZRDDIP")) {
            //organizar por div
            Rectangle2D region_div = new Rectangle2D.Double(65, 100, 500, 20);
            Rectangle2D region_periodo = new Rectangle2D.Double(330, 60, 100, 20);
            Rectangle2D region_programa = new Rectangle2D.Double(0, 150, 150, 12);
            Rectangle2D region_nombre = new Rectangle2D.Double(120, 120, 155, 20);
            int numberOfPages = this.document.getNumberOfPages();
            // String regionName = "region_type";
            split_report_consolidado_division(region_div, region_periodo, region_programa,
                    "Consolidado Division", numberOfPages);
        }
        //consolidado division pregrado
        if (type.equals("GZRDEDI")) {
            //organizar por div
            Rectangle2D region_div = new Rectangle2D.Double(65, 100, 500, 20);
            Rectangle2D region_periodo = new Rectangle2D.Double(290, 60, 30, 20);
            Rectangle2D region_programa = new Rectangle2D.Double(0, 150, 150, 12);
            Rectangle2D region_nombre = new Rectangle2D.Double(120, 120, 155, 20);
            int numberOfPages = this.document.getNumberOfPages();
            // String regionName = "region_type";
            split_report_consolidado_division(region_div, region_periodo, region_programa,
                    "Consolidado Division", numberOfPages);
        }

        //get pdf type by extracting baner ID from coordinates.

        //si es comentario... if type == "GZRDEVA"

        //pdf.split by id in cordenates
        //si es resultado... else GZRDPRP
        //split by id in coordinates
        int numberOfPages = this.document.getNumberOfPages();
        System.out.println("Selected file: " + numberOfPages);
    } catch (IOException ex) {
        Logger.getLogger(pdfsplitter.class.getName()).log(Level.SEVERE, null, ex);
    }

}