Example usage for org.apache.pdfbox.pdmodel PDPage getMediaBox

List of usage examples for org.apache.pdfbox.pdmodel PDPage getMediaBox

Introduction

In this page you can find the example usage for org.apache.pdfbox.pdmodel PDPage getMediaBox.

Prototype

public PDRectangle getMediaBox() 

Source Link

Document

A rectangle, expressed in default user space units, defining the boundaries of the physical medium on which the page is intended to be displayed or printed.

Usage

From source file:br.com.techne.gluonsoft.pdfgenerator.PDFGenerator.java

License:Apache License

/**
 * Add a new page to the PDF document/*from w  w w.j  av a 2s  .c  om*/
 * @param title
 * @param strLineContent Text to be added to the page
 * @throws IOException 
 */
public void addNewPage(String pageTitle, String[] strLineContent) throws IOException {
    PDPage page = new PDPage(PDRectangle.A4);
    this.addNewPage(page);

    PDRectangle rect = new PDRectangle();
    rect = page.getMediaBox();

    final float PAGE_MAX_WIDTH = rect.getWidth() - (2 * PAGE_MARGIN);
    final float PAGE_MAX_HEIGHT = rect.getHeight();

    final float PAGE_X_ALIGN_CENTER = PAGE_MAX_WIDTH / 2; // (PAGE_MAX_WIDTH + (2 * PAGE_MARGIN)) / 2 ;

    PDPageContentStream pageContent = new PDPageContentStream(this.getPdfDocument(), page); // Page's Stream

    int line = 1;

    // Add the page's title
    if (pageTitle != null) {
        pageContent.beginText();
        pageContent.setFont(FONT_BOLD, FONT_SIZE_DEFAULT);
        pageContent.newLineAtOffset(PAGE_X_ALIGN_CENTER, PAGE_INITIAL_Y_POSITION); // CENTER
        pageContent.showText(pageTitle); // Title
        pageContent.endText();

        pageContent.beginText();
        pageContent.setFont(FONT_BOLD, FONT_SIZE_DEFAULT);
        pageContent.newLineAtOffset(PAGE_MARGIN, PAGE_INITIAL_Y_POSITION - 10 * (line++)); // pageContent.newLineAtOffset(PAGE_MARGIN, PAGE_INITIAL_Y_POSITION);
        pageContent.showText(""); // Line after title
        pageContent.endText();
    }

    // Add the page's content
    if (strLineContent != null && strLineContent.length > 0) {
        for (String strLine : strLineContent) {
            ArrayList<String> newLines = autoBreakLineIntoOthers(strLine, _MAX_LINE_CHARACTERS); // Break a text line into others lines to fit into page width.

            for (String str : newLines) {
                pageContent.beginText();
                pageContent.setFont(FONT_PLAIN, FONT_SIZE_DEFAULT);
                pageContent.newLineAtOffset(PAGE_MARGIN, PAGE_INITIAL_Y_POSITION - 10 * (line++));
                pageContent.showText(str);
                pageContent.endText();
            }
        }
    }

    pageContent.close();
}

From source file:br.com.techne.gluonsoft.pdfgenerator.PDFGenerator.java

License:Apache License

/**
 * Create a page with table./*from www  .j a  v  a 2  s  .c o m*/
 * @param tableTitle Table Title
 * @param tableColumnsName   Array of Strings with table columns titles.
 * @param strTableContent Array of Strings with the table data.
 * @throws IOException
 */
