Example usage for org.apache.pdfbox.pdmodel PDPageContentStream PDPageContentStream

List of usage examples for org.apache.pdfbox.pdmodel PDPageContentStream PDPageContentStream

Introduction

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

Prototype

public PDPageContentStream(PDDocument doc, PDAppearanceStream appearance) throws IOException 

Source Link

Document

Create a new appearance stream.

Usage

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

License:Apache License

/**
 * Add a new page to the PDF document/*  w ww .j  a va 2 s .  c o  m*/
 * @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.//  www .  java2  s .  c  om
 * @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./*from www .  ja  v  a 2 s  .c  o 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:Bulletin.Bulletin2.java

private PDPageContentStream newPage() {
    PDPageContentStream cos = null;//from   w ww.j  av  a2s .c  o  m
    try {
        this.page = new PDPage();
        this.rect = page.getMediaBox();

        this.left = leftMargin;
        this.right = rect.getWidth() - leftMargin;
        this.width = right - left;
        this.height = rect.getHeight();
        this.center = width / 2 + left;
        this.midStart = left + leftColWidth;
        this.midEnd = right - rightColWidth;
        this.midColWidth = width - rightColWidth - leftColWidth;

        this.Y = rect.getHeight() - topMargin;

        cos = new PDPageContentStream(document, page);
    } catch (IOException ex) {
        Logger.getLogger(Bulletin2.class.getName()).log(Level.SEVERE, null, ex);
    }
    return cos;
}

From source file:Bulletin.myPdf.java

public void newPage() {
    System.out.println("new page");
    this.page = new PDPage(PDRectangle.A4);
    this.rect = page.getMediaBox();
    this.left = leftMargin;
    this.right = rect.getWidth() - leftMargin;
    this.width = right - left;
    this.height = rect.getHeight();
    this.Y = rect.getHeight() - topMargin;
    this.top = this.Y;

    try {//from www.j ava 2  s.c  o m
        this.cos = new PDPageContentStream(this.document, this.page);
    } catch (IOException ex) {
        Logger.getLogger(myPdf.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:Bulletin.test.java

public static void test2() {
    try {/*  w  ww.  j av a2 s. c o  m*/
        PDDocument document = new PDDocument();
        PDPage page = new PDPage(PDRectangle.A4);
        PDPageContentStream cos = null;
        try {
            cos = new PDPageContentStream(document, page);
        } catch (IOException ex) {
            Logger.getLogger(test.class.getName()).log(Level.SEVERE, null, ex);
        }

        float X = 501.4f;
        float Y = 556.0f;
        //            String text = "HALLO";
        //            String text = "HALLO#HOE#GAAT#HET";
        //            String text = "HALLO#HOE#GAAT";
        String text = "Non atteints";
        int rh = 10;

        cos.moveTo(X, Y - 50);
        cos.lineTo(X, Y + 50);
        cos.stroke();
        cos.moveTo(X - 50, Y);
        cos.lineTo(X + 50, Y);
        cos.stroke();

        cos.beginText();
        cos.setFont(PDType1Font.HELVETICA, 6);
        float dtw = 0.5f * getTextWidth(PDType1Font.HELVETICA, text, 6);
        float dth = 0.0f * getFontHeight(PDType1Font.HELVETICA, 6);
        int nbLines = text.split("#").length;

        Y += 0.5f * (nbLines - 1) * rh;

        for (String line : text.split("#")) {
            Matrix M = Matrix.getTranslateInstance(X, Y);
            M.concatenate(Matrix.getRotateInstance(Math.toRadians(0), 0, 0));
            M.concatenate(Matrix.getTranslateInstance(-dtw, -dth));
            cos.setTextMatrix(M);
            cos.showText(line);
            Y -= rh;
        }
        cos.close();
        document.addPage(page);
        document.save("/tmp/test.pdf");
        document.close();

    } catch (IOException ex) {
        Logger.getLogger(test.class.getName()).log(Level.SEVERE, null, ex);
    }
}

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;//  w ww.  j  av  a  2s.co  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;/*from w ww. j  a va 2  s .c o 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:ch.eggbacon.app.pdf.PDFCreator.java

License:Open Source License

public PDPageContentStream addPage(int pageNumber) throws IOException {
    PDPage page = new PDPage(PDFConstants.PAPER_SIZE);
    doc.addPage(page);/*from  w  ww . j  a  va 2  s  . co m*/
    PDPageContentStream contentStream = new PDPageContentStream(doc, page);
    //drawHeader(contentStream);
    drawFooter(pageNumber, contentStream);

    return contentStream;
}

From source file:Clavis.Windows.WShedule.java

/**
 * @see// w w  w. j  ava2 s .  co  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;
    }

}