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:ccc.plugins.search.lucene.PdfLoader.java

License:Open Source License

/** {@inheritDoc} */
@Override/*from  w  w w  .  j  ava 2 s . c o m*/
public void execute(final InputStream is) {
    try {
        final PDDocument doc = PDDocument.load(is);
        if (doc == null) {
            return;
        }
        extractText(doc);

    } catch (final Exception e) {
        LOG.warn("PDF file extraction failed.", e);
    }
}

From source file:cdiscisa.StreamUtil.java

private static void imprimirDiplomas(ArrayList<Participante> listaParticipantes, Curso c, Directorio d,
            String chkDipFirma, String chkDipLogo, String savePath, Map<String, String> dosc, String instructor,
            Map<String, String> abreviaturas) throws IOException {

        ListIterator<Participante> it = listaParticipantes.listIterator();
        Participante p1 = null;/*  ww w .  j a v a  2 s .  co  m*/
        Participante p2 = null;
        String abrev_curso = "";

        // Create a document and add a page to it
        PDDocument document = new PDDocument();
        PDDocument documentSingle;

        InputStream file = null;

        BufferedImage logo = null;
        BufferedImage firma = null;

        try {

            //logo = new File(cdiscisa.Cdiscisa.class.getClassLoader().getResource("files/logo.png").getFile());
            //logo = cdiscisa.Cdiscisa.class.getClassLoader().getResourceAsStream("files/logo.png");
            logo = ImageIO.read(cdiscisa.Cdiscisa.class.getClassLoader().getResourceAsStream("files/logo.png"));
            //logo = cdiscisa.Cdiscisa.class.getClassLoader().getResourceAsStream("files/logo.png");

            if (instructor.equalsIgnoreCase("Ing. Jorge Antonio Razn Gutierrez")) {
                //firma = new File(cdiscisa.Cdiscisa.class.getClassLoader().getResource("files/firmaCoco.png").getFile());
                firma = ImageIO
                        .read(cdiscisa.Cdiscisa.class.getClassLoader().getResourceAsStream("files/firmaCoco.png"));
            } else if (instructor.equalsIgnoreCase("Manuel Anguiano Razn")) {
                firma = ImageIO.read(
                        cdiscisa.Cdiscisa.class.getClassLoader().getResourceAsStream("files/firmaManuel.png"));
                //firma = new File(cdiscisa.Cdiscisa.class.getClassLoader().getResource("files/firmaManuel.png").getFile());
            } else {
                firma = ImageIO
                        .read(cdiscisa.Cdiscisa.class.getClassLoader().getResourceAsStream("files/firmaJorge.png"));
                //firma = new File(cdiscisa.Cdiscisa.class.getClassLoader().getResource("files/firmaJorge.png").getFile());
            }

        } catch (Exception ex) {
            JOptionPane.showMessageDialog(null, "Error al cargar la imagen del logo o la firma \nfile: "
                    + String.valueOf(logo) + "\n" + String.valueOf(firma) + "\n" + ex.toString());
        }

        PDImageXObject firmaObject = null;
        PDImageXObject logoObject = null;

        try {
            if (chkDipLogo.equalsIgnoreCase("true")) {
                //logoObject = PDImageXObject.createFromFile(logo, document);                
                logoObject = LosslessFactory.createFromImage(document, logo);
            }

            if (chkDipFirma.equalsIgnoreCase("true")) {
                // firmaObject = PDImageXObject.createFromFile(firma, document);
                firmaObject = LosslessFactory.createFromImage(document, firma);
            }

        } catch (Exception ex) {
            JOptionPane.showMessageDialog(null, "Error al crear objetos de logo o firma \nfile: "
                    + String.valueOf(logoObject) + "\n" + String.valueOf(firmaObject) + "\n" + ex.toString());
        }

        try {
            file = cdiscisa.Cdiscisa.class.getClassLoader()
                    .getResourceAsStream("files/n_diploma_simple_vacio_nf_nl_nr.pdf");
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(null,
                    "Error al cargar el el diploma single base. \ndiploma: files/n_diploma_simple_vacio_nf_nl_nr.pdf \nfile: "
                            + String.valueOf(file) + "\n" + ex.toString());
        }

        documentSingle = PDDocument.load(file);

        PDPage pageSingle = (PDPage) documentSingle.getDocumentCatalog().getPages().get(0);
        COSDictionary pageDictSingle = pageSingle.getCOSObject();
        COSDictionary newPageSingleDict = new COSDictionary(pageDictSingle);
        PDPage templatePageSingle = new PDPage(newPageSingleDict);

        // Create a document and add a page to it

        PDDocument documentDoble;

        InputStream file2 = null;

        try {
            file2 = cdiscisa.Cdiscisa.class.getClassLoader()
                    .getResourceAsStream("files/n_diploma_doble_vacio_nf_nl_nr.pdf");
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(null,
                    "Error al cargar el el diploma doble base. \ndiploma: n_diploma_doble_vacio_nf_nl_nr.pdf\nfile: "
                            + String.valueOf(file2) + "\n" + ex.toString());
        }

        documentDoble = PDDocument.load(file2);

        PDPage pageDoble = (PDPage) documentDoble.getDocumentCatalog().getPages().get(0);
        COSDictionary pageDobleDict = pageDoble.getCOSObject();
        COSDictionary newPageDobleDict = new COSDictionary(pageDobleDict);

        PDPage templatePageDoble = new PDPage(newPageDobleDict);

        InputStream isFont1 = null, isFont2 = null, isFont3 = null;

        try {
            isFont1 = cdiscisa.Cdiscisa.class.getClassLoader().getResourceAsStream("files/Calibri.ttf");
            isFont2 = cdiscisa.Cdiscisa.class.getClassLoader().getResourceAsStream("files/CalibriBold.ttf");
            isFont3 = cdiscisa.Cdiscisa.class.getClassLoader().getResourceAsStream("files/Pristina.ttf");
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(null,
                    "Error al cargar el una fuente \nisFont1: " + String.valueOf(isFont1) + "\nisFont2: "
                            + String.valueOf(isFont2) + "\nisFont3: " + String.valueOf(isFont3) + "\n"
                            + ex.toString());
        }
        PDFont calibri = null;
        PDFont calibriBold = null;
        PDFont pristina = null;

        calibri = PDType0Font.load(document, isFont1);
        calibriBold = PDType0Font.load(document, isFont2);
        pristina = PDType0Font.load(document, isFont3);

        if (listaParticipantes.size() % 2 == 0 && listaParticipantes.size() >= 2) {

            while (it.hasNext()) {
                p1 = it.next();
                p2 = it.next();

                imprimirDiplomaDoble(p1, p2, c, d, document, templatePageDoble, calibri, calibriBold, pristina,
                        logoObject, firmaObject, instructor);
            }
        } else {
            if (listaParticipantes.size() > 1) {
                //Lista es impar y contiene mas de 2 participantes.
                while (it.hasNext()) {

                    if (it.nextIndex() == listaParticipantes.size() - 1) {
                        p1 = it.next();
                        imprimirDiplomaArriba(p1, c, d, document, templatePageSingle, calibri, calibriBold,
                                pristina, logoObject, firmaObject, instructor);
                        break;
                    }

                    p1 = it.next();
                    p2 = it.next();

                    imprimirDiplomaDoble(p1, p2, c, d, document, templatePageDoble, calibri, calibriBold, pristina,
                            logoObject, firmaObject, instructor);
                }
            } else if (listaParticipantes.size() == 1) {
                p1 = it.next();
                imprimirDiplomaArriba(p1, c, d, document, templatePageSingle, calibri, calibriBold, pristina,
                        logoObject, firmaObject, instructor);
            }

        }

        Format formatter = new SimpleDateFormat("ddMMMYYYY", new Locale("es", "MX"));
        String formatedDate = formatter.format(c.fecha_inicio);

        String abrev = abreviaturas.get(c.nombre_curso);

        if (c.walmart) {
            document.save(savePath + File.separator + "Diplomas_" + d.formato + "_" + d.unidad + "_"
                    + d.determinante + "_" + abrev + "_" + formatedDate + ".pdf");
            document.close();
            dosc.put(savePath + File.separator + "Diplomas_" + d.formato + "_" + d.unidad + "_" + d.determinante
                    + "_" + abrev + "_" + formatedDate + ".pdf", d.determinante);
        } else {
            document.save(savePath + File.separator + "Diplomas_" + d.determinante + "_" + abrev + "_"
                    + formatedDate + ".pdf");
            document.close();
            dosc.put(savePath + File.separator + "Diplomas_" + d.determinante + "_" + abrev + "_" + formatedDate
                    + ".pdf", d.determinante);
        }
    }