@SuppressWarnings("deprecation")
public void addNewTable(String tableTitle, ArrayList<String> tableColumnsName,
        ArrayList<String> strTableContent) throws IOException {
    PDRectangle rectLandscapeOrientation = new PDRectangle(PDRectangle.A4.getHeight(),
            PDRectangle.A4.getWidth()); // Changed width to height to get Landscape Orientation

    PDPage tablePage = new PDPage(PDRectangle.A4);
    PDRectangle rect = tablePage.getMediaBox();

    this.getPdfDocument().addPage(tablePage);

    PDPageContentStream pageContent = new PDPageContentStream(this.getPdfDocument(), tablePage);

    final float margin = 20f;
    final int tableRows = strTableContent != null ? strTableContent.size() : 0;
    final int tableColumns = tableColumnsName != null ? tableColumnsName.size() : 0;
    final float rowHeigth = 20f;
    final float tableWidth = rect.getWidth() - (2 * margin);
    final float tableHeight = rowHeigth * tableRows;
    final float tableColWidth = tableWidth / (float) tableColumns;
    final float tableCelMargin = 5f;

    // Draw the lines
    float nextY = PAGE_INITIAL_Y_POSITION;
    for (int r = 0; r <= tableRows; r++) {
        pageContent.drawLine(margin, nextY, margin + tableWidth, nextY);
        nextY -= rowHeigth;
    }

    // Draw the columns
    float nextX = margin;
    for (int i = 0; i <= tableColumns; i++) {
        pageContent.drawLine(nextX, PAGE_INITIAL_Y_POSITION, nextX, PAGE_INITIAL_Y_POSITION - tableHeight);
        nextX += tableColWidth;
    }

    pageContent.setFont(FONT_BOLD, FONT_SIZE_DEFAULT); // Initial Font for the columns' titles

    float textPosX = margin + tableCelMargin;
    float textPosY = PAGE_INITIAL_Y_POSITION - 15;

    // Title
    float centerX = tableWidth / 2 - (margin * 2);
    float xAlignLeft = margin;
    pageContent.beginText();
    pageContent.newLineAtOffset(xAlignLeft, PAGE_INITIAL_Y_POSITION + 5);
    pageContent.showText(tableTitle);
    pageContent.endText();

    // Columns' names
    for (int i = 0; i < tableColumnsName.size(); i++) {
        String columnName = tableColumnsName.get(i);
        System.out.println(columnName);

        pageContent.beginText();
        pageContent.newLineAtOffset(textPosX, textPosY);
        pageContent.showText(columnName);
        pageContent.endText();
        textPosX += tableColWidth;
    }

    //       textPosY -= rowHeigth;
    //       textPosX = margin + tableCelMargin;

    // Cels' content (Add the text)
    int actualCol = 0;
    pageContent.setFont(FONT_PLAIN, FONT_SIZE_DEFAULT);
    for (int i = 0; i < strTableContent.size(); i++) {
        if (actualCol % tableColumns == 0) {
            actualCol = 0;
            textPosY -= rowHeigth;
            textPosX = margin + tableCelMargin;
        }

        String celText = strTableContent.get(i);
        System.out.println(celText);
        pageContent.beginText();
        pageContent.newLineAtOffset(textPosX, textPosY);
        pageContent.showText(celText);
        pageContent.endText();
        textPosX += tableColWidth;

        actualCol++;
    }

    pageContent.close();
}

From source file:br.com.techne.gluonsoft.pdfgenerator.PDFGenerator.java

License:Apache License

/**
 * Create a page with table.//w  ww  .ja va 2 s.  co  m
 * @param tableTitle Table Title
 * @param strTableContent   Array of Strings, where the column's titles goes into the first array line and the data goes into others lines.
 * @throws IOException
 */
