Example usage for org.apache.pdfbox.util Matrix Matrix

List of usage examples for org.apache.pdfbox.util Matrix Matrix

Introduction

In this page you can find the example usage for org.apache.pdfbox.util Matrix Matrix.

Prototype

public Matrix(float a, float b, float c, float d, float e, float f) 

Source Link

Document

Creates a transformation matrix with the given 6 elements.

Usage

From source file:cdiscisa.StreamUtil.java

private static void imprimirDiplomaArriba(Participante p1, Curso c, Directorio d, PDDocument document,
            PDPage page, PDFont calibri, PDFont calibriBold, PDFont pristina, PDImageXObject logoObject,
            PDImageXObject firmaObject, String instructor) throws IOException {

        COSDictionary pageDict = page.getCOSObject();
        COSDictionary newPageDict = new COSDictionary(pageDict);

        PDPage newPage = new PDPage(newPageDict);
        document.addPage(newPage);/* w  w  w.j av  a  2s.  c o  m*/

        // Start a new content stream which will "hold" the to be created content
        PDPageContentStream contentStream = new PDPageContentStream(document, newPage, true, true);

        float pageWidth = newPage.getMediaBox().getWidth();
        //float pageHeight = newPage.getMediaBox().getHeight();

        //System.out.println("pageWidth: " + pageWidth + "\npageHeight: " + pageHeight);

        // Print Name
        contentStream.beginText();
        contentStream.setFont(pristina, 28);
        //contentStream.setNonStrokingColor(0,112,192);
        contentStream.setNonStrokingColor(0, 128, 0);

        float nameWidth = pristina.getStringWidth(p1.nombre + " " + p1.apellidos) / 1000 * 28;

        //System.out.println(p1.nombre + " " + p1.apellidos + "::" + nameWidth);

        float xPosition;
        if (nameWidth < 470) {
            xPosition = (pageWidth - nameWidth) / 2;
            contentStream.setTextMatrix(new Matrix(1, 0, 0, 1, xPosition, 641));
            contentStream.showText(p1.nombre + " " + p1.apellidos);
        } else {
            contentStream.setFont(pristina, 22);
            nameWidth = pristina.getStringWidth(p1.nombre + " " + p1.apellidos) / 1000 * 22;
            xPosition = (pageWidth - nameWidth) / 2;
            contentStream.setTextMatrix(new Matrix(1, 0, 0, 1, xPosition, 641));
            contentStream.showText(p1.nombre + " " + p1.apellidos);
        }

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

        nameWidth = calibri.getStringWidth(c.razon_social) / 1000 * 15;
        //System.out.println("nameWidth: " + nameWidth);
        xPosition = (pageWidth - nameWidth) / 2;

        contentStream.setTextMatrix(new Matrix(1, 0, 0, 1, xPosition, 615));
        contentStream.showText(c.razon_social);

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

        contentStream.setTextMatrix(new Matrix(1, 0, 0, 1, 255, 593));
        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);
        }

        contentStream.setTextMatrix(new Matrix(1, 0, 0, 1, 210, (float) 538.5));
        contentStream.showText(c.horas_texto);

        contentStream.setTextMatrix(new Matrix(1, 0, 0, 1, 394, (float) 538.5));
        contentStream.showText(c.fecha_texto_diploma);

        contentStream.setFont(calibriBold, 10);

        float nameWidthStroked = calibri.getStringWidth(c.nombre_curso) / 1000 * 10;
        //System.out.println("nameWidth: " + nameWidthStroked);
        float strokePosition = (pageWidth - nameWidthStroked) / 2;
        contentStream.setTextMatrix(new Matrix(1, 0, 0, 1, strokePosition, 554));
        contentStream.showText(c.nombre_curso);

        contentStream.setFont(calibri, 8);
        contentStream.setNonStrokingColor(Color.GRAY);

        if (instructor.equalsIgnoreCase("Manuel Anguiano Razn")) {
            contentStream.setTextMatrix(new Matrix(1, 0, 0, 1, 170, 457));
            contentStream.showText("Registro STPS: GIS100219KK8003");
            contentStream.setTextMatrix(new Matrix(1, 0, 0, 1, 170, 447));
            contentStream.showText("Registro PC: " + c.registro_manuel);
            contentStream.setTextMatrix(new Matrix(1, 0, 0, 1, 170, 437));
            contentStream.showText("Registro PC: " + c.registro_jorge);

        } else if (instructor.equalsIgnoreCase("Ing. Jorge Antonio Razn Gutierrez")) {
            contentStream.setTextMatrix(new Matrix(1, 0, 0, 1, 170, 457));
            contentStream.showText("Registro STPS: GIS100219KK8003");
            contentStream.setTextMatrix(new Matrix(1, 0, 0, 1, 170, 447));
            contentStream.showText("Registro PC: " + c.registro_coco);
            contentStream.setTextMatrix(new Matrix(1, 0, 0, 1, 170, 437));
            contentStream.showText("Registro PC: " + c.registro_jorge);
        } else {
            contentStream.setTextMatrix(new Matrix(1, 0, 0, 1, 150, 457));
            contentStream.showText("Registro STPS: GIS100219KK8003");
            contentStream.setTextMatrix(new Matrix(1, 0, 0, 1, 150, 447));
            contentStream.showText("Registro STPS: RAGJ610813BIA005");
            contentStream.setTextMatrix(new Matrix(1, 0, 0, 1, 150, 437));
            contentStream.showText("Registro PC: " + c.registro_jorge);
            contentStream.setTextMatrix(new Matrix(1, 0, 0, 1, 270, 447));
            contentStream.showText("Registro PC: SPC-COAH-056-2015");
            contentStream.setTextMatrix(new Matrix(1, 0, 0, 1, 270, 437));
            contentStream.showText("Registro PC: CGPC-28/6016/026/NL-PS14");
        }
        // "Registro PC: DPC-ENL-CE-002/2015"
        // DPC-ENL-I-103_2015 "Ing. Jorge Antonio Razn Gutierrez"
        // DPC-ENL-I-056_2015 "Manuel Anguiano Razn"
        // "TSI. Jorge Antonio Razn Gil"

        contentStream.endText();

        contentStream.setStrokingColor(Color.BLACK);
        contentStream.setLineWidth(1);
        contentStream.moveTo(strokePosition, 552);
        contentStream.lineTo(strokePosition + nameWidthStroked + 6, 552);
        contentStream.stroke();

        if (logoObject != null && !logoObject.isEmpty()) {
            contentStream.drawImage(logoObject, 451, 700, 130, 65);
        }
        if (firmaObject != null && !firmaObject.isEmpty()) {
            contentStream.drawImage(firmaObject, 452, 440, 110, 42);

            contentStream.beginText();
            contentStream.setFont(calibri, 10);
            contentStream.setNonStrokingColor(Color.BLACK);
            nameWidth = calibri.getStringWidth(instructor) / 1000 * 10;
            xPosition = 505 - nameWidth / 2;

            contentStream.setTextMatrix(new Matrix(1, 0, 0, 1, xPosition, 445));
            contentStream.showText(instructor);
            contentStream.setTextMatrix(new Matrix(1, 0, 0, 1, 485, 435));
            contentStream.showText("Instructor");
            contentStream.endText();
        }
        /*
        System.out.println("logoWidth: " + logoObject.getWidth());
        System.out.println("logoHeight: " + logoObject.getHeight());
        System.out.println("firmaWidth: " + firmaObject.getWidth());
        System.out.println("firmaHeight: " + firmaObject.getHeight());
        */

        /*
        contentStream.addRect(50, 750, 500, 100);
        contentStream.setNonStrokingColor(Color.WHITE);
        contentStream.fill();
        contentStream.drawImage(logo, 430,700,150,75);
        contentStream.drawImage(firma, 93,239,72,29);
        */

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

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

    }

