Example usage for com.lowagie.text.pdf PdfPTable writeSelectedRows

List of usage examples for com.lowagie.text.pdf PdfPTable writeSelectedRows

Introduction

In this page you can find the example usage for com.lowagie.text.pdf PdfPTable writeSelectedRows.

Prototype

public float writeSelectedRows(int rowStart, int rowEnd, float xPos, float yPos, PdfContentByte canvas) 

Source Link

Document

Writes the selected rows to the document.

Usage

From source file:it.eng.spagobi.engines.documentcomposition.exporterUtils.PdfCreator.java

License:Mozilla Public License

public FileOutputStream createPdfFile(FileOutputStream fileOutputStream,
        Map<String, DocumentContainer> documentsMap, boolean defaultStyle)
        throws MalformedURLException, IOException, DocumentException {

    logger.debug("IN");

    Document document = new Document(PageSize.A4.rotate());
    Rectangle rect = document.getPageSize();
    docWidth = rect.getWidth();//from   w ww  . j a v a2s .  com
    docHeight = rect.getHeight();

    logger.debug("document size width: " + docWidth + " height: " + docHeight);

    //PdfWriter writer=PdfWriter.getInstance(document,new FileOutputStream("C:/comp/SpagoBIProva.pdf"));
    PdfWriter writer = PdfWriter.getInstance(document, fileOutputStream);
    document.open();

    int documentsNumber = documentsMap.keySet().size();
    int columnnsNumber = 2;

    if (defaultStyle == true) {
        logger.debug("use default style");
        int cellsCounter = 0;

        PdfPTable table = new PdfPTable(columnnsNumber);
        table.setWidthPercentage(100);

        for (Iterator iterator = documentsMap.keySet().iterator(); iterator.hasNext();) {
            String label = (String) iterator.next();
            DocumentContainer docContainer = documentsMap.get(label);
            byte[] content = docContainer.getContent();
            if (content != null) {
                Image img = null;
                try {
                    img = Image.getInstance(content);
                    table.addCell(img);
                } catch (Exception e) {
                    logger.debug("Trying to evaluate response as a PDF file... ");
                    table.addCell("");
                    //                  try {
                    //                     PdfReader reader = new PdfReader(content);
                    //                     PdfImportedPage page = writer.getImportedPage(reader, 1);
                    //                     writer.addPage(page);
                    //                     table.addCell("");
                    //                  } catch (Exception x) {
                    //                     logger.error("Error in inserting image for document " + label, e);
                    //                     logger.error("Error in inserting pdf file for document " + label, x);
                    //                     table.addCell("");
                    //                  }
                }
            }
            cellsCounter++;
        }

        // if cell counter is not pair make it pair
        if (cellsCounter % 2 != 0) {
            table.addCell("");
        }
        document.add(table);

    } else { // ************* NO DEFAULT STYLE *****************
        logger.debug("No default style");

        // I want to calculate total height of scaled heights!!
        //int totalScaledHeight=calculateTotaleScaledHeights(documentsMap, defaultStyle);

        // run on all documents
        for (Iterator iterator = documentsMap.keySet().iterator(); iterator.hasNext();) {
            String label = (String) iterator.next();
            logger.debug("document with label " + label);

            DocumentContainer docContainer = documentsMap.get(label);
            MetadataStyle style = docContainer.getStyle();

            // one table for each image, set at absolute position
            PdfPTable table = new PdfPTable(1);

            // width and height specified for the container by style attribute
            int widthStyle = style.getWidth();
            int heightStyle = style.getHeight();
            logger.debug("style for document width: " + widthStyle + " height: " + heightStyle);

            // width and height for the table scaled to the document size
            int tableWidth = calculatePxSize(docWidth, widthStyle, videoWidth);
            int tableHeight = calculatePxSize(docHeight, heightStyle, videoHeight);

            logger.debug("table for document width: " + tableWidth + " height: " + tableHeight);

            // x and y position as specified for the container by the style attribute
            int yStyle = style.getY();
            int xStyle = style.getX();
            // width and height scaled to the document size
            int xPos = (calculatePxPos(docWidth, xStyle, videoWidth));
            int yPos = (int) docHeight - (calculatePxPos(docHeight, yStyle, videoHeight));
            logger.debug("Table position at x: " + xPos + " y: " + yPos);

            // get the image
            byte[] content = docContainer.getContent();
            if (content != null) {
                Image img = null;
                try {
                    img = Image.getInstance(content);
                } catch (Exception e) {
                    logger.debug("Trying to evaluate response as a PDF file... ");
                    try {
                        PdfReader reader = new PdfReader(content);
                        PdfContentByte cb = writer.getDirectContent();
                        PdfImportedPage page = writer.getImportedPage(reader, 1);
                        float[] tm = getTransformationMatrix(page, xPos, yPos, tableWidth, tableHeight);
                        cb.addTemplate(page, tm[0], tm[1], tm[2], tm[3], tm[4], tm[5]);
                    } catch (Exception x) {
                        logger.error("Error in inserting image for document " + label, e);
                        logger.error("Error in inserting pdf file for document " + label, x);
                    }
                    continue;
                }

                //if it is a REPORT and has more than one page, too large, you have to resize the image, but how to understand it?
                // if image size is more than double of the container size cut the first part,otherwise scale it
                if (docContainer.getDocumentType().equals("REPORT")) {
                    boolean cutImageWIdth = isToCutWidth(img, tableWidth);
                    boolean cutImageHeight = isToCutHeight(img, tableWidth);

                    if (cutImageWIdth == true || cutImageHeight == true) {
                        logger.debug(
                                "Report will be cut to width " + tableWidth + " and height " + tableHeight);
                        try {
                            img = cutImage(content, cutImageHeight, cutImageWIdth, tableHeight, tableWidth,
                                    (int) img.getWidth(), (int) img.getHeight());
                        } catch (Exception e) {
                            logger.error(
                                    "Error in image cut, cutt will be ignored and image will be drawn anyway ",
                                    e);
                        }
                    }
                }

                // this is percentage to resize
                // The image must be size within the cell               
                int percToResize = percentageToResize((int) img.getWidth(), (int) img.getHeight(), tableWidth,
                        tableHeight);
                logger.debug("image will be scaled of percentage " + percToResize);
                img.scalePercent(percToResize);

                PdfPCell cell = new PdfPCell(img);
                cell.setNoWrap(true);
                cell.setFixedHeight(tableHeight);
                cell.setBorderWidth(0);
                cell.setHorizontalAlignment(Element.ALIGN_CENTER);
                cell.setVerticalAlignment(Element.ALIGN_CENTER);
                table.addCell(cell);

                //table.setWidthPercentage(tableWidthPerc);
                table.setTotalWidth(tableWidth);
                table.setLockedWidth(true);
            } else {
                // TODO: setALT!
            }
            logger.debug("Add table");
            table.writeSelectedRows(0, -1, xPos, yPos, writer.getDirectContent());
            logger.debug("Document added");
        }

    }
    document.close();
    logger.debug("OUT");
    return fileOutputStream;
}