@SuppressWarnings("deprecation")
public void addNewTable(String tableTitle, String[][] strTableContent) throws IOException {
    PDPage tablePage = new PDPage(PDRectangle.A4);

    PDRectangle rect = new PDRectangle();
    rect = tablePage.getMediaBox();

    this.getPdfDocument().addPage(tablePage);

    PDPageContentStream pageContent = new PDPageContentStream(this.getPdfDocument(), tablePage);

    final float margin = 20f;
    final int tableRows = strTableContent.length;
    final int tableColumns = strTableContent[0].length;
    final float rowHeigth = 20f;
    final float tableWidth = rect.getWidth() - (2 * margin);
    final float tableHeight = rowHeigth * tableRows;
    final float tableColWidth = tableWidth / (float) tableColumns;
    final float tableCelMargin = 5f;

    // Draw the lines
    float nextY = PAGE_INITIAL_Y_POSITION;
    for (int r = 0; r <= tableRows; r++) {
        pageContent.drawLine(margin, nextY, margin + tableWidth, nextY);
        nextY -= rowHeigth;
    }

    // Draw the columns
    float nextX = margin;
    for (int i = 0; i <= tableColumns; i++) {
        pageContent.drawLine(nextX, PAGE_INITIAL_Y_POSITION, nextX, PAGE_INITIAL_Y_POSITION - tableHeight);
        nextX += tableColWidth;
    }

    pageContent.setFont(FONT_BOLD, FONT_SIZE_DEFAULT); // Fonte inicial para o ttulo das colunas

    float textPosX = margin + tableCelMargin;
    float textPosY = PAGE_INITIAL_Y_POSITION - 15;

    // Title
    float centerX = tableWidth / 2 - (margin * 2);
    pageContent.beginText();
    pageContent.newLineAtOffset(centerX, PAGE_INITIAL_Y_POSITION + 5);
    pageContent.showText(tableTitle);
    pageContent.endText();

    // Cels' content (Add the text)
    for (int l = 0; l < strTableContent.length; l++) {
        for (int c = 0; c < strTableContent[l].length; c++) {
            String celText = strTableContent[l][c];

            if (l > 0) {
                pageContent.setFont(FONT_PLAIN, FONT_SIZE_DEFAULT);
            }

            pageContent.beginText();
            pageContent.newLineAtOffset(textPosX, textPosY);
            pageContent.showText(celText);
            pageContent.endText();
            textPosX += tableColWidth;
        }

        textPosY -= rowHeigth;
        textPosX = margin + tableCelMargin;
    }

    pageContent.close();
}

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);/*from   w w  w. j  a  va2  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 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  w w w.  ja va2s .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 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 ww.  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.rasc.downloadchart.DownloadChartServlet.java

License:Apache License

private static void handlePdf(HttpServletResponse response, byte[] imageData, Integer width, Integer height,
        String filename, PdfOptions options) throws IOException {

    response.setContentType("application/pdf");
    response.setHeader("Content-Disposition", "attachment; filename=\"" + filename + ".pdf\";");

    try (PDDocument document = new PDDocument()) {
        PDRectangle format = PDPage.PAGE_SIZE_A4;
        if (options != null) {
            if ("A3".equals(options.format)) {
                format = PDPage.PAGE_SIZE_A3;
            } else if ("A5".equals(options.format)) {
                format = PDPage.PAGE_SIZE_A5;
            } else if ("Letter".equals(options.format)) {
                format = PDPage.PAGE_SIZE_LETTER;
            } else if ("Legal".equals(options.format)) {
                format = new PDRectangle(215.9f * MM_TO_UNITS, 355.6f * MM_TO_UNITS);
            } else if ("Tabloid".equals(options.format)) {
                format = new PDRectangle(279 * MM_TO_UNITS, 432 * MM_TO_UNITS);
            } else if (options.width != null && options.height != null) {
                Float pdfWidth = convertToPixel(options.width);
                Float pdfHeight = convertToPixel(options.height);
                if (pdfWidth != null && pdfHeight != null) {
                    format = new PDRectangle(pdfWidth, pdfHeight);
                }//from   w w w  .  j  a  va2s .  c o  m
            }
        }

        PDPage page = new PDPage(format);

        if (options != null && "landscape".equals(options.orientation)) {
            page.setRotation(90);
        }

        document.addPage(page);

        BufferedImage originalImage = ImageIO.read(new ByteArrayInputStream(imageData));

        try (PDPageContentStream contentStream = new PDPageContentStream(document, page)) {

            PDPixelMap ximage = new PDPixelMap(document, originalImage);

            Dimension newDimension = calculateDimension(originalImage, width, height);
            int imgWidth = ximage.getWidth();
            int imgHeight = ximage.getHeight();
            if (newDimension != null) {
                imgWidth = newDimension.width;
                imgHeight = newDimension.height;
            }

            Float border = options != null ? convertToPixel(options.border) : null;
            if (border == null) {
                border = 0.0f;
            }

            AffineTransform transform;

            if (page.getRotation() == null) {
                float scale = (page.getMediaBox().getWidth() - border * 2) / imgWidth;
                if (scale < 1.0) {
                    transform = new AffineTransform(imgWidth, 0, 0, imgHeight, border,
                            page.getMediaBox().getHeight() - border - imgHeight * scale);

                    transform.scale(scale, scale);
                } else {
                    transform = new AffineTransform(imgWidth, 0, 0, imgHeight, border,
                            page.getMediaBox().getHeight() - border - imgHeight);
                }

            } else {
                float scale = (page.getMediaBox().getHeight() - border * 2) / imgWidth;
                if (scale < 1.0) {
                    transform = new AffineTransform(imgHeight, 0, 0, imgWidth, imgHeight * scale + border,
                            border);

                    transform.scale(scale, scale);
                } else {
                    transform = new AffineTransform(imgHeight, 0, 0, imgWidth, imgHeight + border, border);
                }

                transform.rotate(1.0 * Math.PI / 2.0);
            }

            contentStream.drawXObject(ximage, transform);

        }

        try {
            document.save(response.getOutputStream());
        } catch (COSVisitorException e) {
            throw new IOException(e);
        }
    }
}

From source file:chiliad.parser.pdf.extractor.image.operator.ShowImage.java

License:Apache License

@Override
public void process(PDFOperator operator, List<COSBase> arguments) throws IOException {
    final ImageExtractor extractor = (ImageExtractor) context;
    final COSName objectName = (COSName) arguments.get(0);
    final Map<String, PDXObject> xobjects = context.getResources().getXObjects();
    final PDXObject xobject = (PDXObject) xobjects.get(objectName.getName());
    if (xobject instanceof PDXObjectImage) {
        System.out.println("ImageName=" + ((COSName) arguments.get(0)).getName());
        PDXObjectImage image = (PDXObjectImage) xobject;
        Matrix ctmNew = extractor.getGraphicsState().getCurrentTransformationMatrix();
        PDPage page = extractor.getCurrentPage();
        double pageHeight = page.getMediaBox().getHeight();
        extractor.addPDFImage(new PDFImage(((COSName) arguments.get(0)).getName(), image, ctmNew, pageHeight));
    } else if (xobject instanceof PDXObjectForm) {
        // save the graphics state
        extractor.getGraphicsStack().push((PDGraphicsState) extractor.getGraphicsState().clone());
        PDPage page = extractor.getCurrentPage();

        PDXObjectForm form = (PDXObjectForm) xobject;
        COSStream invoke = (COSStream) form.getCOSObject();
        PDResources pdResources = form.getResources();
        if (pdResources == null) {
            pdResources = page.findResources();
        }/*  www .j  a va 2s .co m*/
        // if there is an optional form matrix, we have to
        // map the form space to the user space
        Matrix matrix = form.getMatrix();
        if (matrix != null) {
            Matrix xobjectCTM = matrix.multiply(extractor.getGraphicsState().getCurrentTransformationMatrix());
            extractor.getGraphicsState().setCurrentTransformationMatrix(xobjectCTM);
        }
        extractor.processSubStream(page, pdResources, invoke);

        // restore the graphics state
        extractor.setGraphicsState((PDGraphicsState) extractor.getGraphicsStack().pop());
    }
}