From source file:cdiscisa.StreamUtil.java

private static void imprimirDiplomaDoble(Participante p1, Participante p2, Curso c, Directorio d,
            PDDocument document, PDPage page, PDFont calibri, PDFont calibriBold, PDFont pristina,
            PDImageXObject logoObject, PDImageXObject firmaObject, String instructor) throws IOException {

        COSDictionary pageDict = page.getCOSObject();
        COSDictionary newPageDict = new COSDictionary(pageDict);

        PDPage newPage = new PDPage(newPageDict);
        document.addPage(newPage);/*from ww  w.  j a v  a 2  s. c  o m*/

        // Start a new content stream which will "hold" the to be created content
        PDPageContentStream contentStream = new PDPageContentStream(document, newPage, true, true);

        float pageWidth = newPage.getMediaBox().getWidth();
        //float pageHeight = newPage.getMediaBox().getHeight();

        //System.out.println("pageWidth: " + pageWidth + "\npageHeight: " + pageHeight);

        // Print UP Side

        contentStream.beginText();
        contentStream.setFont(pristina, 28);
        //contentStream.setNonStrokingColor(0,112,192);
        contentStream.setNonStrokingColor(0, 128, 0);

        float nameWidth = pristina.getStringWidth(p1.nombre + " " + p1.apellidos) / 1000 * 28;

        //System.out.println(p1.nombre + " " + p1.apellidos + "::" + nameWidth);

        float xPosition;
        if (nameWidth < 470) {
            xPosition = (pageWidth - nameWidth) / 2;
            contentStream.setTextMatrix(new Matrix(1, 0, 0, 1, xPosition, 641));
            contentStream.showText(p1.nombre + " " + p1.apellidos);
        } else {
            contentStream.setFont(pristina, 22);
            nameWidth = pristina.getStringWidth(p1.nombre + " " + p1.apellidos) / 1000 * 22;
            xPosition = (pageWidth - nameWidth) / 2;
            contentStream.setTextMatrix(new Matrix(1, 0, 0, 1, xPosition, 641));
            contentStream.showText(p1.nombre + " " + p1.apellidos);
        }

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

        nameWidth = calibri.getStringWidth(c.razon_social) / 1000 * 15;
        //System.out.println("nameWidth: " + nameWidth);
        xPosition = (pageWidth - nameWidth) / 2;

        contentStream.setTextMatrix(new Matrix(1, 0, 0, 1, xPosition, 615));
        contentStream.showText(c.razon_social);

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

        if (c.walmart) {
            contentStream.setTextMatrix(new Matrix(1, 0, 0, 1, 275, 593));
            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.setTextMatrix(new Matrix(1, 0, 0, 1, 275, 593));
            contentStream.showText(d.sucursal);
        }

        contentStream.setTextMatrix(new Matrix(1, 0, 0, 1, 210, (float) 538.5));
        contentStream.showText(c.horas_texto);

        contentStream.setTextMatrix(new Matrix(1, 0, 0, 1, 394, (float) 538.5));
        contentStream.showText(c.fecha_texto_diploma);

        contentStream.setFont(calibriBold, 10);

        float nameWidthStroked = calibri.getStringWidth(c.nombre_curso) / 1000 * 10;
        //System.out.println("nameWidth: " + nameWidthStroked);
        float strokePosition = (pageWidth - nameWidthStroked) / 2;
        contentStream.setTextMatrix(new Matrix(1, 0, 0, 1, strokePosition, 554));
        contentStream.showText(c.nombre_curso);

        contentStream.setFont(calibri, 8);
        contentStream.setNonStrokingColor(Color.GRAY);

        if (instructor.equalsIgnoreCase("Manuel Anguiano Razn")) {
            contentStream.setTextMatrix(new Matrix(1, 0, 0, 1, 170, 457));
            contentStream.showText("Registro STPS: GIS100219KK8003");
            contentStream.setTextMatrix(new Matrix(1, 0, 0, 1, 170, 447));
            contentStream.showText("Registro PC: " + c.registro_manuel);
            contentStream.setTextMatrix(new Matrix(1, 0, 0, 1, 170, 437));
            contentStream.showText("Registro PC: " + c.registro_jorge);

        } else if (instructor.equalsIgnoreCase("Ing. Jorge Antonio Razn Gutierrez")) {
            contentStream.setTextMatrix(new Matrix(1, 0, 0, 1, 170, 457));
            contentStream.showText("Registro STPS: GIS100219KK8003");
            contentStream.setTextMatrix(new Matrix(1, 0, 0, 1, 170, 447));
            contentStream.showText("Registro PC: " + c.registro_coco);
            contentStream.setTextMatrix(new Matrix(1, 0, 0, 1, 170, 437));
            contentStream.showText("Registro PC: " + c.registro_jorge);
        } else {
            contentStream.setTextMatrix(new Matrix(1, 0, 0, 1, 150, 457));
            contentStream.showText("Registro STPS: GIS100219KK8003");
            contentStream.setTextMatrix(new Matrix(1, 0, 0, 1, 150, 447));
            contentStream.showText("Registro STPS: RAGJ610813BIA005");
            contentStream.setTextMatrix(new Matrix(1, 0, 0, 1, 150, 437));
            contentStream.showText("Registro PC: " + c.registro_jorge);
            contentStream.setTextMatrix(new Matrix(1, 0, 0, 1, 270, 447));
            contentStream.showText("Registro PC: SPC-COAH-056-2015");
            contentStream.setTextMatrix(new Matrix(1, 0, 0, 1, 270, 437));
            contentStream.showText("Registro PC: CGPC-28/6016/026/NL-PS14");
        }

        contentStream.endText();

        contentStream.setStrokingColor(Color.BLACK);
        contentStream.setLineWidth(1);
        contentStream.moveTo(strokePosition, 552);
        contentStream.lineTo(strokePosition + nameWidthStroked + 6, 552);
        contentStream.stroke();

        if (logoObject != null && !logoObject.isEmpty()) {
            contentStream.drawImage(logoObject, 451, 700, 130, 65);
        }
        if (firmaObject != null && !firmaObject.isEmpty()) {
            contentStream.setStrokingColor(Color.BLACK);
            contentStream.drawImage(firmaObject, 452, 440, 110, 42);
            contentStream.beginText();
            contentStream.setFont(calibri, 10);
            nameWidth = calibri.getStringWidth(instructor) / 1000 * 10;
            xPosition = 505 - nameWidth / 2;

            contentStream.setTextMatrix(new Matrix(1, 0, 0, 1, xPosition, 445));
            contentStream.showText(instructor);
            contentStream.setTextMatrix(new Matrix(1, 0, 0, 1, 485, 435));
            contentStream.showText("Instructor");
            contentStream.endText();
        }

        // Print DOWN Side

        contentStream.beginText();
        contentStream.setFont(pristina, 28);
        //contentStream.setNonStrokingColor(0,112,192);
        contentStream.setNonStrokingColor(0, 128, 0);

        nameWidth = pristina.getStringWidth(p2.nombre + " " + p2.apellidos) / 1000 * 28;

        //System.out.println(p2.nombre + " " + p2.apellidos + "::" + nameWidth);

        if (nameWidth < 470) {
            xPosition = (pageWidth - nameWidth) / 2;
            contentStream.setTextMatrix(new Matrix(1, 0, 0, 1, xPosition, 262));
            contentStream.showText(p2.nombre + " " + p2.apellidos);
        } else {
            contentStream.setFont(pristina, 22);
            nameWidth = pristina.getStringWidth(p2.nombre + " " + p2.apellidos) / 1000 * 22;
            xPosition = (pageWidth - nameWidth) / 2;
            contentStream.setTextMatrix(new Matrix(1, 0, 0, 1, xPosition, 262));
            contentStream.showText(p2.nombre + " " + p2.apellidos);
        }

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

        nameWidth = calibri.getStringWidth(c.razon_social) / 1000 * 15;
        //System.out.println("nameWidth: " + nameWidth);
        xPosition = (pageWidth - nameWidth) / 2;

        contentStream.setTextMatrix(new Matrix(1, 0, 0, 1, xPosition, 235));
        contentStream.showText(c.razon_social);

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

        if (c.walmart) {
            contentStream.setTextMatrix(new Matrix(1, 0, 0, 1, 275, (float) 213.4));
            contentStream.showText(p2.determinante + " " + d.unidad);
        } else if (d.sucursal.isEmpty() || d.sucursal.equalsIgnoreCase("")) {
            contentStream.endText();
            contentStream.addRect(100, 211, 400, 20);
            contentStream.setNonStrokingColor(Color.WHITE);
            contentStream.fill();
            contentStream.beginText();
            contentStream.setNonStrokingColor(Color.BLACK);
        } else {
            contentStream.setTextMatrix(new Matrix(1, 0, 0, 1, 275, (float) 213.4));
            contentStream.showText(d.sucursal);
        }

        contentStream.setTextMatrix(new Matrix(1, 0, 0, 1, 210, 159));
        contentStream.showText(c.horas_texto);

        contentStream.setTextMatrix(new Matrix(1, 0, 0, 1, 394, 159));
        contentStream.showText(c.fecha_texto_diploma);

        contentStream.setFont(calibriBold, 10);

        nameWidthStroked = calibri.getStringWidth(c.nombre_curso) / 1000 * 10;
        //System.out.println("nameWidth: " + nameWidthStroked);
        strokePosition = (pageWidth - nameWidthStroked) / 2;
        contentStream.setTextMatrix(new Matrix(1, 0, 0, 1, strokePosition, 174));
        contentStream.showText(c.nombre_curso);

        contentStream.setFont(calibri, 8);
        contentStream.setNonStrokingColor(Color.GRAY);

        if (instructor.equalsIgnoreCase("Manuel Anguiano Razn")) {
            contentStream.setTextMatrix(new Matrix(1, 0, 0, 1, 170, 74));
            contentStream.showText("Registro STPS: GIS100219KK8003");
            contentStream.setTextMatrix(new Matrix(1, 0, 0, 1, 170, 64));
            contentStream.showText("Registro PC: " + c.registro_manuel);
            contentStream.setTextMatrix(new Matrix(1, 0, 0, 1, 170, 54));
            contentStream.showText("Registro PC: " + c.registro_jorge);

        } else if (instructor.equalsIgnoreCase("Ing. Jorge Antonio Razn Gutierrez")) {
            contentStream.setTextMatrix(new Matrix(1, 0, 0, 1, 170, 74));
            contentStream.showText("Registro STPS: GIS100219KK8003");
            contentStream.setTextMatrix(new Matrix(1, 0, 0, 1, 170, 64));
            contentStream.showText("Registro PC: " + c.registro_coco);
            contentStream.setTextMatrix(new Matrix(1, 0, 0, 1, 170, 54));
            contentStream.showText("Registro PC: " + c.registro_jorge);
        } else {
            contentStream.setTextMatrix(new Matrix(1, 0, 0, 1, 150, 74));
            contentStream.showText("Registro STPS: GIS100219KK8003");
            contentStream.setTextMatrix(new Matrix(1, 0, 0, 1, 150, 64));
            contentStream.showText("Registro STPS: RAGJ610813BIA005");
            contentStream.setTextMatrix(new Matrix(1, 0, 0, 1, 150, 54));
            contentStream.showText("Registro PC: " + c.registro_jorge);
            contentStream.setTextMatrix(new Matrix(1, 0, 0, 1, 270, 64));
            contentStream.showText("Registro PC: SPC-COAH-056-2015");
            contentStream.setTextMatrix(new Matrix(1, 0, 0, 1, 270, 54));
            contentStream.showText("Registro PC: CGPC-28/6016/026/NL-PS14");
        }

        contentStream.endText();

        contentStream.setStrokingColor(Color.BLACK);
        contentStream.moveTo(strokePosition, 172);
        contentStream.lineTo(strokePosition + nameWidthStroked + 6, 172);
        contentStream.stroke();

        if (logoObject != null && !logoObject.isEmpty()) {
            contentStream.drawImage(logoObject, 451, 320, 130, 65);
        }
        if (firmaObject != null && !firmaObject.isEmpty()) {
            contentStream.drawImage(firmaObject, 452, 62, 110, 42);

            contentStream.beginText();
            contentStream.setFont(calibri, 10);
            contentStream.setStrokingColor(Color.BLACK);
            nameWidth = calibri.getStringWidth(instructor) / 1000 * 10;

            xPosition = 505 - nameWidth / 2;

            contentStream.setTextMatrix(new Matrix(1, 0, 0, 1, xPosition, 67));

            contentStream.showText(instructor);
            contentStream.setTextMatrix(new Matrix(1, 0, 0, 1, 485, 57));
            contentStream.showText("Instructor");
            contentStream.endText();
        }
        // Make sure that the content stream is closed:
        contentStream.close();

        // Save the results and ensure that the document is properly closed:
        //document.save( "DiplomaSoloTest.pdf");
        //document.close();
    }

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 w w.  ja v a 2  s . co 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://from  ww  w. j  a  va2 s.c  o  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:GUI.Helper.PDFIOHelper.java