From source file:cdiscisa.StreamUtil.java

private static void imprimirDC3_individual(Participante p, Curso c, String chkDC3Firmaa, String chkDC3Logoa,
            String savePath, Map<String, String> dosc, Map<String, String> abreviaturas) throws IOException {

        //JOptionPane.showMessageDialog(null, "entrando a imrpimir individual");
        PDDocument document;/*from w  ww.  ja v  a 2s  . c  o  m*/
        //BufferedInputStream file;
        InputStream file = null;

        try {
            file = cdiscisa.Cdiscisa.class.getClassLoader().getResourceAsStream("files/DC3_blank.pdf");
            //file = cdiscisa.Cdiscisa.class.getClassLoader().getResourceAsStream("files/DC3_base_firma.pdf");
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(null,
                    "Error al cargar el una forma DC3 \nfile: " + String.valueOf(file) + "\n" + ex.toString());
        }
        document = PDDocument.load(file);

        BufferedImage logo = null;
        BufferedImage firma = null;

        try {
            //logo = new File(cdiscisa.Cdiscisa.class.getClassLoader().getResource("files/logo.png").getFile());
            logo = ImageIO.read(cdiscisa.Cdiscisa.class.getClassLoader().getResourceAsStream("files/logo.png"));
            //logo = StreamUtil.stream2file(cdiscisa.Cdiscisa.class.getClassLoader().getResourceAsStream("files/logo.png"));
            if (c.capacitador.equalsIgnoreCase("Ing. Jorge Antonio Razn Gutierrez")) {
                //firma = new File(cdiscisa.Cdiscisa.class.getClassLoader().getResource("files/firmaCoco.png").getFile());
                firma = ImageIO
                        .read(cdiscisa.Cdiscisa.class.getClassLoader().getResourceAsStream("files/firmaCoco.png"));
            } else if (c.capacitador.equalsIgnoreCase("Manuel Anguiano Razn")) {
                firma = ImageIO.read(
                        cdiscisa.Cdiscisa.class.getClassLoader().getResourceAsStream("files/firmaManuel.png"));
                //firma = new File(cdiscisa.Cdiscisa.class.getClassLoader().getResource("files/firmaManuel.png").getFile());
            } else {
                firma = ImageIO
                        .read(cdiscisa.Cdiscisa.class.getClassLoader().getResourceAsStream("files/firmaJorge.png"));
                //firma = new File(cdiscisa.Cdiscisa.class.getClassLoader().getResource("files/firmaJorge.png").getFile());
            }

        } catch (Exception ex) {
            JOptionPane.showMessageDialog(null, "Error al cargar la imagen del logo o la firma \nfile: "
                    + String.valueOf(logo) + "\n" + String.valueOf(firma) + "\n" + ex.toString());
        }

        PDImageXObject firmaObject = null;
        PDImageXObject logoObject = null;

        try {
            if (chkDC3Firmaa.equalsIgnoreCase("true")) {
                firmaObject = LosslessFactory.createFromImage(document, firma);
                //firmaObject = PDImageXObject.createFromFile(firma, document);
            }

            if (chkDC3Logoa.equalsIgnoreCase("true")) {
                logoObject = LosslessFactory.createFromImage(document, logo);
                //logoObject = PDImageXObject.createFromFile(logo, document);
            }
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(null, "Error al crear objetos de logo o firma \nfile: "
                    + String.valueOf(logoObject) + "\n" + String.valueOf(firmaObject) + "\n" + ex.toString());
        }

        PDPage page = (PDPage) document.getDocumentCatalog().getPages().get(0);
        PDFont helvetica = PDType1Font.HELVETICA_BOLD;
        PDFont helvetica_normal = PDType1Font.HELVETICA;
        PDPageContentStream contentStream = new PDPageContentStream(document, page, true, true);

        contentStream.beginText();
        contentStream.setFont(helvetica_normal, 13);
        contentStream.setNonStrokingColor(Color.BLACK);

        contentStream.setTextMatrix(new Matrix(1, 0, 0, 1, 30, 602));
        contentStream.showText(p.apellidos + " " + p.nombre);

        String temp;

        if (p.curp.length() > 18) {
            temp = p.curp.substring(0, 18);
        } else {
            temp = p.curp;
        }
        char[] curpArray = temp.toCharArray();
        float[] xPosition = { 32, 49, 63, 77, 92, (float) 106.5, 120, (float) 134.5, 149, 163, 177, (float) 191.5,
                205, 223, 241, 255, 269, 286 };

        float charWidth;

        for (int i = 0; i <= curpArray.length - 1; i++) {
            charWidth = helvetica_normal.getStringWidth(String.valueOf(curpArray[i])) / 1000 * 13;
            //System.out.println("Char " + i + " width: " + charWidth);

            float x = xPosition[i] - (charWidth / 2);
            contentStream.setTextMatrix(new Matrix(1, 0, 0, 1, x, 572));
            contentStream.showText(String.valueOf(curpArray[i]));
        }

        contentStream.setTextMatrix(new Matrix(1, 0, 0, 1, 30, 548));
        contentStream.showText(p.area_puesto);

        contentStream.setTextMatrix(new Matrix(1, 0, 0, 1, 30, 486));
        if (c.walmart) {
            contentStream.showText("OPERADORA WALMART S DE RL DE CV");
        } else {
            contentStream.showText(c.nombre_empresa);
        }

        char[] rfc_emprea_array;

        if (c.walmart) {
            rfc_emprea_array = "OWM011023AWA".toCharArray();
        } else {
            rfc_emprea_array = c.rfc_empresa.toCharArray();
        }

        try {
            int j = 0;
            for (int i = 0; i <= rfc_emprea_array.length - 1; i++) {
                charWidth = helvetica_normal
                        .getStringWidth(String.valueOf(rfc_emprea_array[rfc_emprea_array.length - i - 1])) / 1000
                        * 13;
                //System.out.println("Char " + i + " width: " + charWidth);

                if (j == 3 || i == 9) {
                    j = j + 1;
                }
                float x = xPosition[xPosition.length - j - 4] - (charWidth / 2);
                contentStream.setTextMatrix(new Matrix(1, 0, 0, 1, x, 458));
                contentStream.showText(String.valueOf(rfc_emprea_array[rfc_emprea_array.length - i - 1]));
                j = j + 1;
            }
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(null,
                    "El RFC de la empresa esta mal formado. \n\nex.toString : " + ex.toString());
            return;
        }
        contentStream.setTextMatrix(new Matrix(1, 0, 0, 1, 30, 405));
        contentStream.showText(c.nombre_curso);

        contentStream.setTextMatrix(new Matrix(1, 0, 0, 1, 30, 381));
        contentStream.showText(c.horas_texto);

        //if (c.walmart){
        contentStream.setTextMatrix(new Matrix(1, 0, 0, 1, 30, 356));
        contentStream.showText("6000 SEGURIDAD");
        //} else{
        //    contentStream.setTextMatrix(new Matrix(1,0,0,1,30,356 ));           
        //    contentStream.showText(p.area_tematica);
        //}

        contentStream.setTextMatrix(new Matrix(1, 0, 0, 1, 30, 332));
        contentStream.showText(c.uCapacitadora);

        Calendar cal = Calendar.getInstance();
        cal.setTime(c.fecha_inicio);
        String month = String.format("%02d", cal.get(Calendar.MONTH) + 1);
        String year = String.format("%04d", cal.get(Calendar.YEAR));
        String day = String.format("%02d", cal.get(Calendar.DAY_OF_MONTH));

        String date = year + month + day;

        cal.setTime(c.fecha_termino);
        month = String.format("%02d", cal.get(Calendar.MONTH) + 1);
        year = String.format("%04d", cal.get(Calendar.YEAR));
        day = String.format("%02d", cal.get(Calendar.DAY_OF_MONTH));

        date = date + year + month + day;

        char[] date_array = date.toCharArray();
        float[] xPos = { 256, 272, 288, 304, 322, 343, 365, 386, 428, 447, 467, 486, 507, 528, 549, 570 };

        for (int i = 0; i <= date_array.length - 1; i++) {
            charWidth = helvetica_normal.getStringWidth(String.valueOf(date_array[i])) / 1000 * 13;
            //System.out.println("Char " + i + " width: " + charWidth);

            float x = xPos[i] - (charWidth / 2);
            contentStream.setTextMatrix(new Matrix(1, 0, 0, 1, x, 381));
            contentStream.showText(String.valueOf(date_array[i]));

        }

        charWidth = helvetica_normal.getStringWidth(p.area_tematica) / 1000 * 13;
        //System.out.println(p.area_tematica + " bold : " + charWidth);
        if (charWidth >= 255) {
            contentStream.setFont(helvetica_normal, 10);
            charWidth = helvetica_normal.getStringWidth(p.area_tematica) / 1000 * 10;
            //System.out.println(p.area_tematica + " : " + charWidth);
            if (charWidth >= 260) {
                contentStream.setFont(helvetica_normal, 8);
                //charWidth = helvetica_normal.getStringWidth(p.area_tematica) /1000 * 8;
                //System.out.println(p.area_tematica + " : " + charWidth);
            }
        }

        contentStream.setTextMatrix(new Matrix(1, 0, 0, 1, 310, 572));
        contentStream.showText(p.area_tematica);

        contentStream.endText();

        //xPosition = 256, 272, 288, 304, 322, 343, 365, 386, 428, 447, 467, 486, 507, 528, 549, 570
        //year: 256, 272, 288, 304
        //month: 322, 343
        //day: 365, 386

        //year: 428, 447, 467, 486
        //month: 507, 528
        //day: 549, 570

        // 32, 49, 63, 77, 92, 106.5, 120, 134.5, 149, 163, 177, 191.5, 205, 223, 241, 255, 269, 286  
        /*Esto es para medir las casillas del curp
        contentStream.setStrokingColor(Color.BLACK);
        contentStream.moveTo(286,569);
        contentStream.lineTo(286,580);
        contentStream.stroke();
        */

        /*
        PDImageXObject logo = PDImageXObject.createFromFile("src/files/logo.png", document);
        PDImageXObject firma = PDImageXObject.createFromFile("src/files/firmasola.png", document);
            
        System.out.println("logoWidth: " + logo.getWidth());
        System.out.println("logoHeight: " + logo.getHeight());
        System.out.println("firmaWidth: " + firma.getWidth());
        System.out.println("firmaHeight: " + firma.getHeight());
        */
        contentStream.addRect(50, 750, 500, 100);
        contentStream.setNonStrokingColor(Color.WHITE);
        contentStream.fill();

        contentStream.addRect(50, 224, 150, 10);
        contentStream.setNonStrokingColor(Color.WHITE);
        contentStream.fill();

        if (logoObject != null && !logoObject.isEmpty()) {
            contentStream.drawImage(logoObject, 430, 700, 150, 75);
        }
        if (firmaObject != null && !firmaObject.isEmpty()) {
            contentStream.drawImage(firmaObject, 80, 223, 110, 42);

            contentStream.setStrokingColor(Color.BLACK);
            contentStream.setLineWidth((float) .8);
            contentStream.moveTo(50, (float) 235.6);
            contentStream.lineTo(200, (float) 235.6);
            contentStream.stroke();

        }

        contentStream.beginText();
        contentStream.setFont(helvetica_normal, 8);
        contentStream.setNonStrokingColor(Color.BLACK);

        charWidth = helvetica_normal.getStringWidth(c.capacitador) / 1000 * 8;
        float x = 126 - charWidth / 2;

        contentStream.setTextMatrix(new Matrix(1, 0, 0, 1, x, 228));
        contentStream.showText(c.capacitador);
        //GIS100219KK8003
        String regUnidad;

        if (c.uCapacitadora.equalsIgnoreCase("TSI. Jorge Antonio Razn Gil")) {
            regUnidad = "RAGJ610813BIA005";
        } else {
            regUnidad = "GIS100219KK8003";
        }

        charWidth = helvetica_normal.getStringWidth(regUnidad) / 1000 * 8;
        x = 126 - charWidth / 2;
        contentStream.setTextMatrix(new Matrix(1, 0, 0, 1, x, 219));
        contentStream.showText(regUnidad);

        contentStream.endText();

        // Make sure that the content stream is closed:
        contentStream.close();
        Format formatter = new SimpleDateFormat("ddMMMYYYY", new Locale("es", "MX"));
        String formatedDate = formatter.format(c.fecha_inicio);

        String abrev = abreviaturas.get(c.nombre_curso);

        // Save the results and ensure that the document is properly closed:

        document.save(savePath + File.separator + "p_DC3_" + p.curp + "_" + p.determinante + "_"
                + p.nombre.replaceAll(" ", "_") + "_" + p.apellidos.replaceAll(" ", "_") + "_" + abrev + "_"
                + formatedDate + ".pdf");
        document.close();
        dosc.put(savePath + File.separator + "p_DC3_" + p.curp + "_" + p.determinante + "_"
                + p.nombre.replaceAll(" ", "_") + "_" + p.apellidos.replaceAll(" ", "_") + "_" + abrev + "_"
                + formatedDate + ".pdf", p.determinante);

    }