From source file:Clavis.Windows.WShedule.java

/**
 * @see//from  w ww.  ja v a 2s  . com
 * http://fahdshariff.blogspot.pt/2010/10/creating-tables-with-pdfbox.html
 */
private static void drawTable(PDDocument doc, String[][] content, String titulo, String subtitulo,
        String subsubtitulo) throws IOException {

    float y = 680f;
    float margin = 60f;
    final int rows = content.length;
    final int cols = content[0].length;
    final float rowHeight = 20f;
    int maximolinhas = (int) (y / (rowHeight + 2));

    float tableHeight;
    int paginas = 0;
    int linhas;

    if (rows < maximolinhas) {
        linhas = rows;
        paginas++;
    } else {
        linhas = maximolinhas;
        int auxiliar = 0;
        while (auxiliar < rows) {
            paginas++;
            auxiliar += maximolinhas;
        }
    }
    final float cellMargin = 5f;
    float tamanhotexto = 12f;
    float tamanhotexto2 = 8f;
    float dimensao = 0f;
    float dimensao2 = 0f;
    PDFont font = PDType1Font.TIMES_ROMAN;
    for (String[] content1 : content) {
        dimensao = font.getStringWidth(content1[0]) / 1000 * tamanhotexto2;
        if (dimensao > 222.0f) {
            String nome = content1[0];
            String[] texto = nome.split(" ");
            nome = nome.replace(texto[0], "");
            nome = nome.replace(texto[texto.length - 1], "");
            int i = 1;
            while (dimensao > 222.0f) {
                if (texto[i].length() > 2) {
                    nome = nome.replace(texto[i], texto[i].charAt(0) + ".");
                } else {
                    nome = nome.replace(texto[i], "");
                }
                dimensao = font.getStringWidth(texto[0] + nome + texto[texto.length - 1]) / 1000
                        * tamanhotexto2;
                i++;
            }
            content1[0] = texto[0] + nome + texto[texto.length - 1];
        }
        dimensao2 = font.getStringWidth(content1[3]) / 1000 * tamanhotexto2 + 10;
        if (dimensao2 > 180.0f) {
            String nome = content1[3];
            String[] texto = nome.split(" ");
            nome = nome.replace(texto[0], "");
            nome = nome.replace(texto[texto.length - 1], "");
            int i = 1;
            while (dimensao2 > 180.0f) {
                if (texto[i].length() > 2) {
                    nome = nome.replace(texto[i], texto[i].charAt(0) + ".");
                } else {
                    nome = nome.replace(texto[i], "");
                }
                dimensao2 = font.getStringWidth(texto[0] + nome + texto[texto.length - 1]) / 1000
                        * tamanhotexto2;
                i++;
            }
            content1[3] = texto[0] + nome + texto[texto.length - 1];
        }
    }
    int passagem = 0;
    int passagemdepagina = 0;
    float tableWidth;
    if (dimensao < 100) {
        dimensao = 100;
    }
    if (dimensao2 < 100) {
        dimensao2 = 100;
    }
    float firstcolWidth = dimensao + 10 * cellMargin;
    float lastcolWidth = dimensao2 + 10 * cellMargin;
    float colWidth;
    PDPageContentStream contentStream = null;
    while (passagem < paginas) {
        PDPage page = new PDPage();
        doc.addPage(page);
        try {
            contentStream = new PDPageContentStream(doc, page);
        } catch (IOException ex) {
            Logger.getLogger(WShedule.class.getName()).log(Level.SEVERE, null, ex);
        }
        if (contentStream != null) {
            contentStream.setFont(font, tamanhotexto);
            tableWidth = page.getMediaBox().getWidth() - (2 * margin);
            colWidth = (tableWidth - firstcolWidth - lastcolWidth) / (float) (cols - 2);
            if (passagem == 0) {
                contentStream.beginText();
                float posicao = margin + (tableWidth / 2)
                        - ((font.getStringWidth(titulo) / 1000 * tamanhotexto) / 2);
                contentStream.newLineAtOffset(posicao, page.getMediaBox().getHeight() - 40);
                contentStream.showText(titulo);
                contentStream.endText();
                contentStream.beginText();
                posicao = margin + (tableWidth / 2)
                        - ((font.getStringWidth(subtitulo) / 1000 * tamanhotexto) / 2);
                contentStream.newLineAtOffset(posicao, page.getMediaBox().getHeight() - 60);
                contentStream.showText(subtitulo);
                contentStream.endText();
                contentStream.beginText();
                posicao = margin + (tableWidth / 2)
                        - ((font.getStringWidth(subsubtitulo) / 1000 * tamanhotexto) / 2);
                contentStream.newLineAtOffset(posicao, page.getMediaBox().getHeight() - 80);
                contentStream.showText(subsubtitulo);
                contentStream.endText();
            }
            if (passagem == 1) {
                y += 40;
            }
            float nexty = y;
            contentStream.setFont(font, tamanhotexto2);

            for (int i = 0; i <= linhas; i++) {
                if (i < linhas) {
                    if ((i % 2) == 0) {
                        contentStream.setNonStrokingColor(200, 200, 200);
                        contentStream.addRect(margin, nexty - rowHeight, tableWidth, rowHeight);
                        contentStream.fill();
                    }
                }
                contentStream.setNonStrokingColor(0, 0, 0);
                contentStream.moveTo(margin, nexty);
                contentStream.lineTo(margin + tableWidth, nexty);
                contentStream.stroke();
                nexty -= rowHeight;
            }

            //draw the columns
            float nextx = margin;
            for (int i = 0; i <= cols; i++) {
                contentStream.moveTo(nextx, y);
                if (linhas < maximolinhas) {
                    tableHeight = rowHeight * linhas;
                } else {
                    tableHeight = rowHeight * maximolinhas;
                }
                contentStream.lineTo(nextx, y - tableHeight);
                contentStream.stroke();
                switch (i) {
                case 0:
                    nextx += firstcolWidth;
                    break;
                case 3:
                    nextx += lastcolWidth;
                    break;
                default:
                    nextx += colWidth;
                    break;
                }
            }

            float textx = margin;
            float texty = y - 15;
            float ttexto;
            boolean primeira = true;
            for (int i = 0; i < linhas; i++) {
                for (int j = 0; j < content[i + passagemdepagina].length; j++) {
                    String text = content[i + passagemdepagina][j];
                    ttexto = font.getStringWidth(text) / 1000 * tamanhotexto2;
                    if (j == 0) {
                        ttexto = textx + ((firstcolWidth / 2) - (ttexto / 2));
                    } else if (j < 3) {
                        ttexto = textx + ((colWidth / 2) - (ttexto / 2));
                    } else {
                        ttexto = textx + ((lastcolWidth / 2) - (ttexto / 2));
                    }
                    contentStream.beginText();
                    contentStream.newLineAtOffset(ttexto, texty);
                    contentStream.showText(text);
                    contentStream.endText();
                    if (j == 0) {
                        textx += firstcolWidth;
                    } else {
                        textx += colWidth;
                    }
                }
                texty -= rowHeight;
                textx = margin;
            }
            contentStream.beginText();
            contentStream.newLineAtOffset((tableWidth / 2) + margin, 40);
            contentStream.showText("" + (passagem + 1));
            contentStream.endText();
            contentStream.close();
        }
        passagem++;
        maximolinhas = (int) (y / (rowHeight + 1));
        linhas = rows - (maximolinhas * passagem);
        if (linhas > maximolinhas) {
            linhas = maximolinhas;
        }
        passagemdepagina = maximolinhas * passagem;
    }

}