private static void drawReportHeaderFooter(PDDocument report, Project proj, boolean headerOnFirstPage) {

    int pageIdx = headerOnFirstPage ? 0 : 1;
    int marginOffset = 10;
    try {//from   w w w  .j  ava2  s  . co  m
        PDPageContentStream cs;
        for (int p = pageIdx; p < report.getNumberOfPages(); p++) {
            cs = new PDPageContentStream(report, report.getPage(p), true, false);
            cs.setFont(PDType1Font.TIMES_ROMAN, 11);
            cs.setNonStrokingColor(Color.BLACK);
            cs.beginText();
            String dateString = DateFormat.getDateInstance(DateFormat.MEDIUM)
                    .format(Calendar.getInstance().getTime());
            cs.setTextMatrix(new Matrix(1, 0, 0, 1, MARGIN_LEFT_X, MARGIN_TOP_Y + marginOffset));
            cs.showText(dateString);
            String projectString = "WZ ITS Tool Report: " + proj.getName();
            cs.setTextMatrix(new Matrix(1, 0, 0, 1,
                    MARGIN_RIGHT_X - (PDType1Font.TIMES_ROMAN.getStringWidth(projectString) / 1000 * 11),
                    MARGIN_TOP_Y + marginOffset));
            cs.showText(projectString);
            String pageNumString = "Page " + String.valueOf(p + 1) + " of "
                    + String.valueOf(report.getNumberOfPages());
            cs.setTextMatrix(new Matrix(1, 0, 0, 1,
                    MARGIN_LEFT_X + (MARGIN_RIGHT_X - MARGIN_LEFT_X) / 2.0f
                            - (PDType1Font.TIMES_ROMAN.getStringWidth(pageNumString) / 1000 * 11) / 2.0f,
                    MARGIN_BOTTOM_Y - marginOffset));
            cs.showText(pageNumString);
            cs.setTextMatrix(new Matrix(1, 0, 0, 1, MARGIN_LEFT_X + 20, MARGIN_BOTTOM_Y - marginOffset));
            cs.showText("WZ ITS Tool V" + WZITS_FX.VERSION);
            String analystAgencyStr = (proj.getAnalyst() != null ? proj.getAnalyst() : "")
                    + (proj.getAnalyst() != null && proj.getAgency() != null ? " / " : "")
                    + (proj.getAgency() != null ? proj.getAgency() : "");
            cs.setTextMatrix(new Matrix(1, 0, 0, 1,
                    MARGIN_RIGHT_X - (PDType1Font.TIMES_ROMAN.getStringWidth(analystAgencyStr) / 1000 * 11),
                    MARGIN_BOTTOM_Y - marginOffset));
            cs.showText(analystAgencyStr);
            cs.endText();

            BufferedImage logoWZITS = ImageIO.read(WZITS_FX.class.getResource("/GUI/Icon/wzits_icon_64.png"));
            //ColorConvertOp op = new ColorConvertOp(ColorSpace.getInstance(ColorSpace.CS_GRAY), null);
            //op.filter(logoWZITS, logoWZITS);
            cs.drawImage(LosslessFactory.createFromImage(report, logoWZITS), MARGIN_LEFT_X,
                    MARGIN_BOTTOM_Y - marginOffset - 3, 16, 16);
            cs.close();
        }
    } catch (IOException e) {
        System.out.println("Something went wrong");
    }

}