From source file:jm.web.Addons.java

License:GNU General Public License

public static void setEncabezado(PdfWriter writer, Document document, String texto) {
    if (writer.getPageNumber() > 1) {
        try {//from  www .  ja v a2  s  .  co m
            PdfPTable encabezado = new PdfPTable(1);
            encabezado.setTotalWidth(document.right() - document.left() - 120);
            encabezado.addCell(Addons.setCeldaPDF(texto, Font.HELVETICA, 9, Font.BOLD, Element.ALIGN_LEFT, 0));
            encabezado.writeSelectedRows(0, -1, 60, document.top() + 25, writer.getDirectContent());

            PdfContentByte cb = writer.getDirectContent();
            cb.setLineWidth(2);
            cb.moveTo(60, document.top() + 10);
            cb.lineTo(document.right() - document.left() - 58, document.top() + 10);
        } catch (Exception e) {
            throw new ExceptionConverter(e);
        }
    }
}

From source file:jm.web.Addons.java

License:GNU General Public License

public static void setPie(PdfWriter writer, Document document, String rep_pie) {
    try {//from   w  w w  . j a  va2  s . c om
        PdfContentByte cb = writer.getDirectContent();
        /*cb.setLineWidth(2);
        cb.moveTo(60, document.bottomMargin()-5);
        cb.lineTo(document.right() - document.left()-70, document.bottomMargin()-5);
        */
        PdfPTable pie = new PdfPTable(1);
        pie.setTotalWidth(document.right() - document.left() - 120);
        pie.addCell(Addons.setCeldaPDF(rep_pie, Font.HELVETICA, 9, Font.BOLD, Element.ALIGN_CENTER, 0));
        pie.addCell(Addons.setCeldaPDF("Pg " + String.valueOf(writer.getPageNumber()), Font.HELVETICA, 9,
                Font.BOLD, Element.ALIGN_RIGHT, 0));
        pie.addCell(Addons.setCeldaPDF(
                "Reporte diseado por: Jorge Mueses Cevallos.      Mvil: 095204832     mail:jorge_mueses@yahoo.com",
                Font.HELVETICA, 5, Font.BOLD, Element.ALIGN_LEFT, 0));
        pie.writeSelectedRows(0, -1, 60, document.bottomMargin() - 10, cb);
    } catch (Exception e) {
        throw new ExceptionConverter(e);
    }
}