From source file:cdiscisa.StreamUtil.java

private static void imprimirUnaConstancia(ArrayList<Participante> listaParticipantes, Curso c, Directorio d,
            String chkConstFirma, String chkConstLogo, String savePath, Map<String, String> dosc, String instructor,
            Map<String, String> abreviaturas) throws IOException {

        String contanciaTemplate = "";

        switch (c.nombre_curso) {
        case "PREVENCIN Y COMBATE DE INCENDIOS I":
            contanciaTemplate = "files/certificado_vacio_incendio_basico_nf_nl.pdf";
            break;
        case "BUSQUEDA Y RESCATE":
            contanciaTemplate = "files/certificado_vacio_busq_rescate_nf_nl.pdf";
            break;
        case "EVACUACIN, BUSQUEDA Y RESCATE":
            contanciaTemplate = "files/certificado_vacio_evac_busq_resc_nf_nl.pdf";
            break;
        case "EVACUACIN":
            contanciaTemplate = "files/certificado_vacio_evacuacion_nf_nl.pdf";
            break;
        case "PREVENCIN Y COMBATE DE INCENDIOS II":
            contanciaTemplate = "files/certificado_vacio_incendio_intermedio_nf_nl.pdf";
            break;
        case "PREVENCIN Y COMBATE DE INCENDIOS III":
            contanciaTemplate = "files/certificado_vacio_incendio_avanzado_nf_nl.pdf";
            break;
        case "FORMACION DE BRIGADAS MULTIFUNCIONALES DE EMERGENCIA":
            contanciaTemplate = "files/certificado_vacio_multi_nf_nl.pdf";
            break;
        case "FORMACIN DE BRIGADA MULTIFUNCIONAL DE EMERGENCIA":
            contanciaTemplate = "files/certificado_vacio_multi_nf_nl.pdf";
            break;
        case "FORMACION DE BRIGADA MULTIFUNCIONAL DE EMERGENCIAS":
            contanciaTemplate = "files/certificado_vacio_multi_nf_nl.pdf";
            break;
        case "PRIMEROS AUXILIOS":
            contanciaTemplate = "files/certificado_vacio_primeros_auxilios_nf_nl.pdf";
            break;
        default:/*  w  w  w . j a v  a  2s.  co m*/
            contanciaTemplate = "files/cerificado_vacio.pdf";
            break;
        }

        InputStream file = null;
        try {
            file = cdiscisa.Cdiscisa.class.getClassLoader().getResourceAsStream(contanciaTemplate);
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(null, "Error al cargar el certificado base. \nconstancia: "
                    + contanciaTemplate + "\nfile: " + String.valueOf(file) + "\n" + ex.toString());
        }
        PDDocument document = PDDocument.load(file);
        PDPage page1 = (PDPage) document.getDocumentCatalog().getPages().get(0);
        PDPage page2 = (PDPage) document.getDocumentCatalog().getPages().get(1);

        PDPageContentStream contentStream = new PDPageContentStream(document, page1, true, true);
        PDPageContentStream contentStream2 = new PDPageContentStream(document, page2, true, true);

        float pageWidth = page1.getMediaBox().getWidth();

        BufferedImage logo = null;
        BufferedImage firma = null;

        try {
            ClassLoader classLoader = Thread.currentThread().getContextClassLoader();

            //logo = new File(classLoader.getResource("files/logo.png").getFile());
            //logo = StreamUtil.stream2file(cdiscisa.Cdiscisa.class.getClassLoader().getResourceAsStream("files/logo.png"));
            logo = ImageIO.read(cdiscisa.Cdiscisa.class.getClassLoader().getResourceAsStream("files/logo.png"));

            if (instructor.equalsIgnoreCase("Ing. Jorge Antonio Razn Gutierrez")) {
                firma = ImageIO
                        .read(cdiscisa.Cdiscisa.class.getClassLoader().getResourceAsStream("files/firmaCoco.png"));
                //firma = new File(cdiscisa.Cdiscisa.class.getClassLoader().getResource("files/firmaCoco.png").getFile());
            } else if (instructor.equalsIgnoreCase("Manuel Anguiano Razn")) {
                firma = ImageIO.read(
                        cdiscisa.Cdiscisa.class.getClassLoader().getResourceAsStream("files/firmaManuel.png"));
                //firma = new File(cdiscisa.Cdiscisa.class.getClassLoader().getResource("files/firmaManuel.png").getFile());
            } else {
                firma = ImageIO
                        .read(cdiscisa.Cdiscisa.class.getClassLoader().getResourceAsStream("files/firmaJorge.png"));
                //firma = new File(cdiscisa.Cdiscisa.class.getClassLoader().getResource("files/firmaJorge.png").getFile());
            }

        } catch (Exception ex) {
            JOptionPane.showMessageDialog(null, "Error al cargar la imagen del logo o la firma \nfile: "
                    + String.valueOf(logo) + "\n" + String.valueOf(firma) + "\n" + ex.toString());
        }

        PDImageXObject firmaObject = null;
        PDImageXObject logoObject = null;

        try {
            if (chkConstFirma.equalsIgnoreCase("true")) {
                firmaObject = LosslessFactory.createFromImage(document, firma);
                //firmaObject = PDImageXObject.createFromFile(firma, document);
            }
            if (chkConstLogo.equalsIgnoreCase("true")) {
                logoObject = LosslessFactory.createFromImage(document, logo);
                //logoObject = PDImageXObject.createFromFile(logo, document);
            }
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(null, "Error al crear objetos de logo o firma \nfile: "
                    + String.valueOf(logoObject) + "\n" + String.valueOf(firmaObject) + "\n" + ex.toString());
        }

        InputStream isFont1 = null, isFont2 = null;
        try {
            isFont1 = cdiscisa.Cdiscisa.class.getClassLoader().getResourceAsStream("files/Calibri.ttf");
            isFont2 = cdiscisa.Cdiscisa.class.getClassLoader().getResourceAsStream("files/CalibriBold.ttf");
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(null, "Error al cargar el una fuente \nisFont1: "
                    + String.valueOf(isFont1) + "\nisFont2: " + String.valueOf(isFont2) + "\n" + ex.toString());
        }

        PDFont calibri = PDType0Font.load(document, isFont1);
        PDFont calibriBold = PDType0Font.load(document, isFont2);

        contentStream.beginText();
        DateFormat df = DateFormat.getDateInstance(DateFormat.LONG, new Locale("es", "MX"));

        contentStream.setFont(calibri, 9);
        contentStream.setNonStrokingColor(Color.BLACK);

        contentStream.setTextMatrix(new Matrix(1, 0, 0, 1, 465, 656));
        contentStream.showText(df.format(new Date()));

        contentStream.setFont(calibriBold, 11);

        contentStream.setTextMatrix(new Matrix(1, 0, 0, 1, 135, 585));
        contentStream.showText(c.razon_social);

        contentStream.setTextMatrix(new Matrix(1, 0, 0, 1, 120, (float) 572.5));
        if (c.walmart) {
            contentStream.showText(d.determinante + " " + d.unidad);
        } else if (d.sucursal.isEmpty() || d.sucursal.equalsIgnoreCase("")) {
            contentStream.endText();
            contentStream.addRect(30, 572, 150, 10);
            contentStream.setNonStrokingColor(Color.WHITE);
            contentStream.fill();
            contentStream.beginText();
            contentStream.setNonStrokingColor(Color.BLACK);
        } else {
            contentStream.showText(d.sucursal);
        }

        if (!c.walmart) {
            contentStream.setTextMatrix(new Matrix(1, 0, 0, 1, 120, 527));
            contentStream.showText(d.RFC);
            contentStream.setFont(calibri, 11);
            contentStream.setTextMatrix(new Matrix(1, 0, 0, 1, 72, 527));
            contentStream.showText("RFC: ");
            contentStream.setFont(calibriBold, 11);
        }
        /*
        if (c.walmart){
        contentStream.showText(p1.determinante + " " + d.unidad);
        } else if (d.sucursal.isEmpty() || d.sucursal.equalsIgnoreCase("")){
        contentStream.endText();
        contentStream.addRect(100, 590, 400, 20);
        contentStream.setNonStrokingColor(Color.WHITE);
        contentStream.fill();
        contentStream.beginText();
        contentStream.setNonStrokingColor(Color.BLACK);
        } else{
        contentStream.showText(d.sucursal);
        }
            
        */

        float charWidth = calibriBold.getStringWidth(d.direccion) / 1000 * 11;
        //System.out.println(charWidth + " " + d.direccion.length() + " " +  d.direccion);

        if (charWidth <= 400) {
            contentStream.setTextMatrix(new Matrix(1, 0, 0, 1, 120, 549));
            contentStream.showText(d.direccion);
        } else {
            contentStream.setTextMatrix(new Matrix(1, 0, 0, 1, 120, 552));
            contentStream.showText(d.direccion.substring(0, d.direccion.indexOf(" ", 82)));
            contentStream.setTextMatrix(new Matrix(1, 0, 0, 1, 120, 541));
            contentStream.showText(d.direccion.substring(d.direccion.indexOf(" ", 82) + 1, d.direccion.length()));
        }

        charWidth = calibriBold.getStringWidth(c.nombre_curso) / 1000 * 11;

        float xPosition = (pageWidth - charWidth) / 2;

        contentStream.setTextMatrix(new Matrix(1, 0, 0, 1, xPosition, 490));
        contentStream.showText(c.nombre_curso);

        contentStream.setTextMatrix(new Matrix(1, 0, 0, 1, 160, 465));
        contentStream.showText(c.fecha_certificado);

        contentStream.setTextMatrix(new Matrix(1, 0, 0, 1, 160, (float) 450.5));
        contentStream.showText(c.horas_texto);

        ListIterator<Participante> it = listaParticipantes.listIterator();

        float y = 0;
        while (it.hasNext()) {
            Participante p = it.next();

            if (p.determinante.equalsIgnoreCase(d.determinante)) {
                contentStream.setFont(calibri, 11);

                charWidth = calibri.getStringWidth(p.nombre + " " + p.apellidos) / 1000 * 11;
                //System.out.println(charWidth + " " + p.nombre + " " + p.apellidos);

                if (charWidth > 165) {
                    contentStream.setFont(calibri, 9);
                    contentStream.setTextMatrix(new Matrix(1, 0, 0, 1, 135, (float) 376.5 - y));
                    contentStream.showText(p.nombre + " " + p.apellidos);

                    contentStream.setFont(calibri, 11);

                } else {
                    contentStream.setTextMatrix(new Matrix(1, 0, 0, 1, 135, (float) 376.5 - y));
                    contentStream.showText(p.nombre + " " + p.apellidos);
                }

                charWidth = calibri.getStringWidth(p.area_puesto) / 1000 * 11;
                //System.out.println(charWidth + " " + p.area_puesto);

                if (charWidth > 112) {
                    contentStream.setFont(calibri, 9);
                    contentStream.setTextMatrix(new Matrix(1, 0, 0, 1, 360, (float) 376.5 - y));
                    contentStream.showText(p.area_puesto);

                } else {
                    contentStream.setTextMatrix(new Matrix(1, 0, 0, 1, 360, (float) 376.5 - y));
                    contentStream.showText(p.area_puesto);
                }

                y = y + (float) 12.7;

            }
        }

        contentStream.endText();
        float nameWidth;

        if (logoObject != null && !logoObject.isEmpty()) {
            contentStream.drawImage(logoObject, 30, 700, 156, 78);
        }
        if (firmaObject != null && !firmaObject.isEmpty()) {
            xPosition = (pageWidth - 100) / 2;
            contentStream.drawImage(firmaObject, xPosition, 55, 110, 42);

            contentStream.beginText();
            contentStream.setFont(calibriBold, 10);
            contentStream.setNonStrokingColor(Color.BLACK);

            nameWidth = calibriBold.getStringWidth(instructor) / 1000 * 10;
            xPosition = (pageWidth - nameWidth) / 2 + 9;
            contentStream.setTextMatrix(new Matrix(1, 0, 0, 1, xPosition, 55));
            contentStream.showText(instructor);

            if (instructor.equalsIgnoreCase("Manuel Anguiano Razn")) {
                nameWidth = calibriBold.getStringWidth(c.registro_manuel) / 1000 * 10;
                xPosition = (pageWidth - nameWidth) / 2 + 9;
                contentStream.setTextMatrix(new Matrix(1, 0, 0, 1, xPosition, 40));
                contentStream.showText(c.registro_manuel);
            } else if (instructor.equalsIgnoreCase("Ing. Jorge Antonio Razn Gutierrez")) {
                nameWidth = calibriBold.getStringWidth(c.registro_coco) / 1000 * 10;
                xPosition = (pageWidth - nameWidth) / 2 + 9;
                contentStream.setTextMatrix(new Matrix(1, 0, 0, 1, xPosition, 40));
                contentStream.showText(c.registro_coco);
            } else {
                nameWidth = calibriBold.getStringWidth(c.registro_jorge) / 1000 * 10;
                xPosition = (pageWidth - nameWidth) / 2 + 9;
                contentStream.setTextMatrix(new Matrix(1, 0, 0, 1, xPosition, 40));
                contentStream.showText(c.registro_jorge);
            }

            contentStream.endText();
        }

        // Make sure that the content stream is closed:
        contentStream.close();

        contentStream2.beginText();

        contentStream2.setFont(calibri, 11);
        contentStream2.setNonStrokingColor(Color.BLACK);

        contentStream2.setTextMatrix(new Matrix(1, 0, 0, 1, 465, 656));
        contentStream2.showText(df.format(new Date()));

        contentStream2.setFont(calibriBold, 11);

        contentStream2.setTextMatrix(new Matrix(1, 0, 0, 1, 135, 585));
        contentStream2.showText(c.razon_social);

        contentStream2.setTextMatrix(new Matrix(1, 0, 0, 1, 120, (float) 572.5));
        if (c.walmart) {
            contentStream2.showText(d.determinante + " " + d.unidad);
        } else {
            contentStream2.showText(d.sucursal);
            contentStream2.setTextMatrix(new Matrix(1, 0, 0, 1, 120, 527));
            contentStream2.showText(d.RFC);
            contentStream2.setFont(calibri, 11);
            contentStream2.setTextMatrix(new Matrix(1, 0, 0, 1, 73, 527));
            contentStream2.showText("RFC: ");
            contentStream2.setFont(calibriBold, 11);
        }

        charWidth = calibriBold.getStringWidth(d.direccion) / 1000 * 11;
        //System.out.println(charWidth + " " + d.direccion.length() + " " +  d.direccion);

        if (charWidth <= 400) {
            contentStream2.setTextMatrix(new Matrix(1, 0, 0, 1, 120, 549));
            contentStream2.showText(d.direccion);
        } else {
            contentStream2.setTextMatrix(new Matrix(1, 0, 0, 1, 120, 555));
            contentStream2.showText(d.direccion.substring(0, d.direccion.indexOf(" ", 82)));
            contentStream2.setTextMatrix(new Matrix(1, 0, 0, 1, 120, 540));
            contentStream2.showText(d.direccion.substring(d.direccion.indexOf(" ", 82) + 1, d.direccion.length()));
        }

        charWidth = calibriBold.getStringWidth(c.nombre_curso) / 1000 * 11;

        pageWidth = page2.getMediaBox().getWidth();
        xPosition = (pageWidth - charWidth) / 2;

        contentStream2.setTextMatrix(new Matrix(1, 0, 0, 1, xPosition, 490));
        contentStream2.showText(c.nombre_curso);

        contentStream2.setTextMatrix(new Matrix(1, 0, 0, 1, 160, 465));
        contentStream2.showText(c.fecha_certificado);

        contentStream2.setTextMatrix(new Matrix(1, 0, 0, 1, 160, (float) 450.5));
        contentStream2.showText(c.horas_texto);

        contentStream2.endText();

        if (logoObject != null && !logoObject.isEmpty()) {
            contentStream2.drawImage(logoObject, 30, 700, 156, 78);
        }
        if (firmaObject != null && !firmaObject.isEmpty()) {
            xPosition = (pageWidth - 100) / 2;
            contentStream2.drawImage(firmaObject, xPosition, 55, 110, 42);

            contentStream2.beginText();
            contentStream2.setFont(calibriBold, 10);
            contentStream2.setNonStrokingColor(Color.BLACK);

            nameWidth = calibriBold.getStringWidth(instructor) / 1000 * 10;
            xPosition = (pageWidth - nameWidth) / 2 + 9;
            contentStream2.setTextMatrix(new Matrix(1, 0, 0, 1, xPosition, 55));
            contentStream2.showText(instructor);

            if (instructor.equalsIgnoreCase("Manuel Anguiano Razn")) {
                nameWidth = calibriBold.getStringWidth(c.registro_manuel) / 1000 * 10;
                xPosition = (pageWidth - nameWidth) / 2 + 9;
                contentStream2.setTextMatrix(new Matrix(1, 0, 0, 1, xPosition, 40));
                contentStream2.showText(c.registro_manuel);
            } else if (instructor.equalsIgnoreCase("Ing. Jorge Antonio Razn Gutierrez")) {
                nameWidth = calibriBold.getStringWidth(c.registro_coco) / 1000 * 10;
                xPosition = (pageWidth - nameWidth) / 2 + 9;
                contentStream2.setTextMatrix(new Matrix(1, 0, 0, 1, xPosition, 40));
                contentStream2.showText(c.registro_coco);
            } else {
                nameWidth = calibriBold.getStringWidth(c.registro_jorge) / 1000 * 10;
                xPosition = (pageWidth - nameWidth) / 2 + 9;
                contentStream2.setTextMatrix(new Matrix(1, 0, 0, 1, xPosition, 40));
                contentStream2.showText(c.registro_jorge);
            }
            contentStream2.endText();
        }

        contentStream2.close();

        //"Capacitacion_BAE_Centro de Huinala_2631_MULTI_19ago2015"

        //Capacitacin + formato tienda + nombre sucursal + numero sucursal + nombre curso + ddmmaaaa

        Format formatter = new SimpleDateFormat("ddMMMYYYY", new Locale("es", "MX"));
        String formatedDate = formatter.format(c.fecha_inicio);

        String abrev = abreviaturas.get(c.nombre_curso);

        // Save the results and ensure that the document is properly closed:
        if (c.walmart) {
            document.save(savePath + File.separator + "Certificado_" + d.formato + "_" + d.unidad + "_"
                    + d.determinante + "_" + abrev + "_" + formatedDate + ".pdf");
            document.close();
            dosc.put(savePath + File.separator + "Certificado_" + d.formato + "_" + d.unidad + "_" + d.determinante
                    + "_" + abrev + "_" + formatedDate + ".pdf", d.determinante);
        } else {
            document.save(savePath + File.separator + "Certificado_" + d.determinante + "_" + abrev + "_"
                    + formatedDate + ".pdf");
            document.close();
            dosc.put(savePath + File.separator + "Certificado_" + d.determinante + "_" + abrev + "_" + formatedDate
                    + ".pdf", d.determinante);
        }

    }