From source file:mil.tatrc.physiology.utilities.Excel2PDF.java

License:Apache License

public static void convert(String from, String to) throws IOException {
    FileInputStream xlFile = new FileInputStream(new File(from));
    // Read workbook into HSSFWorkbook
    XSSFWorkbook xlWBook = new XSSFWorkbook(xlFile);
    //We will create output PDF document objects at this point
    PDDocument pdf = new PDDocument();

    //pdf.addTitle();
    for (int s = 0; s < xlWBook.getNumberOfSheets(); s++) {
        XSSFSheet xlSheet = xlWBook.getSheetAt(s);
        Log.info("Processing Sheet : " + xlSheet.getSheetName());
        PDPage page = new PDPage(PDRectangle.A4);
        page.setRotation(90);//from w  ww.j a  v  a 2 s  .c  o  m
        pdf.addPage(page);
        PDRectangle pageSize = page.getMediaBox();
        PDPageContentStream contents = new PDPageContentStream(pdf, page);
        contents.transform(new Matrix(0, 1, -1, 0, pageSize.getWidth(), 0));// including a translation of pageWidth to use the lower left corner as 0,0 reference
        contents.setFont(PDType1Font.HELVETICA_BOLD, 16);
        contents.beginText();
        contents.newLineAtOffset(50, pageSize.getWidth() - 50);
        contents.showText(xlSheet.getSheetName());
        contents.endText();
        contents.close();

        int rows = xlSheet.getPhysicalNumberOfRows();
        for (int r = 0; r < rows; r++) {
            XSSFRow row = xlSheet.getRow(r);
            if (row == null)
                continue;
            int cells = row.getPhysicalNumberOfCells();
            if (cells == 0)
                continue;// Add an empty Roe

        }
    }

    /*    
        //We will use the object below to dynamically add new data to the table
        PdfPCell table_cell;
        //Loop through rows.
        while(rowIterator.hasNext()) 
        {
          Row row = rowIterator.next(); 
          Iterator<Cell> cellIterator = row.cellIterator();
          while(cellIterator.hasNext()) 
          {
            Cell cell = cellIterator.next(); //Fetch CELL
            switch(cell.getCellType()) 
            { //Identify CELL type
              //you need to add more code here based on
              //your requirement / transformations
              case Cell.CELL_TYPE_STRING:
    //Push the data from Excel to PDF Cell
    table_cell=new PdfPCell(new Phrase(cell.getStringCellValue()));
    //feel free to move the code below to suit to your needs
    my_table.addCell(table_cell);
    break;
            }
            //next line
          }
        }
    */
    pdf.save(new File(to));
    pdf.close();
    xlWBook.close();
    xlFile.close(); //close xls
}