From source file:nl.knaw.dans.common.lang.pdf.PdfPageLayouter.java

License:Apache License

public void onEndPage(final PdfWriter writer, final Document document) {
    final float bottom = document.bottom();
    final float centerX = getCenterX(document);
    final PdfContentByte canvas = writer.getDirectContent();
    final int rotation = 0;

    final PdfPTable table = new PdfPTable(5);
    table.setTotalWidth(PAGE_NUMBER_TABLE_WIDTH);
    table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
    table.getDefaultCell().setBorder(0);

    table.addCell(TO_FIRST);/*from   w  ww . ja  v  a  2s . c o m*/
    table.addCell(TO_PREV);
    table.addCell(new Phrase(new Chunk("" + document.getPageNumber(), FONT)));
    table.addCell(TO_NEXT);
    table.addCell(TO_LAST);

    table.writeSelectedRows(0, -1, centerX - (table.getTotalWidth() / 2), bottom - FOOTER_POSITION, canvas);
    if (footerPhrase == null)
        return;
    showTextAligned(canvas, Element.ALIGN_CENTER, new Phrase(footerPhrase), centerX, bottom - FOOTER_POSITION,
            rotation);
}

From source file:org.cyberoam.iview.charts.Chart.java

License:Open Source License

/**
 * This Event handler Method adds Header and Footer in PDF File
 *//*from  w w  w.  j av a2s.  c  o  m*/
public void onEndPage(PdfWriter writer, Document document) {
    try {
        if (document.getPageNumber() > 1) {
            String seperator = System.getProperty("file.separator");
            //String path=System.getProperty("catalina.home") +seperator+"webapps" +seperator+"ROOT" + seperator + "images" + seperator;
            String path = InitServlet.contextPath + seperator + "images" + seperator;
            Image imgHead = Image.getInstance(path + "iViewPDFHeader.JPG");
            Image imgFoot = Image.getInstance(path + "iViewPDFFooter.JPG");
            Rectangle page = document.getPageSize();

            PdfPTable head = new PdfPTable(1);
            head.addCell(imgHead);
            head.setTotalWidth(page.getWidth() - document.leftMargin() - document.rightMargin());
            head.writeSelectedRows(0, -1, document.leftMargin() - 10,
                    page.getHeight() - document.topMargin() + head.getTotalHeight(), writer.getDirectContent());

            PdfPTable foot = new PdfPTable(1);
            foot.addCell(imgFoot);
            foot.setTotalWidth(page.getWidth() - document.leftMargin() - document.rightMargin());
            foot.writeSelectedRows(0, -1, document.leftMargin() - 10, document.bottomMargin() + 24,
                    writer.getDirectContent());
        }
    } catch (Exception e) {
        throw new ExceptionConverter(e);
    }
}

From source file:org.drools.verifier.doc.DroolsDocsComponentFactory.java

License:Apache License

public void onEndPage(PdfWriter writer, Document document) {

    try {//from w ww  .ja v a 2s . co m
        Image image = Image.getInstance(DroolsDocsBuilder.class.getResource("guvnor-webapp.png")); // TODO this image never existed
        image.setAlignment(Image.RIGHT);
        image.scaleAbsolute(100, 30);
        Rectangle page = document.getPageSize();
        PdfPTable head = new PdfPTable(2);

        PdfPCell cell1 = new PdfPCell(image);
        cell1.setHorizontalAlignment(Element.ALIGN_LEFT);
        cell1.setBorder(0);

        head.addCell(cell1);

        PdfPCell cell2 = new PdfPCell(new Phrase(currentDate, DroolsDocsComponentFactory.HEADER_FOOTER_TEXT));
        cell2.setHorizontalAlignment(Element.ALIGN_RIGHT);
        cell2.setBorder(0);

        head.addCell(cell2);

        head.setTotalWidth(page.getWidth() - document.leftMargin() - document.rightMargin());
        head.writeSelectedRows(0, -1, document.leftMargin(),
                page.getHeight() - document.topMargin() + head.getTotalHeight(), writer.getDirectContent());

    } catch (Exception e) {
        throw new ExceptionConverter(e);
    }
}

