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

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

Introduction

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

Prototype

public void addPage(PDPage page) 

Source Link

Document

This will add a page to the document.

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);

        // 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();/*  w w w . j av a  2s .c om*/
        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);

        // 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();//from   w  ww  . j a v a 2 s.  co  m
        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:ch.dowa.jassturnier.pdf.PdfGenerator.java

public void exportTemplateWithTable(TableBuilder tableBuilder, String fileName, String title)
        throws IOException {
    String vLogoPath = !ResourceLoader.readProperty("LOGOPATH").isEmpty()
            ? ResourceLoader.readProperty("LOGOPATH")
            : null;//from w  w  w.jav  a  2 s.  c  o m

    final PDDocument document = new PDDocument();
    boolean firstPage = true;
    PDImageXObject image = null;
    float imageStartX = 0F;
    float imageStartY = 0F;
    PDRectangle imgSize = null;

    TableDrawer drawer = TableDrawer.builder().table(tableBuilder.build()).startX(docContentStartX())
            .startY(docContentStartY()).endY(documentPadding).build();

    if (vLogoPath != null) {
        image = PDImageXObject.createFromFile(vLogoPath, document);
        imgSize = getImageSizePdf(image);
        imageStartX = imgEndX() - imgSize.getWidth();
        imageStartY = imgEndY() - imgSize.getHeight();
    }

    do {
        PDPage page = new PDPage(pageFormat);
        document.addPage(page);
        try (PDPageContentStream contentStream = new PDPageContentStream(document, page)) {
            if (firstPage) {
                contentStream.beginText();
                contentStream.setFont(STANDART_FONT_BOLD, 14);
                contentStream.newLineAtOffset(docTitelStartX(), docTitelStartY());
                contentStream.showText(title);
                contentStream.endText();
                if (image != null) {
                    contentStream.drawImage(image, imageStartX, imageStartY, imgSize.getWidth(),
                            imgSize.getHeight());
                }
                drawer.startY(docContentSartFirsPageY());
                firstPage = false;
            }
            drawer.contentStream(contentStream).draw();
        }
        drawer.startY(docContentStartY());
    } while (!drawer.isFinished());

    document.save(fileName);
    document.close();
}

From source file:ch.dowa.jassturnier.pdf.PdfGenerator.java

public void exportTemplateWithTableMultiPage(HashMap<String, Table.TableBuilder> tableBuildersMap,
        String fileName) throws IOException {
    String vLogoPath = !ResourceLoader.readProperty("LOGOPATH").isEmpty()
            ? ResourceLoader.readProperty("LOGOPATH")
            : null;// w w  w. java  2s  .  co m
    PDDocument mainDoc = new PDDocument();
    PDFMergerUtility merger = new PDFMergerUtility();
    for (Map.Entry<String, TableBuilder> entry : tableBuildersMap.entrySet()) {
        String title = entry.getKey();
        TableBuilder tableBuilder = entry.getValue();

        final PDDocument documentPage = new PDDocument();
        boolean firstPage = true;
        PDImageXObject image = null;
        float imageStartX = 0F;
        float imageStartY = 0F;
        PDRectangle imgSize = null;

        TableDrawer drawer = TableDrawer.builder().table(tableBuilder.build()).startX(docContentStartX())
                .startY(docContentStartY()).endY(documentPadding).build();

        if (vLogoPath != null) {
            image = PDImageXObject.createFromFile(vLogoPath, documentPage);
            imgSize = getImageSizePdf(image);
            imageStartX = imgEndX() - imgSize.getWidth();
            imageStartY = imgEndY() - imgSize.getHeight();
        }

        do {
            PDPage page = new PDPage(pageFormat);
            documentPage.addPage(page);
            try (PDPageContentStream contentStream = new PDPageContentStream(documentPage, page)) {
                if (firstPage) {
                    contentStream.beginText();
                    contentStream.setFont(STANDART_FONT_BOLD, 14);
                    contentStream.newLineAtOffset(docTitelStartX(), docTitelStartY());
                    contentStream.showText(title);
                    contentStream.endText();
                    if (image != null) {
                        contentStream.drawImage(image, imageStartX, imageStartY, imgSize.getWidth(),
                                imgSize.getHeight());
                    }
                    drawer.startY(docContentSartFirsPageY());
                    firstPage = false;
                }
                drawer.contentStream(contentStream).draw();
            }
            drawer.startY(docContentStartY());
        } while (!drawer.isFinished());

        merger.appendDocument(mainDoc, documentPage);
    }

    mainDoc.save(fileName);
    mainDoc.close();
}