From source file:org.esteco.jira.pdf.UsingTextMatrix.java

License:Apache License

/**
 * creates a sample document with some text using a text matrix.
 *
 * @param message The message to write in the file.
 * @param outfile The resulting PDF.//from   w  w  w . j av  a 2s  . c o  m
 * @throws IOException If there is an error writing the data.
 */
public void doIt(String message, String outfile) throws IOException {
    // the document
    PDDocument doc = null;
    try {
        doc = new PDDocument();

        // Page 1
        PDFont font = PDType1Font.HELVETICA;
        PDPage page = new PDPage(PDRectangle.A4);
        doc.addPage(page);
        float fontSize = 12.0f;

        PDRectangle pageSize = page.getMediaBox();
        float centeredXPosition = (pageSize.getWidth() - fontSize / 1000f) / 2f;
        float stringWidth = font.getStringWidth(message);
        float centeredYPosition = (pageSize.getHeight() - (stringWidth * fontSize) / 1000f) / 3f;

        PDPageContentStream contentStream = new PDPageContentStream(doc, page, AppendMode.OVERWRITE, false);
        contentStream.setFont(font, fontSize);
        contentStream.beginText();
        // counterclockwise rotation
        for (int i = 0; i < 8; i++) {
            contentStream.setTextMatrix(Matrix.getRotateInstance(i * Math.PI * 0.25, centeredXPosition,
                    pageSize.getHeight() - centeredYPosition));
            contentStream.showText(message + " " + i);
        }
        // clockwise rotation
        for (int i = 0; i < 8; i++) {
            contentStream.setTextMatrix(
                    Matrix.getRotateInstance(-i * Math.PI * 0.25, centeredXPosition, centeredYPosition));
            contentStream.showText(message + " " + i);
        }

        contentStream.endText();
        contentStream.close();

        // Page 2
        page = new PDPage(PDRectangle.A4);
        doc.addPage(page);
        fontSize = 1.0f;

        contentStream = new PDPageContentStream(doc, page, AppendMode.OVERWRITE, false);
        contentStream.setFont(font, fontSize);
        contentStream.beginText();

        // text scaling and translation
        for (int i = 0; i < 10; i++) {
            contentStream.setTextMatrix(new Matrix(12 + (i * 6), 0, 0, 12 + (i * 6), 100, 100 + i * 50));
            contentStream.showText(message + " " + i);
        }
        contentStream.endText();
        contentStream.close();

        // Page 3
        page = new PDPage(PDRectangle.A4);
        doc.addPage(page);
        fontSize = 1.0f;

        contentStream = new PDPageContentStream(doc, page, AppendMode.OVERWRITE, false);
        contentStream.setFont(font, fontSize);
        contentStream.beginText();

        int i = 0;
        // text scaling combined with rotation
        contentStream.setTextMatrix(new Matrix(12, 0, 0, 12, centeredXPosition, centeredYPosition * 1.5f));
        contentStream.showText(message + " " + i++);

        contentStream.setTextMatrix(new Matrix(0, 18, -18, 0, centeredXPosition, centeredYPosition * 1.5f));
        contentStream.showText(message + " " + i++);

        contentStream.setTextMatrix(new Matrix(-24, 0, 0, -24, centeredXPosition, centeredYPosition * 1.5f));
        contentStream.showText(message + " " + i++);

        contentStream.setTextMatrix(new Matrix(0, -30, 30, 0, centeredXPosition, centeredYPosition * 1.5f));
        contentStream.showText(message + " " + i++);

        contentStream.endText();
        contentStream.close();

        doc.save(outfile);
    } finally {
        if (doc != null) {
            doc.close();
        }
    }
}