From source file:org.mapfish.print.config.layout.ColumnsBlock.java

License:Open Source License

public void render(final PJsonObject params, PdfElement target, final RenderingContext context)
        throws DocumentException {

    if (isAbsolute()) {
        context.getCustomBlocks().addAbsoluteDrawer(new PDFCustomBlocks.AbsoluteDrawer() {
            public void render(PdfContentByte dc) throws DocumentException {
                final PdfPTable table = PDFUtils.buildTable(items, params, context, nbColumns, config);
                if (table != null) {
                    table.setTotalWidth(width);
                    table.setLockedWidth(true);

                    if (widths != null) {
                        table.setWidths(widths);
                    }/*from   ww  w.j  a v  a 2 s  .com*/

                    table.writeSelectedRows(0, -1, absoluteX, absoluteY, dc);
                }
            }
        });
    } else {
        final PdfPTable table = PDFUtils.buildTable(items, params, context, nbColumns, config);
        if (table != null) {
            if (widths != null) {
                table.setWidths(widths);
            }

            table.setSpacingAfter((float) spacingAfter);
            target.add(table);
        }
    }
}

From source file:org.mapfish.print.config.layout.HeaderFooter.java

License:Open Source License

public void render(final Rectangle rectangle, PdfContentByte dc, PJsonObject params, RenderingContext context) {
    try {//w w w.  jav a  2s .c  o m
        final PdfPTable table = PDFUtils.buildTable(items, params, context,
                1/*multiple items are arranged by lines*/, null);
        if (table != null) {
            table.setTotalWidth(rectangle.getWidth());
            table.writeSelectedRows(0, -1, rectangle.getLeft(), rectangle.getTop(), dc);
        }
    } catch (DocumentException e) {
        context.addError(e);
    }
}

From source file:org.mapfish.print.config.layout.PivotTableBlock.java

License:Open Source License

public void render(final PJsonObject params, PdfElement target, final RenderingContext context)
        throws DocumentException {

    if (isAbsolute()) {
        context.getCustomBlocks().addAbsoluteDrawer(new PDFCustomBlocks.AbsoluteDrawer() {
            public void render(PdfContentByte dc) throws DocumentException {
                final PdfPTable table = buildPivotTable(params, context, tableConfig);
                if (table != null) {
                    table.setTotalWidth(width);
                    table.setLockedWidth(true);

                    if (widths != null) {
                        table.setWidths(widths);
                    }/*from w  w w  . j av  a 2s .c o m*/

                    table.writeSelectedRows(0, -1, absoluteX, absoluteY, dc);
                }
            }
        });
    } else {
        final PdfPTable table = buildPivotTable(params, context, tableConfig);
        if (table != null) {
            if (widths != null) {
                table.setWidths(widths);
            }

            table.setSpacingAfter((float) spacingAfter);
            target.add(table);
        }
    }
}

From source file:org.revager.export.PDFPageEventHelper.java

License:Open Source License