From source file:Clavis.Windows.WShedule.java

/**
 * @see/*from   w w  w  .ja  v  a  2  s.c o m*/
 * 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.display.DBDesktopPane.java

License:Open Source License

/**
 * Prints the current page to a pdf file
 *
 * @throws IOException if the file cannot be found or the pdf cannot be created
 *//*  w  w w  .ja va  2  s. co m*/
protected void printCurrentPageToPdf() throws IOException {
    io.clearActivePoints();
    ddf.updateAll(io.getActivePoints());
    String fileName = DBMenuBar.cleanseFileName(
            Main.getState().getCurrentFileName().substring(0, Main.getState().getCurrentFileName().length() - 6)
                    + ": " + Main.getCurrentPage().toDisplayString().replaceAll("\\|", "-"));
    File f = new File(Main.getFilePath());
    f.mkdirs();
    f = new File(Main.getFilePath() + fileName + ".pdf");

    BufferedImage bi = new BufferedImage(getSize().width, getSize().height, BufferedImage.TYPE_INT_ARGB);
    Graphics g = bi.createGraphics();
    paintComponent(g);
    g.dispose();

    PDDocument doc = null;

    try {
        doc = new PDDocument();
        boolean crop = true;
        State.print(field);
        for (Point p : Main.getCurrentPage().getDots().keySet())
            if (p.getX() < field.getWidth() * 0.1 + field.getX()
                    || p.getX() > field.getWidth() * 0.9 + field.getX()) {
                crop = false;
                break;
            }
        if (Main.getCurrentPage().getTextPoint().getX() < field.getWidth() * 0.1 + field.getX()
                || Main.getCurrentPage().getTextPoint().getX() + 100 > field.getWidth() * 0.9 + field.getX())
            crop = false;

        float scale = 1.0f;
        if (crop)
            scale = 0.8f;

        PDPage page = new PDPage(new PDRectangle((float) field.getWidth() * scale, (float) field.getHeight()));
        doc.addPage(page);
        PDImageXObject pdImage = LosslessFactory.createFromImage(doc, bi);
        PDPageContentStream contentStream = new PDPageContentStream(doc, page, AppendMode.APPEND, true);

        contentStream.drawImage(pdImage, -1 * field.x - (float) (((1 - scale) / 2.0f) * field.getWidth()),
                -1 * field.y, pdImage.getWidth(), pdImage.getHeight());

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

From source file:com.evanbelcher.DrillBook.display.DBDesktopPane.java

License:Open Source License

/**
 * Prints every page to a pdf file/*  ww w  .  jav a  2s.  c  om*/
 *
 * @throws IOException if the file cannot be found or the pdf cannot be created
 */
protected void printAllPagesToPdf() throws IOException {
    io.clearActivePoints();
    ddf.updateAll(io.getActivePoints());
    File f = new File(Main.getFilePath());
    f.mkdirs();
    String fileName = DBMenuBar.cleanseFileName(Main.getState().getCurrentFileName().substring(0,
            Main.getState().getCurrentFileName().length() - 6));

    f = new File(Main.getFilePath() + fileName + " full show" + ".pdf");

    boolean crop = true;
    a: for (int pageNum : Main.getPages().keySet()) {
        for (Point p : Main.getPages().get(pageNum).getDots().keySet()) {
            if (p.getX() < field.getWidth() * 0.1 + field.getX()
                    || p.getX() > field.getWidth() * 0.9 + field.getX()) {
                crop = false;
                break a;
            }
        }
        if (Main.getPages().get(pageNum).getTextPoint().getX() < field.getWidth() * 0.1 + field.getX()
                || Main.getPages().get(pageNum).getTextPoint().getX() + 100 > field.getWidth() * 0.9
                        + field.getX()) {
            crop = false;
            break;
        }
    }

    float scale = 1.0f;
    if (crop)
        scale = 0.8f;
    PDDocument doc = null;

    try {
        doc = new PDDocument();

        for (int i : Main.getPages().keySet()) {
            Main.setCurrentPage(i);

            BufferedImage bi = new BufferedImage(getSize().width, getSize().height,
                    BufferedImage.TYPE_INT_ARGB);
            Graphics g = bi.createGraphics();
            paintComponent(g);
            g.dispose();

            PDPage page = new PDPage(
                    new PDRectangle((float) field.getWidth() * scale, (float) field.getHeight()));
            doc.addPage(page);
            PDImageXObject pdImage = LosslessFactory.createFromImage(doc, bi);
            PDPageContentStream contentStream = new PDPageContentStream(doc, page, AppendMode.APPEND, true);

            contentStream.drawImage(pdImage, -1 * field.x - (float) (((1 - scale) / 2.0f) * field.getWidth()),
                    -1 * field.y, pdImage.getWidth(), pdImage.getHeight());

            contentStream.close();
        }
        doc.save(f);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } finally {
        if (doc != null)
            doc.close();
        pdf.updateAfterPrintAll();
    }
}

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

License:Open Source License

/**
 * Prints all dot sheets to pdf files/*from  w  w w  . j av  a 2  s  .c  o  m*/
 */
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;
}

From source file:com.fangxin365.core.utils.PDFMerger.java

License:Apache License

/**
 * append all pages from source to destination.
 * /*from   ww w . ja v a2  s  . c o m*/
 * @param destination
 *            the document to receive the pages
 * @param source
 *            the document originating the new pages
 * 
 * @throws IOException
 *             If there is an error accessing data from either document.
 */
public void appendDocument(PDDocument destination, PDDocument source) throws IOException {
    if (destination.isEncrypted()) {
        System.out.println("Error: destination PDF is encrypted, can't append encrypted PDF documents.");
    }
    if (source.isEncrypted()) {
        System.out.println("Error: source PDF is encrypted, can't append encrypted PDF documents.");
    }
    PDDocumentInformation destInfo = destination.getDocumentInformation();
    PDDocumentInformation srcInfo = source.getDocumentInformation();
    destInfo.getDictionary().mergeInto(srcInfo.getDictionary());

    PDDocumentCatalog destCatalog = destination.getDocumentCatalog();
    PDDocumentCatalog srcCatalog = source.getDocumentCatalog();

    // use the highest version number for the resulting pdf
    float destVersion = destination.getDocument().getVersion();
    float srcVersion = source.getDocument().getVersion();

    if (destVersion < srcVersion) {
        destination.getDocument().setVersion(srcVersion);
    }

    if (destCatalog.getOpenAction() == null) {
        destCatalog.setOpenAction(srcCatalog.getOpenAction());
    }

    // maybe there are some shared resources for all pages
    COSDictionary srcPages = (COSDictionary) srcCatalog.getCOSDictionary().getDictionaryObject(COSName.PAGES);
    COSDictionary srcResources = (COSDictionary) srcPages.getDictionaryObject(COSName.RESOURCES);
    COSDictionary destPages = (COSDictionary) destCatalog.getCOSDictionary().getDictionaryObject(COSName.PAGES);
    COSDictionary destResources = (COSDictionary) destPages.getDictionaryObject(COSName.RESOURCES);
    if (srcResources != null) {
        if (destResources != null) {
            destResources.mergeInto(srcResources);
        } else {
            destPages.setItem(COSName.RESOURCES, srcResources);
        }
    }

    PDFCloneUtility cloner = new PDFCloneUtility(destination);

    try {
        PDAcroForm destAcroForm = destCatalog.getAcroForm();
        PDAcroForm srcAcroForm = srcCatalog.getAcroForm();
        if (destAcroForm == null) {
            cloner.cloneForNewDocument(srcAcroForm);
            destCatalog.setAcroForm(srcAcroForm);
        } else {
            if (srcAcroForm != null) {
                mergeAcroForm(cloner, destAcroForm, srcAcroForm);
            }
        }
    } catch (Exception e) {
        // if we are not ignoring exceptions, we'll re-throw this
        if (!ignoreAcroFormErrors) {
            throw (IOException) e;
        }
    }

    COSArray destThreads = (COSArray) destCatalog.getCOSDictionary().getDictionaryObject(COSName.THREADS);
    COSArray srcThreads = (COSArray) cloner
            .cloneForNewDocument(destCatalog.getCOSDictionary().getDictionaryObject(COSName.THREADS));
    if (destThreads == null) {
        destCatalog.getCOSDictionary().setItem(COSName.THREADS, srcThreads);
    } else {
        destThreads.addAll(srcThreads);
    }

    PDDocumentNameDictionary destNames = destCatalog.getNames();
    PDDocumentNameDictionary srcNames = srcCatalog.getNames();
    if (srcNames != null) {
        if (destNames == null) {
            destCatalog.getCOSDictionary().setItem(COSName.NAMES, cloner.cloneForNewDocument(srcNames));
        } else {
            cloner.cloneMerge(srcNames, destNames);
        }

    }

    PDDocumentOutline destOutline = destCatalog.getDocumentOutline();
    PDDocumentOutline srcOutline = srcCatalog.getDocumentOutline();
    if (srcOutline != null) {
        if (destOutline == null) {
            PDDocumentOutline cloned = new PDDocumentOutline(
                    (COSDictionary) cloner.cloneForNewDocument(srcOutline));
            destCatalog.setDocumentOutline(cloned);
        } else {
            PDOutlineItem first = srcOutline.getFirstChild();
            if (first != null) {
                PDOutlineItem clonedFirst = new PDOutlineItem(
                        (COSDictionary) cloner.cloneForNewDocument(first));
                destOutline.appendChild(clonedFirst);
            }
        }
    }

    String destPageMode = destCatalog.getPageMode();
    String srcPageMode = srcCatalog.getPageMode();
    if (destPageMode == null) {
        destCatalog.setPageMode(srcPageMode);
    }

    COSDictionary destLabels = (COSDictionary) destCatalog.getCOSDictionary()
            .getDictionaryObject(COSName.PAGE_LABELS);
    COSDictionary srcLabels = (COSDictionary) srcCatalog.getCOSDictionary()
            .getDictionaryObject(COSName.PAGE_LABELS);
    if (srcLabels != null) {
        int destPageCount = destination.getNumberOfPages();
        COSArray destNums = null;
        if (destLabels == null) {
            destLabels = new COSDictionary();
            destNums = new COSArray();
            destLabels.setItem(COSName.NUMS, destNums);
            destCatalog.getCOSDictionary().setItem(COSName.PAGE_LABELS, destLabels);
        } else {
            destNums = (COSArray) destLabels.getDictionaryObject(COSName.NUMS);
        }
        COSArray srcNums = (COSArray) srcLabels.getDictionaryObject(COSName.NUMS);
        if (srcNums != null) {
            for (int i = 0; i < srcNums.size(); i += 2) {
                COSNumber labelIndex = (COSNumber) srcNums.getObject(i);
                long labelIndexValue = labelIndex.intValue();
                destNums.add(COSInteger.get(labelIndexValue + destPageCount));
                destNums.add(cloner.cloneForNewDocument(srcNums.getObject(i + 1)));
            }
        }
    }

    COSStream destMetadata = (COSStream) destCatalog.getCOSDictionary().getDictionaryObject(COSName.METADATA);
    COSStream srcMetadata = (COSStream) srcCatalog.getCOSDictionary().getDictionaryObject(COSName.METADATA);
    if (destMetadata == null && srcMetadata != null) {
        PDStream newStream = new PDStream(destination, srcMetadata.getUnfilteredStream(), false);
        newStream.getStream().mergeInto(srcMetadata);
        newStream.addCompression();
        destCatalog.getCOSDictionary().setItem(COSName.METADATA, newStream);
    }

    // finally append the pages
    @SuppressWarnings("unchecked")
    List<PDPage> pages = srcCatalog.getAllPages();
    Iterator<PDPage> pageIter = pages.iterator();
    while (pageIter.hasNext()) {
        PDPage page = pageIter.next();
        PDPage newPage = new PDPage((COSDictionary) cloner.cloneForNewDocument(page.getCOSDictionary()));
        newPage.setCropBox(page.findCropBox());
        newPage.setMediaBox(page.findMediaBox());
        newPage.setRotation(page.findRotation());
        destination.addPage(newPage);
    }
}

From source file:com.fileOperations.EmailBodyToPDF.java

/**
 * Places the text of the email into the PDF
 *
 * @param eml EmailBodyPDF/* w w w . j  ava  2s.  c  o m*/
 */
private static void createEmailBody(EmailBodyPDF eml) {
    PDDocument doc = null;
    PDPageContentStream contentStream = null;

    //Fonts used
    PDFont bodyTitleFont = PDType1Font.TIMES_BOLD;
    PDFont bodyFont = PDType1Font.TIMES_ROMAN;

    //Font Sizes
    float emailHeaderFontSize = 7;
    float leadingEmailHeader = 1.5f * emailHeaderFontSize;
    float bodyFontSize = 12;
    float leadingBody = 1.5f * bodyFontSize;

    try {
        //Create Document, Page, Margins.
        doc = new PDDocument();
        PDPage page = new PDPage();
        doc.addPage(page);
        contentStream = new PDPageContentStream(doc, page, AppendMode.APPEND, true, false);
        PDRectangle mediabox = page.getMediaBox();
        float margin = 72;
        float width = mediabox.getWidth() - 2 * margin;
        float startX = mediabox.getLowerLeftX() + margin;
        float startY = mediabox.getUpperRightY() - margin;
        float textYlocation = margin;

        //Set Line Breaks
        List<String> sentDateContent = PDFBoxTools.setLineBreaks(eml.getSentDate(), width, emailHeaderFontSize,
                bodyFont);
        List<String> recievedDateContent = PDFBoxTools.setLineBreaks(eml.getReceiveDate(), width,
                emailHeaderFontSize, bodyFont);
        List<String> toContent = PDFBoxTools.setLineBreaks(eml.getTo(), width, emailHeaderFontSize, bodyFont);
        List<String> fromContent = PDFBoxTools.setLineBreaks(eml.getFrom(), width, emailHeaderFontSize,
                bodyFont);
        List<String> ccContent = PDFBoxTools.setLineBreaks(eml.getCc(), width, emailHeaderFontSize, bodyFont);
        List<String> bccContent = PDFBoxTools.setLineBreaks(eml.getBcc(), width, emailHeaderFontSize, bodyFont);
        List<String> attachmentContent = PDFBoxTools.setLineBreaks(eml.getAttachments(), width,
                emailHeaderFontSize, bodyFont);
        List<String> subjectContent = PDFBoxTools.setLineBreaks(eml.getSubject(), width, bodyFontSize,
                bodyFont);
        List<String> bodyContent = PDFBoxTools.setLineBreaks(eml.getBody(), width, bodyFontSize, bodyFont);

        //Set Email Header
        contentStream.beginText();
        contentStream.setFont(bodyFont, emailHeaderFontSize);
        contentStream.setNonStrokingColor(Color.BLACK);
        contentStream.newLineAtOffset(startX, startY);

        //Set Date Sent
        if (!"".equals(eml.getSentDate())) {
            contentStream.setFont(bodyTitleFont, emailHeaderFontSize);
            contentStream.showText("Date Sent: ");
            contentStream.setFont(bodyFont, emailHeaderFontSize);
            contentStream.newLineAtOffset(0, -leadingEmailHeader);
            textYlocation += leadingEmailHeader;
            for (String line : sentDateContent) {
                if (textYlocation > (mediabox.getHeight() - (margin * 2) - leadingEmailHeader)) {
                    contentStream.endText();
                    contentStream.close();
                    textYlocation = 0;

                    page = new PDPage();
                    doc.addPage(page);
                    contentStream = new PDPageContentStream(doc, page, AppendMode.APPEND, true, false);

                    contentStream.beginText();
                    contentStream.setFont(bodyFont, emailHeaderFontSize);
                    contentStream.setNonStrokingColor(Color.BLACK);
                    contentStream.newLineAtOffset(startX, startY);
                }

                contentStream.showText(line);
                contentStream.newLineAtOffset(0, -leadingEmailHeader);
                textYlocation += leadingEmailHeader;
            }
        }

        //Set Date Received
        if (!"".equals(eml.getReceiveDate().trim())) {
            contentStream.setFont(bodyTitleFont, emailHeaderFontSize);
            contentStream.showText("Date Received: ");
            contentStream.setFont(bodyFont, emailHeaderFontSize);
            contentStream.newLineAtOffset(0, -leadingEmailHeader);
            textYlocation += leadingEmailHeader;
            for (String line : recievedDateContent) {
                if (textYlocation > (mediabox.getHeight() - (margin * 2) - leadingEmailHeader)) {
                    contentStream.endText();
                    contentStream.close();
                    textYlocation = 0;

                    page = new PDPage();
                    doc.addPage(page);
                    contentStream = new PDPageContentStream(doc, page, AppendMode.APPEND, true, false);

                    contentStream.beginText();
                    contentStream.setFont(bodyFont, emailHeaderFontSize);
                    contentStream.setNonStrokingColor(Color.BLACK);
                    contentStream.newLineAtOffset(startX, startY);
                }

                contentStream.showText(line);
                contentStream.newLineAtOffset(0, -leadingEmailHeader);
                textYlocation += leadingBody;
            }
        }
        contentStream.newLineAtOffset(0, -leadingBody);

        //Set From
        if (!"".equals(eml.getFrom().trim())) {
            contentStream.setFont(bodyTitleFont, emailHeaderFontSize);
            contentStream.showText("From: ");
            contentStream.setFont(bodyFont, emailHeaderFontSize);
            contentStream.newLineAtOffset(0, -leadingEmailHeader);
            textYlocation += leadingEmailHeader;
            for (String line : fromContent) {
                if (textYlocation > (mediabox.getHeight() - (margin * 2) - leadingEmailHeader)) {
                    contentStream.endText();
                    contentStream.close();
                    textYlocation = 0;

                    page = new PDPage();
                    doc.addPage(page);
                    contentStream = new PDPageContentStream(doc, page, AppendMode.APPEND, true, false);

                    contentStream.beginText();
                    contentStream.setFont(bodyFont, emailHeaderFontSize);
                    contentStream.setNonStrokingColor(Color.BLACK);
                    contentStream.newLineAtOffset(startX, startY);
                }
                contentStream.showText(line);
                contentStream.newLineAtOffset(0, -leadingEmailHeader);
                textYlocation += leadingEmailHeader;
            }
        }

        //Set To
        if (!"".equals(eml.getTo().trim())) {
            contentStream.setFont(bodyTitleFont, emailHeaderFontSize);
            contentStream.showText("To: ");
            contentStream.setFont(bodyFont, emailHeaderFontSize);
            contentStream.newLineAtOffset(0, -leadingEmailHeader);
            textYlocation += leadingEmailHeader;
            for (String line : toContent) {
                if (textYlocation > (mediabox.getHeight() - (margin * 2) - leadingEmailHeader)) {
                    contentStream.endText();
                    contentStream.close();
                    textYlocation = 0;

                    page = new PDPage();
                    doc.addPage(page);
                    contentStream = new PDPageContentStream(doc, page, AppendMode.APPEND, true, false);

                    contentStream.beginText();
                    contentStream.setFont(bodyFont, emailHeaderFontSize);
                    contentStream.setNonStrokingColor(Color.BLACK);
                    contentStream.newLineAtOffset(startX, startY);
                }
                contentStream.showText(line);
                contentStream.newLineAtOffset(0, -leadingEmailHeader);
                textYlocation += leadingEmailHeader;
            }
        }

        //Set CC
        if (!"".equals(eml.getCc().trim())) {
            contentStream.setFont(bodyTitleFont, emailHeaderFontSize);
            contentStream.showText("CC: ");
            contentStream.setFont(bodyFont, emailHeaderFontSize);
            contentStream.newLineAtOffset(0, -leadingEmailHeader);
            textYlocation += leadingEmailHeader;
            for (String line : ccContent) {
                if (textYlocation > (mediabox.getHeight() - (margin * 2) - leadingEmailHeader)) {
                    contentStream.endText();
                    contentStream.close();
                    textYlocation = 0;

                    page = new PDPage();
                    doc.addPage(page);
                    contentStream = new PDPageContentStream(doc, page, AppendMode.APPEND, true, false);

                    contentStream.beginText();
                    contentStream.setFont(bodyFont, emailHeaderFontSize);
                    contentStream.setNonStrokingColor(Color.BLACK);
                    contentStream.newLineAtOffset(startX, startY);
                }
                contentStream.showText(line);
                contentStream.newLineAtOffset(0, -leadingEmailHeader);
                textYlocation += leadingEmailHeader;
            }
        }

        //Set BCC
        if (!"".equals(eml.getBcc().trim())) {
            contentStream.setFont(bodyTitleFont, emailHeaderFontSize);
            contentStream.showText("BCC: ");
            contentStream.setFont(bodyFont, emailHeaderFontSize);
            contentStream.newLineAtOffset(0, -leadingEmailHeader);
            textYlocation += leadingEmailHeader;
            for (String line : bccContent) {
                if (textYlocation > (mediabox.getHeight() - (margin * 2) - leadingEmailHeader)) {
                    contentStream.endText();
                    contentStream.close();
                    textYlocation = 0;

                    page = new PDPage();
                    doc.addPage(page);
                    contentStream = new PDPageContentStream(doc, page, AppendMode.APPEND, true, false);

                    contentStream.beginText();
                    contentStream.setFont(bodyFont, emailHeaderFontSize);
                    contentStream.setNonStrokingColor(Color.BLACK);
                    contentStream.newLineAtOffset(startX, startY);
                }
                contentStream.showText(line);
                contentStream.newLineAtOffset(0, -leadingEmailHeader);
                textYlocation += leadingEmailHeader;
            }
        }

        //Set AttachmentList
        if (!"".equals(eml.getAttachments().trim())) {
            contentStream.setFont(bodyTitleFont, emailHeaderFontSize);
            contentStream.showText("Attachments: ");
            contentStream.setFont(bodyFont, emailHeaderFontSize);
            contentStream.newLineAtOffset(0, -leadingEmailHeader);
            textYlocation += leadingEmailHeader;
            for (String line : attachmentContent) {
                if (textYlocation > (mediabox.getHeight() - (margin * 2) - leadingEmailHeader)) {
                    contentStream.endText();
                    contentStream.close();
                    textYlocation = 0;

                    page = new PDPage();
                    doc.addPage(page);
                    contentStream = new PDPageContentStream(doc, page, AppendMode.APPEND, true, false);

                    contentStream.beginText();
                    contentStream.setFont(bodyFont, emailHeaderFontSize);
                    contentStream.setNonStrokingColor(Color.BLACK);
                    contentStream.newLineAtOffset(startX, startY);
                }
                contentStream.showText(line);
                contentStream.newLineAtOffset(0, -leadingEmailHeader);
                textYlocation += leadingEmailHeader;
            }
        }

        //Set Subject
        if (!"".equals(eml.getSubject().trim())) {
            contentStream.newLineAtOffset(0, -leadingBody);
            contentStream.newLineAtOffset(0, -leadingBody);
            contentStream.setFont(bodyTitleFont, bodyFontSize);
            contentStream.showText("Subject: ");
            contentStream.newLineAtOffset(0, -leadingBody);
            textYlocation += leadingBody;
            contentStream.setFont(bodyFont, bodyFontSize);
            for (String line : subjectContent) {
                if (textYlocation > (mediabox.getHeight() - (margin * 2) - leadingEmailHeader)) {
                    contentStream.endText();
                    contentStream.close();
                    textYlocation = 0;

                    page = new PDPage();
                    doc.addPage(page);
                    contentStream = new PDPageContentStream(doc, page, AppendMode.APPEND, true, false);

                    contentStream.beginText();
                    contentStream.setFont(bodyFont, emailHeaderFontSize);
                    contentStream.setNonStrokingColor(Color.BLACK);
                    contentStream.newLineAtOffset(startX, startY);
                }
                contentStream.showText(line);
                contentStream.newLineAtOffset(0, -leadingBody);
                textYlocation += leadingBody;
            }
        }
        if (!"".equals(eml.getBody().trim())) {
            // Set Email Body
            contentStream.newLineAtOffset(0, -leadingBody);
            contentStream.setFont(bodyTitleFont, bodyFontSize);
            contentStream.showText("Message: ");
            contentStream.setFont(bodyFont, bodyFontSize);
            contentStream.newLineAtOffset(0, -leadingBody);
            for (String line : bodyContent) {
                if (textYlocation > (mediabox.getHeight() - (margin * 2) - leadingBody)) {
                    contentStream.endText();
                    contentStream.close();
                    textYlocation = 0;

                    page = new PDPage();
                    doc.addPage(page);
                    contentStream = new PDPageContentStream(doc, page, AppendMode.APPEND, true, false);

                    contentStream.beginText();
                    contentStream.setFont(bodyFont, bodyFontSize);
                    contentStream.setNonStrokingColor(Color.BLACK);
                    contentStream.newLineAtOffset(startX, startY);
                }

                textYlocation += leadingBody;

                contentStream.showText(line);
                contentStream.newLineAtOffset(0, -leadingBody);
            }
            contentStream.endText();

        }
        contentStream.close();
        doc.save(eml.getFilePath() + eml.getFileName());
    } catch (IOException ex) {
        ExceptionHandler.Handle(ex);
    } finally {
        if (doc != null) {
            try {
                doc.close();
            } catch (IOException ex) {
                ExceptionHandler.Handle(ex);
            }
        }
    }
}