From source file:org.nmrfx.processor.gui.graphicsio.PDFWriter.java

License:Open Source License

public void create(boolean landScape, double width, double height, String fileName) throws GraphicsIOException {
    // the document
    this.landScape = landScape;
    this.fileName = fileName;
    doc = new PDDocument();
    try {//from w  ww .  ja v  a  2s .  c  om
        PDPage page = new PDPage(PDRectangle.LETTER);
        doc.addPage(page);
        PDRectangle pageSize = page.getMediaBox();
        pageWidth = pageSize.getWidth();
        pageHeight = pageSize.getHeight();
        contentStream = new PDPageContentStream(doc, page, false, false);
        // add the rotation using the current transformation matrix
        // including a translation of pageWidth to use the lower left corner as 0,0 reference
        if (landScape) {
            page.setRotation(90);
            contentStream.transform(new Matrix(0, 1, -1, 0, pageWidth, 0));
        }
    } catch (IOException ioE) {
        throw new GraphicsIOException(ioE.getMessage());
    }
}

From source file:stepReport.reports.model.savePDFModel.java

public void savePDFSemanal(File file, String[][] matrizDados) {

    if (matrizDados == null)
        return;//from   w  ww. j  a  v a 2  s  .  com

    //Cria o documento
    PDDocument document = new PDDocument();

    //Vou criando as paginas dinamicamente de acordo com o numero de registros a serem impressos.
    //Para cada 25 registros, crio uma nova pagina
    //O valor de k vai ser atualizado durante o loop de impressao de registros,
    //assim como o loop de impressao de registro comeca a partir do valor de k
    int k = 1;
    int pagina = 0;
    while (k < matrizDados.length) {
        //Variavel com o numero da pagina
        pagina++;
        //Adiciona uma pagina
        PDPage page = new PDPage();
        //Configura o padrao de tamanho da pagina
        page.setMediaBox(PDRectangle.A4);
        //Configura a orientacao
        page.setRotation(90);
        //Adiciona a pagina ao documento
        document.addPage(page);
        PDFont font;
        //Obtem a largura da pagina
        float pageWidth = page.getMediaBox().getWidth();

        try {
            //abre o buffer pra edicao da pagina
            PDPageContentStream contentStream = new PDPageContentStream(document, page);
            //Gira a pagina em 90 graus
            contentStream.transform(new Matrix(0, 1, -1, 0, pageWidth, 0));

            PDImageXObject pdImage = PDImageXObject.createFromFile("./step2.png", document);

            contentStream.drawImage(pdImage, 30, 520);

            //Define a cor da letra
            contentStream.setNonStrokingColor(Color.BLACK);
            //Abre pra edicao escrita
            contentStream.beginText();

            //Configura a fonte de titulo e o tamanho no buffer
            font = PDType1Font.COURIER_BOLD;
            contentStream.setFont(font, 18);
            contentStream.setLeading(14.5f);

            contentStream.newLineAtOffset(250, 530);
            contentStream.showText("Resumo de Horas semanais");

            //Imprime o numero da pagina
            font = PDType1Font.COURIER;
            contentStream.setFont(font, 12);

            contentStream.newLineAtOffset(490, 0);
            contentStream.showText("Pag " + Integer.toString(pagina));

            //Define o ponto de partida em X e Y
            contentStream.newLineAtOffset(-700, -50);
            //Define a fonte do cabecalho
            font = PDType1Font.COURIER_BOLD;
            contentStream.setFont(font, 12);
            //carrega o cabecalho com nome, profissao, itera pra cada data da semana e depois o total
            String titulo = StringUtils.rightPad("Nome", 20) + StringUtils.rightPad("Profissao", 16);
            for (int i = 2; i < matrizDados[0].length; i++)
                titulo += matrizDados[0][i] + "  ";

            //Escreve o cabecalho
            contentStream.showText(titulo);
            //Troca a fonte pra normal
            font = PDType1Font.COURIER;
            contentStream.setFont(font, 12);
            //TODO criar loop duplo para criar pagina e depois imprimir o dado enquanto houver dados a serem impressos
            contentStream.newLine();

            //Para cada linha da matriz recebida, vou formatar os campos nome, profissao, cada data da semana e o total pra imprimir na linha
            //Tenho que comecar a partir de k porque pode nao ser a primeira pagina. 

            //Configuro o limite baseado se eu estou ou nao na ultima pagina
            int limite = (k + savePDFModel.REGISTROS_PAGINA < matrizDados.length - 1)
                    ? savePDFModel.REGISTROS_PAGINA
                    : matrizDados.length - k;

            for (int i = 0; i < limite; i++) {
                String nome = this.formatName(matrizDados[i + k][0]);
                String profissao = this.formatProfissao(matrizDados[i + k][1]);
                String linha = nome + profissao;
                for (int j = 2; j < matrizDados[i].length; j++)
                    linha += StringUtils.rightPad(matrizDados[i + k][j], 10);

                contentStream.showText(linha);
                contentStream.newLine();
            }
            k += limite;

            //Imprime o total em negrito quando chega no final
            System.out.println(k);
            if (k >= matrizDados.length) {
                font = PDType1Font.COURIER_BOLD;
                contentStream.setFont(font, 12);
                Double[] totais = new Double[matrizDados[0].length - 2];
                for (int i = 0; i < totais.length; i++)
                    totais[i] = 0.0;

                for (int i = 1; i < matrizDados.length; i++) {
                    for (int j = 2; j < matrizDados[i].length; j++) {
                        if (!matrizDados[i][j].equals(""))
                            totais[j - 2] += Double.parseDouble(matrizDados[i][j]);
                    }
                }
                String linhaTot = StringUtils.rightPad("Totais", 36);
                for (int i = 0; i < totais.length; i++) {
                    linhaTot += StringUtils.rightPad(totais[i].toString(), 10);
                }
                contentStream.showText(linhaTot);
                //Imprime a linha de assinatura
                this.signatureLine(contentStream);
            }
            contentStream.endText();
            contentStream.close();

        } catch (javax.imageio.IIOException ex) {
            JOptionPane.showMessageDialog(new JFrame(), "Imagem step2.png no encontrada");
            return;
        } catch (IOException ex) {
            Logger.getLogger(savePDFModel.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    try {
        //Esse save vai dentro do loop?
        document.save(file);
        document.close();
    } catch (IOException ex) {
        Logger.getLogger(savePDFModel.class.getName()).log(Level.SEVERE, null, ex);
    }
}