@Override
public void onEndPage(PdfWriter writer, Document document) {
    int columnNumber;

    try {//  ww w.j  a va 2 s  . c  om
        Rectangle page = document.getPageSize();
        float pageWidth = page.getWidth() - document.leftMargin() - document.rightMargin();

        /*
         * Write marks
         */
        setMarks(writer, document);

        /*
         * Define fonts
         */
        headBaseFont = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.EMBEDDED);
        Font headFont = new Font(headBaseFont, headFontSize);

        footBaseFont = BaseFont.createFont(BaseFont.HELVETICA_OBLIQUE, BaseFont.CP1252, BaseFont.EMBEDDED);
        Font footFont = new Font(footBaseFont, footFontSize);

        /*
         * Cell fill for space between head/foot and content
         */
        PdfPCell cellFill = new PdfPCell();
        cellFill.setMinimumHeight(PDFTools.cmToPt(0.8f));
        cellFill.setBorderWidth(0);

        /*
         * Write head
         */
        if (headLogoPath != null) {
            columnNumber = 2;
        } else {
            columnNumber = 1;
        }

        PdfPTable head = new PdfPTable(columnNumber);

        Phrase phraseTitle = new Phrase(headTitle, headFont);

        PdfPCell cellTitle = new PdfPCell(phraseTitle);
        cellTitle.setHorizontalAlignment(Element.ALIGN_LEFT);
        cellTitle.setVerticalAlignment(Element.ALIGN_BOTTOM);
        cellTitle.setPaddingTop(0);
        cellTitle.setPaddingBottom(PDFTools.cmToPt(0.2f));
        cellTitle.setPaddingLeft(0);
        cellTitle.setPaddingRight(0);
        cellTitle.setBorderWidthTop(0);
        cellTitle.setBorderWidthBottom(0.5f);
        cellTitle.setBorderWidthLeft(0);
        cellTitle.setBorderWidthRight(0);

        head.addCell(cellTitle);

        if (headLogoPath != null) {
            Image headLogo = Image.getInstance(headLogoPath);
            headLogo.scaleToFit(PDFTools.cmToPt(5.0f), PDFTools.cmToPt(1.1f));

            PdfPCell cellLogo = new PdfPCell(headLogo);
            cellLogo.setHorizontalAlignment(Element.ALIGN_RIGHT);
            cellLogo.setVerticalAlignment(Element.ALIGN_BOTTOM);
            cellLogo.setPaddingTop(0);
            cellLogo.setPaddingBottom(PDFTools.cmToPt(0.15f));
            cellLogo.setPaddingLeft(0);
            cellLogo.setPaddingRight(0);
            cellLogo.setBorderWidthTop(0);
            cellLogo.setBorderWidthBottom(0.5f);
            cellLogo.setBorderWidthLeft(0);
            cellLogo.setBorderWidthRight(0);

            head.addCell(cellLogo);

            head.addCell(cellFill);
        }

        head.addCell(cellFill);

        head.setTotalWidth(pageWidth);
        head.writeSelectedRows(0, -1, document.leftMargin(),
                page.getHeight() - document.topMargin() + head.getTotalHeight(), writer.getDirectContent());

        /*
         * Write foot
         */
        if (footText == null) {
            footText = " ";
        }

        PdfPTable foot = new PdfPTable(1);

        foot.addCell(cellFill);

        PdfPCell cellFootText = new PdfPCell(new Phrase(footText, footFont));
        cellFootText.setHorizontalAlignment(Element.ALIGN_RIGHT);
        cellFootText.setVerticalAlignment(Element.ALIGN_TOP);
        cellFootText.setPaddingTop(PDFTools.cmToPt(0.15f));
        cellFootText.setPaddingBottom(0);
        cellFootText.setPaddingLeft(0);
        cellFootText.setPaddingRight(0);
        cellFootText.setBorderWidthTop(0.5f);
        cellFootText.setBorderWidthBottom(0);
        cellFootText.setBorderWidthLeft(0);
        cellFootText.setBorderWidthRight(0);

        foot.addCell(cellFootText);

        /*
         * Print page numbers
         */
        PdfContentByte contentByte = writer.getDirectContent();
        contentByte.saveState();

        String text = MessageFormat.format(translate("Page {0} of") + " ", writer.getPageNumber());

        float textSize = footBaseFont.getWidthPoint(text, footFontSize);
        float textBase = document.bottom() - PDFTools.cmToPt(1.26f);
        contentByte.beginText();
        contentByte.setFontAndSize(footBaseFont, footFontSize);

        float adjust;
        if (footText.trim().equals("")) {
            adjust = (pageWidth / 2) - (textSize / 2) - footBaseFont.getWidthPoint("0", footFontSize);
        } else {
            adjust = 0;
        }

        contentByte.setTextMatrix(document.left() + adjust, textBase);
        contentByte.showText(text);
        contentByte.endText();
        contentByte.addTemplate(template, document.left() + adjust + textSize, textBase);

        contentByte.stroke();
        contentByte.restoreState();

        foot.setTotalWidth(pageWidth);
        foot.writeSelectedRows(0, -1, document.leftMargin(), document.bottomMargin(),
                writer.getDirectContent());
    } catch (Exception e) {
        /*
         * Not part of unit testing because this exception is only thrown if
         * an internal error occurs.
         */
        throw new ExceptionConverter(e);
    }
}