From source file:ch.emad.schuetu.reports.pdf.PDFUtil.java

License:Apache License

public static List<byte[]> splitPDFToPNG(byte[] in) {

    List<byte[]> outlist = new ArrayList<>();
    PDDocument document = null;/*from   ww  w  .j  a  va  2  s . com*/
    try {
        InputStream ins = new ByteArrayInputStream(in);
        document = PDDocument.load(ins);
    } catch (IOException e) {
        e.printStackTrace();
    }
    List<PDPage> pdPages = document.getDocumentCatalog().getAllPages();
    int page = 0;
    for (PDPage pdPage : pdPages) {
        ++page;
        BufferedImage bim = null;
        try {
            bim = pdPage.convertToImage(BufferedImage.TYPE_INT_RGB, 300);
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            ByteArrayOutputStream outStr = new ByteArrayOutputStream();
            ImageIOUtil.writeImage(bim, "png", outStr, 300);
            outlist.add(outStr.toByteArray());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    try {
        document.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return outlist;
}

From source file:ch.vaudoise.vaapi.dctm.resource.root.LoadAndSetPDF.java

public static void setPDF(String nom, String prenom, String adresse, String telephone, String commentaire,
        String description) throws IOException {
    String adressePart1 = null;/*from ww w. jav a2s  .  c om*/
    String adressePart2 = null;
    String[] adresseTab = adressParser(adresse);
    if (adresseTab.length > 0) {
        adressePart1 = (adresseTab[0] + " " + adresseTab[1]);
        adressePart2 = (adresseTab[2] + " " + adresseTab[3]);
    }
    //Loading an existing document 
    File file = new File("C:\\Temp\\declaration.pdf");
    try (PDDocument document = PDDocument.load(file)) {

        PDDocumentCatalog docCatalog = document.getDocumentCatalog();
        PDAcroForm acroForm = docCatalog.getAcroForm();

        // Get field names
        List<PDField> fieldList = acroForm.getFields();

        // String the object array
        String[] fieldArray = new String[fieldList.size()];
        int i = 0;
        for (PDField sField : fieldList) {
            fieldArray[i] = sField.getFullyQualifiedName();
            i++;
        }

        // Loop through each field in the array and fill the blanks
        for (String f : fieldArray) {
            PDField field = acroForm.getField(f);
            //                System.out.println(f);
            switch (f) {
            case "Nom prnom ou raison sociale": {
                if (nom != null && nom != null) {
                    field.setValue(nom + " " + prenom);
                    break;
                } else {
                    field.setValue("Faten");
                    break;
                }
            }
            case "Adresse": {
                if (adressePart1 != null) {
                    field.setValue(adressePart1);
                    break;
                } else {
                    field.setValue("Rue des moulins 12");
                    break;
                }
            }
            case "NPA et localit": {
                if (adressePart2 != null) {
                    field.setValue(adressePart2);
                    break;
                } else {
                    field.setValue("1006 lausanne");
                    break;
                }
            }
            case "Tlphone et et fax": {
                if (telephone != null) {
                    field.setValue(telephone);
                    break;
                } else {
                    field.setValue("");
                    break;
                }
            }
            case "Email": {
                field.setValue("");
                break;
            }
            case "Nom de la personne de contact": {
                field.setValue(nom + " " + prenom);
                break;
            }
            case "CCP ou compte bancaire": {
                field.setValue("");
                break;
            }
            case "Si oui N TVA": {
                field.setValue("");
                break;
            }
            case "Si oui compagnie": {
                field.setValue("");
                break;
            }
            case "Numro de contrat dassurance ex1234562200": {
                field.setValue("1234564100");
                break;
            }
            case "Remarques": {
                if (commentaire != null) {
                    field.setValue(commentaire);
                    break;
                } else {
                    field.setValue("Rien  signaler ...");
                    break;
                }
            }
            case "Description de": {
                if (description != null) {
                    field.setValue(description);
                    break;
                } else {
                    field.setValue("Rien  signaler ...");
                    break;
                }
            }
            }
        }
        //Saving the document
        document.save("C:/temp/declarationRemplie.pdf");

        //Closing the document  
        document.close();
    }

}

From source file:checker.Checker.java

License:Open Source License

private String convert(String pathpdf) throws FileNotFoundException, IOException {
    File pdf = new File(pathpdf);
    File totxt = new File(pdf.getPath().substring(0, pdf.getPath().lastIndexOf('.')) + ".txt");

    PDFTextStripper stripper = new PDFTextStripper();
    PDDocument pd;/*  ww  w  . j a v  a2s .  c  om*/
    BufferedWriter wr;

    try {
        pd = PDDocument.load(pdf);

        wr = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(totxt)));
        stripper.writeText(pd, wr);
        if (pd != null) {
            pd.close();
        }
        // I use close() to flush the stream.
        wr.close();
    } catch (Exception e) {

        return "error reading pdf";
    }
    String text = "";
    BufferedReader br;
    br = new BufferedReader(new FileReader(totxt));
    String line;
    while ((line = br.readLine()) != null) {
        text += line;
        text += " ";
    }
    br.close();

    return text;

}

From source file:chiliad.parser.pdf.input.ClasspathSource.java

License:Apache License

@Override
public PDDocument loadDocument() throws IOException {
    return PDDocument.load(this.getClass().getClassLoader().getResourceAsStream(path));
}

From source file:chiliad.parser.pdf.input.FileSource.java

License:Apache License

@Override
public PDDocument loadDocument() throws IOException {
    return PDDocument.load(pdfFile);
}

From source file:com.aaasec.sigserv.csspsupport.pdfbox.CreateSignature.java

License:EUPL

/**
 * Signs the given pdf file.//from   w  ww . j  ava  2s  .  c  om
 */
public File signPDF() throws IOException, COSVisitorException, SignatureException {
    byte[] buffer = new byte[8 * 1024];
    File document = new File(model.getOriginalLoc());
    if (document == null || !document.exists()) {
        throw new RuntimeException("Document for signing does not exist");
    }

    File outputDocument = new File(model.getSignedLoc());
    FileInputStream fis = new FileInputStream(document);
    FileOutputStream fos = new FileOutputStream(outputDocument);

    int c;
    while ((c = fis.read(buffer)) != -1) {
        fos.write(buffer, 0, c);
    }
    fis.close();
    fis = new FileInputStream(outputDocument);

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

    // 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);
    if (model.getSignerName() != null) {
        signature.setName(model.getSignerName());
    }
    if (model.getSignerLocation() != null) {
        signature.setLocation(model.getSignerLocation());
    }
    if (model.getReasonForSigning() != null) {
        signature.setReason(model.getReasonForSigning());
    }

    // the signing date, needed for valid signature
    Calendar sigDate = Calendar.getInstance();
    sigDate.setTime(new Date(model.getSigningAndIdTime()));
    signature.setSignDate(sigDate);

    // register signature dictionary and sign interface
    if (model.getOptions() == null) {
        doc.addSignature(signature, this);
    } else {
        doc.addSignature(signature, this, model.getOptions());
    }

    // write incremental (only for signing purpose)
    PdfBoxSigUtil.saveIncremental(doc, fis, fos, model.getSigningAndIdTime());

    return outputDocument;
}