From source file:com.evanbelcher.DrillBook.DotSheetMaker.java

License:Open Source License

/**
 * Prints all dot sheets to pdf files//from ww w  . j av  a2 s .  c  om
 */
private void printAllToPdf() throws IOException {
    printing = true;
    String folder = DBMenuBar.cleanseFileName(Main.getState().getCurrentFileName().substring(0,
            Main.getState().getCurrentFileName().length() - 6)) + " Dot Sheets/";
    File f = new File(Main.getFilePath() + folder);
    f.mkdirs();
    PDDocument doc = null;

    String[] chars = new String[26];
    for (int i = 0; i < 26; i++)
        chars[i] = String.valueOf((char) (65 + i));

    try {
        for (String letter : chars) {
            doc = new PDDocument();

            String fileName = Main.getState().getCurrentFileName().substring(0,
                    Main.getState().getCurrentFileName().length() - 6) + " "
                    + DBMenuBar.cleanseFileName(letter);
            f = new File(Main.getFilePath() + folder + fileName + " dot sheet.pdf");

            ArrayList<String> list = new ArrayList<>(map.keySet());
            list.sort(nameComparator);

            for (String dotName : list) {
                if (dotName.replaceAll("[0-9]", "").equals(letter)) {
                    int i = 0;

                    PDPage page = new PDPage();
                    doc.addPage(page);

                    PDFont font = PDType1Font.HELVETICA_BOLD;
                    PDPageContentStream contentStream = new PDPageContentStream(doc, page);
                    contentStream.beginText();
                    contentStream.setFont(font, 10.0f);
                    contentStream.newLineAtOffset(10, page.getMediaBox().getHeight() - 20);
                    contentStream.showText(Main.getState().getCurrentFileName().substring(0,
                            Main.getState().getCurrentFileName().length() - 6));
                    contentStream.endText();

                    contentStream.beginText();
                    contentStream.setFont(font, 12.0f);
                    contentStream.newLineAtOffset(page.getMediaBox().getWidth() * 0.3f,
                            page.getMediaBox().getHeight() - 20);
                    contentStream.showText(dotName);
                    contentStream.endText();

                    contentStream.beginText();
                    contentStream.setFont(font, 10.0f);
                    contentStream.newLineAtOffset(page.getMediaBox().getWidth() * 0.6f,
                            page.getMediaBox().getHeight() - 20);
                    contentStream.showText("Name: ______________________________");
                    contentStream.endText();
                    contentStream.close();

                    float margin = 10;
                    float tableWidth = page.getMediaBox().getWidth() - (2 * margin);
                    float yStartNewPage = page.getMediaBox().getHeight() - (3 * margin);
                    //noinspection UnnecessaryLocalVariable
                    float yStart = yStartNewPage;
                    float bottomMargin = 70;

                    BaseTable table = new BaseTable(yStart, yStartNewPage, bottomMargin, tableWidth, margin,
                            doc, page, true, true);
                    //Create Header row
                    Row<PDPage> headerRow = table.createRow(15f);
                    Cell<PDPage> headerCell = headerRow.createCell(100 / 7f, "Set #");
                    headerCell.setAlign(HorizontalAlignment.CENTER);
                    headerCell.setFillColor(HEADER_COLOR);
                    headerRow.createCell(300 / 7f, "Horizontal").copyCellStyle(headerCell);
                    headerRow.createCell(300 / 7f, "Vertical").copyCellStyle(headerCell);

                    table.addHeaderRow(headerRow);
                    for (int pageNum : new TreeSet<>(map.get(dotName).keySet())) {
                        String text = map.get(dotName).get(pageNum);
                        String[] lines = text.split("\\n");
                        String line1 = lines[0].replace("Horizontal - ", "");
                        String line2 = lines[1].replace("Vertical - ", "");

                        Row<PDPage> row = table.createRow(10f);
                        Cell<PDPage> cell = row.createCell(100 / 7f, pageNum + "");
                        cell.setAlign(HorizontalAlignment.CENTER);
                        cell.setFillColor(openingSets.contains(pageNum) ? OPENING_SET_COLOR : NORMAL_COLOR);
                        row.createCell(300 / 7f, line1).copyCellStyle(cell);
                        row.createCell(300 / 7f, line2).copyCellStyle(cell);

                        if (++i >= 35) {
                            table.draw();
                            page = new PDPage();
                            doc.addPage(page);
                            table = new BaseTable(yStart, yStartNewPage, bottomMargin, tableWidth, margin, doc,
                                    page, true, true);
                            //Create Header row
                            headerRow = table.createRow(15f);
                            headerCell = headerRow.createCell(100 / 7f, "Set #");
                            headerCell.setAlign(HorizontalAlignment.CENTER);
                            headerCell.setFillColor(HEADER_COLOR);
                            headerRow.createCell(300 / 7f, "Horizontal").copyCellStyle(headerCell);
                            headerRow.createCell(300 / 7f, "Vertical").copyCellStyle(headerCell);
                            table.addHeaderRow(headerRow);

                            i -= 35;
                        }
                    }
                    table.draw();

                }
            }
            if (doc.getNumberOfPages() > 0)
                doc.save(f);
            else
                doc.close();
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } finally {
        if (doc != null)
            doc.close();
    }
    printing = false;
}