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:biblivre3.administration.reports.BaseBiblivreReport.java

License:Open Source License

@Override
public void onEndPage(PdfWriter writer, Document document) {
    try {/*from  w ww.j av  a  2  s .c  om*/
        Rectangle page = document.getPageSize();

        PdfPTable head = new PdfPTable(1);
        PdfPCell cell = new PdfPCell(new Paragraph(this.getText("REPORTS_HEADER")));
        cell.setHorizontalAlignment(PdfPCell.ALIGN_LEFT);
        cell.setVerticalAlignment(PdfPCell.ALIGN_CENTER);
        cell.setBorder(Rectangle.BOTTOM);
        head.addCell(cell);
        head.setTotalWidth((page.width() / 2) - document.leftMargin());
        head.writeSelectedRows(0, -1, document.leftMargin(),
                page.height() - document.topMargin() + head.getTotalHeight(), writer.getDirectContent());

        PdfPTable date = new PdfPTable(1);
        PdfPCell dateCell = new PdfPCell(new Paragraph(dateFormat.format(generationDate)));
        dateCell.setHorizontalAlignment(PdfPCell.ALIGN_RIGHT);
        dateCell.setVerticalAlignment(PdfPCell.ALIGN_CENTER);
        dateCell.setBorder(Rectangle.BOTTOM);
        date.addCell(dateCell);
        date.setTotalWidth((page.width() / 2) - document.rightMargin());
        date.writeSelectedRows(0, -1, (page.width() / 2),
                page.height() - document.topMargin() + head.getTotalHeight(), writer.getDirectContent());

        PdfPTable foot = new PdfPTable(1);
        Chunk pageNumber = new Chunk(String.valueOf(document.getPageNumber()));
        pageNumber.setFont(footerFont);
        cell = new PdfPCell(new Paragraph(pageNumber));
        cell.setHorizontalAlignment(PdfPCell.ALIGN_RIGHT);
        cell.setVerticalAlignment(PdfPCell.ALIGN_CENTER);
        cell.setBorder(Rectangle.TOP);
        foot.addCell(cell);
        foot.setTotalWidth(page.width() - document.leftMargin() - document.rightMargin());
        foot.writeSelectedRows(0, -1, document.leftMargin(), document.bottomMargin(),
                writer.getDirectContent());
    } catch (Exception e) {
        throw new ExceptionConverter(e);
    }
}

From source file:br.gov.jfrj.itextpdf.Documento.java

License:Open Source License

public static byte[] stamp(byte[] abPdf, String sigla, boolean rascunho, boolean cancelado, boolean semEfeito,
        boolean internoProduzido, String qrCode, String mensagem, Integer paginaInicial, Integer paginaFinal,
        Integer cOmitirNumeracao, String instancia, String orgaoUsu) throws DocumentException, IOException {

    PdfReader pdfIn = new PdfReader(abPdf);
    Document doc = new Document(PageSize.A4, 0, 0, 0, 0);
    // final SimpleDateFormat sdf = new SimpleDateFormat(
    // "EEE MMM dd HH:mm:ss zzz yyyy");
    // doc.add(new Meta("creationdate", sdf.format(new Date(0L))));
    final ByteArrayOutputStream boA4 = new ByteArrayOutputStream();
    PdfWriter writer = PdfWriter.getInstance(doc, boA4);
    doc.open();//from ww w .j  a  v a 2s.c  o m
    PdfContentByte cb = writer.getDirectContent();

    // Resize every page to A4 size
    //
    // double thetaRotation = 0.0;
    for (int i = 1; i <= pdfIn.getNumberOfPages(); i++) {
        int rot = pdfIn.getPageRotation(i);
        float left = pdfIn.getPageSize(i).getLeft();
        float bottom = pdfIn.getPageSize(i).getBottom();
        float top = pdfIn.getPageSize(i).getTop();
        float right = pdfIn.getPageSize(i).getRight();

        PdfImportedPage page = writer.getImportedPage(pdfIn, i);
        float w = page.getWidth();
        float h = page.getHeight();

        // Logger.getRootLogger().error("----- dimensoes: " + rot + ", " + w
        // + ", " + h);

        doc.setPageSize((rot != 0 && rot != 180) ^ (w > h) ? PageSize.A4.rotate() : PageSize.A4);
        doc.newPage();

        cb.saveState();

        if (rot != 0 && rot != 180) {
            float swap = w;
            w = h;
            h = swap;
        }

        float pw = doc.getPageSize().getWidth();
        float ph = doc.getPageSize().getHeight();
        double scale = Math.min(pw / w, ph / h);

        // do my transformations :
        cb.transform(AffineTransform.getScaleInstance(scale, scale));

        if (!internoProduzido) {
            cb.transform(AffineTransform.getTranslateInstance(pw * SAFETY_MARGIN, ph * SAFETY_MARGIN));
            cb.transform(AffineTransform.getScaleInstance(1.0f - 2 * SAFETY_MARGIN, 1.0f - 2 * SAFETY_MARGIN));
        }

        if (rot != 0) {
            double theta = -rot * (Math.PI / 180);
            if (rot == 180) {
                cb.transform(AffineTransform.getRotateInstance(theta, w / 2, h / 2));
            } else {
                cb.transform(AffineTransform.getRotateInstance(theta, h / 2, w / 2));
            }
            if (rot == 90) {
                cb.transform(AffineTransform.getTranslateInstance((w - h) / 2, (w - h) / 2));
            } else if (rot == 270) {
                cb.transform(AffineTransform.getTranslateInstance((h - w) / 2, (h - w) / 2));
            }
        }

        // Logger.getRootLogger().error(
        // "----- dimensoes: " + rot + ", " + w + ", " + h);
        // Logger.getRootLogger().error("----- page: " + pw + ", " + ph);

        // cb.transform(AffineTransform.getTranslateInstance(
        // ((pw / scale) - w) / 2, ((ph / scale) - h) / 2));

        // put the page
        cb.addTemplate(page, 0, 0);

        // draw a red rectangle at the page borders
        //
        // cb.saveState();
        // cb.setColorStroke(Color.red);
        // cb.rectangle(pdfIn.getPageSize(i).getLeft(), pdfIn.getPageSize(i)
        // .getBottom(), pdfIn.getPageSize(i).getRight(), pdfIn
        // .getPageSize(i).getTop());
        // cb.stroke();
        // cb.restoreState();

        cb.restoreState();
    }
    doc.close();

    abPdf = boA4.toByteArray();

    final ByteArrayOutputStream bo2 = new ByteArrayOutputStream();

    final PdfReader reader = new PdfReader(abPdf);

    final int n = reader.getNumberOfPages();
    final PdfStamper stamp = new PdfStamper(reader, bo2);

    // adding content to each page
    int i = 0;
    PdfContentByte under;
    PdfContentByte over;
    final BaseFont helv = BaseFont.createFont("Helvetica", BaseFont.WINANSI, false);

    // Image img = Image.getInstance("watermark.jpg");
    final BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.WINANSI, BaseFont.EMBEDDED);

    byte maskr[] = { (byte) 0xff };
    Image mask = Image.getInstance(1, 1, 1, 1, maskr);
    mask.makeMask();
    mask.setInverted(true);

    while (i < n) {
        i++;
        // watermark under the existing page
        under = stamp.getUnderContent(i);
        over = stamp.getOverContent(i);

        final Barcode39 code39 = new Barcode39();
        // code39.setCode(doc.getCodigo());
        code39.setCode(sigla.replace("-", "").replace("/", "").replace(".", ""));
        code39.setStartStopText(false);
        final Image image39 = code39.createImageWithBarcode(over, null, null);
        Rectangle r = stamp.getReader().getPageSizeWithRotation(i);

        image39.setInitialRotation((float) Math.PI / 2.0f);
        image39.setAbsolutePosition(
                r.getWidth() - image39.getHeight() + (STAMP_BORDER_IN_CM - PAGE_BORDER_IN_CM) * CM_UNIT,
                BARCODE_HEIGHT_IN_CM * CM_UNIT);

        image39.setBackgroundColor(Color.green);
        image39.setBorderColor(Color.RED);
        image39.setBorderWidth(0.5f * CM_UNIT);

        image39.setImageMask(mask);

        over.setRGBColorFill(255, 255, 255);
        mask.setAbsolutePosition(r.getWidth() - image39.getHeight() - (PAGE_BORDER_IN_CM) * CM_UNIT,
                (BARCODE_HEIGHT_IN_CM - STAMP_BORDER_IN_CM) * CM_UNIT);
        mask.scaleAbsolute(image39.getHeight() + 2 * STAMP_BORDER_IN_CM * CM_UNIT,
                image39.getWidth() + 2 * STAMP_BORDER_IN_CM * CM_UNIT);
        over.addImage(mask);

        over.setRGBColorFill(0, 0, 0);
        over.addImage(image39);

        // over.addImage(mask, mask.getScaledWidth() * 8, 0, 0,
        // mask.getScaledHeight() * 8, 100, 450);

        if (qrCode != null) {
            java.awt.Image imgQRCode = createQRCodeImage(qrCode);
            Image imageQRCode = Image.getInstance(imgQRCode, Color.BLACK, true);
            imageQRCode.scaleAbsolute(QRCODE_SIZE_IN_CM * CM_UNIT, QRCODE_SIZE_IN_CM * CM_UNIT);
            imageQRCode.setAbsolutePosition(QRCODE_LEFT_MARGIN_IN_CM * CM_UNIT, PAGE_BORDER_IN_CM * CM_UNIT);

            over.setRGBColorFill(255, 255, 255);
            mask.setAbsolutePosition((QRCODE_LEFT_MARGIN_IN_CM - STAMP_BORDER_IN_CM) * CM_UNIT,
                    (PAGE_BORDER_IN_CM - STAMP_BORDER_IN_CM) * CM_UNIT);
            mask.scaleAbsolute((QRCODE_SIZE_IN_CM + 2 * STAMP_BORDER_IN_CM) * CM_UNIT,
                    (QRCODE_SIZE_IN_CM + 2 * STAMP_BORDER_IN_CM) * CM_UNIT);
            over.addImage(mask);

            over.setRGBColorFill(0, 0, 0);
            over.addImage(imageQRCode);
        }

        if (mensagem != null) {
            PdfPTable table = new PdfPTable(1);
            table.setTotalWidth(r.getWidth() - image39.getHeight() - (QRCODE_LEFT_MARGIN_IN_CM
                    + QRCODE_SIZE_IN_CM + 4 * STAMP_BORDER_IN_CM + PAGE_BORDER_IN_CM) * CM_UNIT);
            PdfPCell cell = new PdfPCell(new Paragraph(mensagem,
                    FontFactory.getFont(FontFactory.HELVETICA, 8, Font.NORMAL, Color.BLACK)));
            cell.setBorderWidth(0);
            table.addCell(cell);

            over.setRGBColorFill(255, 255, 255);
            mask.setAbsolutePosition(
                    (QRCODE_LEFT_MARGIN_IN_CM + QRCODE_SIZE_IN_CM + STAMP_BORDER_IN_CM) * CM_UNIT,
                    (PAGE_BORDER_IN_CM - STAMP_BORDER_IN_CM) * CM_UNIT);
            mask.scaleAbsolute(2 * STAMP_BORDER_IN_CM * CM_UNIT + table.getTotalWidth(),
                    2 * STAMP_BORDER_IN_CM * CM_UNIT + table.getTotalHeight());
            over.addImage(mask);

            over.setRGBColorFill(0, 0, 0);
            table.writeSelectedRows(0, -1,
                    (QRCODE_LEFT_MARGIN_IN_CM + QRCODE_SIZE_IN_CM + 2 * STAMP_BORDER_IN_CM) * CM_UNIT,
                    table.getTotalHeight() + PAGE_BORDER_IN_CM * CM_UNIT, over);
        }

        if (cancelado) {
            over.saveState();
            final PdfGState gs = new PdfGState();
            gs.setFillOpacity(0.5f);
            over.setGState(gs);
            over.setColorFill(Color.GRAY);
            over.beginText();
            over.setFontAndSize(helv, 72);
            over.showTextAligned(Element.ALIGN_CENTER, "CANCELADO", r.getWidth() / 2, r.getHeight() / 2, 45);
            over.endText();
            over.restoreState();
        } else if (rascunho) {
            over.saveState();
            final PdfGState gs = new PdfGState();
            gs.setFillOpacity(0.5f);
            over.setGState(gs);
            over.setColorFill(Color.GRAY);
            over.beginText();
            over.setFontAndSize(helv, 72);
            over.showTextAligned(Element.ALIGN_CENTER, "MINUTA", r.getWidth() / 2, r.getHeight() / 2, 45);
            over.endText();
            over.restoreState();
        } else if (semEfeito) {
            over.saveState();
            final PdfGState gs = new PdfGState();
            gs.setFillOpacity(0.5f);
            over.setGState(gs);
            over.setColorFill(Color.GRAY);
            over.beginText();
            over.setFontAndSize(helv, 72);
            over.showTextAligned(Element.ALIGN_CENTER, "SEM EFEITO", r.getWidth() / 2, r.getHeight() / 2, 45);
            over.endText();
            over.restoreState();
        }

        // if (!rascunho
        // && request.getRequestURL().indexOf("http://laguna/") == -1) {

        if (!rascunho && !cancelado && !semEfeito && ((!Contexto.resource("isVersionTest").equals("false"))
                || (!Contexto.resource("isBaseTest").equals("false")))) {
            over.saveState();
            final PdfGState gs = new PdfGState();
            gs.setFillOpacity(0.5f);
            over.setGState(gs);
            over.setColorFill(Color.GRAY);
            over.beginText();
            over.setFontAndSize(helv, 72);
            over.showTextAligned(Element.ALIGN_CENTER, "INVLIDO", r.getWidth() / 2, r.getHeight() / 2, 45);
            over.endText();
            over.restoreState();
        }

        // Imprime um circulo com o numero da pagina dentro.

        if (paginaInicial != null) {
            String sFl = String.valueOf(paginaInicial + i - 1);
            // Se for a ultima pagina e o numero nao casar, acrescenta "-" e
            // pagina final
            if (n == i) {
                if (paginaFinal != paginaInicial + n - 1) {
                    sFl = sFl + "-" + String.valueOf(paginaFinal);
                }
            }
            if (i > cOmitirNumeracao) {

                // Raio do circulo interno
                final float radius = 18f;

                // Distancia entre o circulo interno e o externo
                final float circleInterspace = Math.max(helv.getAscentPoint(instancia, TEXT_HEIGHT),
                        helv.getAscentPoint(orgaoUsu, TEXT_HEIGHT))
                        - Math.min(helv.getDescentPoint(instancia, TEXT_HEIGHT),
                                helv.getDescentPoint(orgaoUsu, TEXT_HEIGHT))
                        + 2 * TEXT_TO_CIRCLE_INTERSPACE;

                // Centro do circulo
                float xCenter = r.getWidth() - 1.8f * (radius + circleInterspace);
                float yCenter = r.getHeight() - 1.8f * (radius + circleInterspace);

                over.saveState();
                final PdfGState gs = new PdfGState();
                gs.setFillOpacity(1f);
                over.setGState(gs);
                over.setColorFill(Color.BLACK);

                over.saveState();
                over.setColorStroke(Color.black);
                over.setLineWidth(1f);
                over.setColorFill(Color.WHITE);

                // Circulo externo
                over.circle(xCenter, yCenter, radius + circleInterspace);
                over.fill();
                over.circle(xCenter, yCenter, radius + circleInterspace);
                over.stroke();

                // Circulo interno
                over.circle(xCenter, yCenter, radius);
                over.stroke();
                over.restoreState();

                {
                    over.saveState();
                    over.beginText();
                    over.setFontAndSize(helv, TEXT_HEIGHT);

                    // Escreve o texto superior do carimbo
                    float fDescent = helv.getDescentPoint(instancia, TEXT_HEIGHT);
                    showTextOnArc(over, instancia, helv, TEXT_HEIGHT, xCenter, yCenter,
                            radius - fDescent + TEXT_TO_CIRCLE_INTERSPACE, true);

                    // Escreve o texto inferior
                    float fAscent = helv.getAscentPoint(orgaoUsu, TEXT_HEIGHT);
                    showTextOnArc(over, orgaoUsu, helv, TEXT_HEIGHT, xCenter, yCenter,
                            radius + fAscent + TEXT_TO_CIRCLE_INTERSPACE, false);
                    over.endText();
                    over.restoreState();
                }

                over.beginText();
                int textHeight = 23;

                // Diminui o tamanho do font ate que o texto caiba dentro do
                // circulo interno
                while (helv.getWidthPoint(sFl, textHeight) > (2 * (radius - TEXT_TO_CIRCLE_INTERSPACE)))
                    textHeight--;
                float fAscent = helv.getAscentPoint(sFl, textHeight) + helv.getDescentPoint(sFl, textHeight);
                over.setFontAndSize(helv, textHeight);
                over.showTextAligned(Element.ALIGN_CENTER, sFl, xCenter, yCenter - 0.5f * fAscent, 0);
                over.endText();
                over.restoreState();
            }
        }

    }
    stamp.close();
    return bo2.toByteArray();
}

From source file:br.org.acessobrasil.silvinha.util.HeaderAndFooter.java

License:Open Source License

/**
 * @see com.lowagie.text.pdf.PdfPageEventHelper#onEndPage(com.lowagie.text.pdf.PdfWriter, com.lowagie.text.Document)
 */// w  w w . java2s  . com
public void onEndPage(PdfWriter writer, Document document) {

    try {
        Rectangle page = document.getPageSize();
        PdfPTable head = new PdfPTable(1);
        PdfPCell cell = new PdfPCell(new Paragraph(GERAL.RELATORIOS_ASES));
        cell.setHorizontalAlignment(PdfPCell.ALIGN_RIGHT);
        cell.setVerticalAlignment(PdfPCell.ALIGN_CENTER);
        cell.setBorder(Rectangle.BOTTOM);
        head.addCell(cell);
        head.setTotalWidth(page.getWidth() - document.leftMargin() - document.rightMargin());
        head.writeSelectedRows(0, -1, document.leftMargin(),
                page.getHeight() - document.topMargin() + head.getTotalHeight(), writer.getDirectContent());
        PdfPTable foot = new PdfPTable(1);
        cell = new PdfPCell(new Paragraph(String.valueOf(document.getPageNumber())));
        cell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
        cell.setVerticalAlignment(PdfPCell.ALIGN_CENTER);
        cell.setBorder(Rectangle.TOP);
        foot.addCell(cell);
        foot.setTotalWidth(page.getWidth() - document.leftMargin() - document.rightMargin());
        foot.writeSelectedRows(0, -1, document.leftMargin(), document.bottomMargin(),
                writer.getDirectContent());
    } catch (Exception e) {
        throw new ExceptionConverter(e);
    }
}

From source file:ca.sqlpower.architect.profile.output.ProfilePDFFormat.java

License:Open Source License

/**
 * Outputs a PDF file report of the data in drs to the given
 * output stream.//w  ww.j av a 2  s.  c om
 * @throws SQLObjectException
 * @throws IllegalAccessException
 * @throws InstantiationException
 */
public void format(OutputStream out, List<ProfileResult> profileResults)
        throws DocumentException, IOException, SQLException, SQLObjectException, InstantiationException,
        IllegalAccessException, ClassNotFoundException {

    final int minRowsTogether = 1; // counts smaller than this are considered orphan/widow
    final int mtop = 50; // margin at top of page (in points)
    final int mbot = 50; // margin at bottom of page (page numbers are below this)
    //        final int pbot = 20;  // padding between bottom margin and bottom of body text
    final int mlft = 50; // margin at left side of page
    final int mrgt = 50; // margin at right side of page
    final Rectangle pagesize = PageSize.LETTER.rotate();
    final Document document = new Document(pagesize, mlft, mrgt, mtop, mbot);
    final PdfWriter writer = PdfWriter.getInstance(document, out);

    final float fsize = 6f; // the font size to use in the table body
    final BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.WINANSI, BaseFont.NOT_EMBEDDED);
    document.addTitle("Table Profiling Report");
    document.addSubject("Tables: " + profileResults);
    document.addAuthor(System.getProperty("user.name"));
    document.addCreator("Power*Architect version " + ArchitectVersion.APP_FULL_VERSION);

    document.open();

    // vertical position where next element should start
    //   (bottom is 0; top is pagesize.height())
    float pos = pagesize.height() - mtop;

    final PdfContentByte cb = writer.getDirectContent();
    final PdfTemplate nptemplate = cb.createTemplate(50, 50);
    writer.setPageEvent(new PdfPageEventHelper() {
        // prints the "page N of <template>" footer
        public void onEndPage(PdfWriter writer, Document document) {
            int pageN = writer.getPageNumber();
            String text = "Page " + pageN + " of ";
            float len = bf.getWidthPoint(text, fsize - 2);
            cb.beginText();
            cb.setFontAndSize(bf, fsize - 2);
            cb.setTextMatrix(pagesize.width() / 2 - len / 2, mbot / 2);
            cb.showText(text);
            cb.endText();
            cb.addTemplate(nptemplate, pagesize.width() / 2 - len / 2 + len, mbot / 2);
        }

        public void onCloseDocument(PdfWriter writer, Document document) {
            nptemplate.beginText();
            nptemplate.setFontAndSize(bf, fsize - 2);
            nptemplate.showText(String.valueOf(writer.getPageNumber() - 1));
            nptemplate.endText();
        }
    });

    document.add(new Paragraph("SQL Power Architect Profiling Report"));
    document.add(new Paragraph("Generated " + new java.util.Date() + " by " + System.getProperty("user.name")));

    float[] widths = new float[totalColumn]; // widths of widest cells per row in pdf table
    LinkedList<ProfileTableStructure> profiles = new LinkedList<ProfileTableStructure>(); // 1 table per profile result

    Font f = new Font(bf, fsize);

    // This ddl generator is set to the appropriate ddl generator for the source database
    // every time we encounter a table profile result in the list.
    DDLGenerator ddlg = null;

    PdfPTable pdfTable = null;
    for (ProfileResult result : profileResults) {
        if (result instanceof TableProfileResult) {
            TableProfileResult tableResult = (TableProfileResult) result;
            pdfTable = new PdfPTable(widths.length);
            pdfTable.setWidthPercentage(100f);
            ProfileTableStructure oneProfile = makeNextTable(tableResult, pdfTable, bf, fsize, widths);
            profiles.add(oneProfile);
            ddlg = tableResult.getDDLGenerator();
        } else if (result instanceof ColumnProfileResult) {
            final ColumnProfileResult columnResult = (ColumnProfileResult) result;
            TableProfileResult tResult = columnResult.getParent();
            addBodyRow(tResult, columnResult, ddlg, pdfTable, bf, f, fsize, widths);
        }
    }

    double allowedTableSize = pagesize.width() - mrgt - mlft;
    double totalWidths = 0;
    for (int i = 0; i < headings.length; i++) {
        if (!columnsToTruncate.contains(headings[i])) {
            widths[i] += PIXELS_PER_BORDER;
            totalWidths += widths[i];
        }
    }
    truncateLength = (allowedTableSize - totalWidths - (PIXELS_PER_BORDER * (columnsToTruncate.size())))
            / columnsToTruncate.size();
    logger.debug("Truncate length is " + truncateLength);
    widths = new float[totalColumn];

    profiles = new LinkedList<ProfileTableStructure>(); // 1 table per profile result
    for (ProfileResult result : profileResults) {
        if (result instanceof TableProfileResult) {
            TableProfileResult tableResult = (TableProfileResult) result;
            pdfTable = new PdfPTable(widths.length);
            pdfTable.setWidthPercentage(100f);
            ProfileTableStructure oneProfile = makeNextTable(tableResult, pdfTable, bf, fsize, widths);
            profiles.add(oneProfile);
            ddlg = tableResult.getDDLGenerator();
        } else if (result instanceof ColumnProfileResult) {
            final ColumnProfileResult columnResult = (ColumnProfileResult) result;
            TableProfileResult tResult = columnResult.getParent();
            addBodyRow(tResult, columnResult, ddlg, pdfTable, bf, f, fsize, widths);
        }
    }

    for (int i = 0; i < headings.length; i++) {
        widths[i] += PIXELS_PER_BORDER;
    }

    // add the PdfPTables to the document; try to avoid orphan and widow rows
    pos = writer.getVerticalPosition(true) - fsize;
    logger.debug("Starting at pos=" + pos);
    boolean newPageInd = true;

    for (ProfileTableStructure profile : profiles) {

        pdfTable = profile.getMainTable();
        pdfTable.setTotalWidth(pagesize.width() - mrgt - mlft);
        pdfTable.setWidths(widths);
        resetHeaderWidths(profile, widths);

        int startrow = pdfTable.getHeaderRows();
        int endrow = startrow; // current page will contain header+startrow..endrow

        /* no other rows in the table, just the header, and the header may
         * contain error message
         */
        if (endrow == pdfTable.size()) {
            pos = pdfTable.writeSelectedRows(0, pdfTable.getHeaderRows(), mlft, pos, cb);
            continue;
        }

        while (endrow < pdfTable.size()) {

            // figure out how many body rows fit nicely on the page
            float endpos = pos - calcHeaderHeight(pdfTable);

            // y position of page number# = (mbot/2+fsize)
            while ((endpos - pdfTable.getRowHeight(endrow)) >= (mbot / 2 + fsize + 2)
                    && endrow < pdfTable.size()) {
                endpos -= pdfTable.getRowHeight(endrow);
                endrow++;
            }

            // adjust for orphan rows. Might create widows or make
            // endrow < startrow, which is handled later by deferring the table
            if (endrow < pdfTable.size() && endrow + minRowsTogether >= pdfTable.size()) {

                // page # maybe fall into table area, but usually that's column of
                // min value, usually that's enough space for both, or we should
                // disable page # on this page
                if (endrow + 1 == pdfTable.size() && endpos - pdfTable.getRowHeight(endrow) > 10) {

                    // short by 1 row.. just squeeze it in
                    endrow = pdfTable.size();
                } else {
                    // more than 1 row remains: shorten this page so orphans aren't lonely
                    endrow = pdfTable.size() - minRowsTogether;
                }
            }

            if (endrow == pdfTable.size() || endrow - startrow >= minRowsTogether) {
                // this is the end of the table, or we have enough rows to bother printing
                pos = pdfTable.writeSelectedRows(0, pdfTable.getHeaderRows(), mlft, pos, cb);
                pos = pdfTable.writeSelectedRows(startrow, endrow, mlft, pos, cb);
                startrow = endrow;
                newPageInd = false;
            } else {
                // not the end of the table and not enough rows to print out
                if (newPageInd)
                    throw new IllegalStateException(
                            "PDF Page is not large engouh to display " + minRowsTogether + " row(s)");
                endrow = startrow;
            }

            // new page if necessary (that is, when we aren't finished the table yet)
            if (endrow != pdfTable.size()) {
                document.newPage();
                pos = pagesize.height() - mtop;
                newPageInd = true;
            }
        }
    }
    document.close();
}

From source file:com.krawler.spring.exportFuctionality.ExportinvController.java

License:Open Source License

private static void addHeaderFooter(Document document, PdfWriter writer)
        throws DocumentException, ServiceException {
    fontSmallRegular.setColor(Color.BLACK);
    java.util.Date dt = new java.util.Date();
    String date = "yyyy-MM-dd";
    java.text.SimpleDateFormat dtf = new java.text.SimpleDateFormat(date);
    String DateStr = dtf.format(dt);
    PdfPTable footer = new PdfPTable(1);
    PdfPCell footerSeparator = new PdfPCell(new Phrase(""));
    footerSeparator.setBorder(PdfPCell.BOX);
    footerSeparator.setPadding(0);//from ww w .j av a  2  s  . c  o m
    footerSeparator.setColspan(3);
    footer.addCell(footerSeparator);

    String PageDate = DateStr;
    PdfPCell pagerDateCell = new PdfPCell(new Phrase("Generated Date : " + PageDate, fontSmallRegular));
    pagerDateCell.setBorder(0);
    pagerDateCell.setHorizontalAlignment(PdfCell.ALIGN_CENTER);
    footer.addCell(pagerDateCell);
    // -------- footer end   -----------
    try {
        Rectangle page = document.getPageSize();
        footer.setTotalWidth(page.getWidth() - document.leftMargin() - document.rightMargin());
        footer.writeSelectedRows(0, -1, document.leftMargin(), document.bottomMargin(),
                writer.getDirectContent());
    } catch (Exception e) {
        throw new ExceptionConverter(e);
    }
}

From source file:com.krawler.spring.exportFuctionality.ExportRecord.java

License:Open Source License

private void addHeaderFooter(Document document, PdfWriter writer) throws DocumentException, ServiceException {
    PdfPTable footer = new PdfPTable(1);
    PdfPCell footerSeparator = new PdfPCell(new Paragraph("THANK YOU FOR YOUR BUSINESS!", fontTblMediumBold));
    footerSeparator.setHorizontalAlignment(Element.ALIGN_CENTER);
    footerSeparator.setBorder(0);/*from   w  ww .  j a  va2  s  .c  o  m*/
    footer.addCell(footerSeparator);

    try {
        Rectangle page = document.getPageSize();
        footer.setTotalWidth(page.getWidth() - document.leftMargin());
        footer.writeSelectedRows(0, -1, document.leftMargin(), document.bottomMargin(),
                writer.getDirectContent());
    } catch (Exception e) {
        throw new ExceptionConverter(e);
    }
}

From source file:com.prime.report.template.TableHeader.java

/**
 * Adds a header to every page/*  ww w. jav  a2s  .c  o  m*/
 *
 * @param writer
 * @param document
 * @see com.itextpdf.text.pdf.PdfPageEventHelper#onEndPage(
 * com.itextpdf.text.pdf.PdfWriter, com.itextpdf.text.Document)
 */
@Override
public void onEndPage(PdfWriter writer, Document document) {

    PdfPTable table = new PdfPTable(4);
    try {
        table.setWidths(new int[] { 10, 11, 9, 1 });
        table.setTotalWidth(527);
        table.setLockedWidth(true);
        table.getDefaultCell().setFixedHeight(20);
        table.getDefaultCell().setBorder(Rectangle.NO_BORDER);

        String logoPath = "/resources/image/logo.png";
        ServletContext servletContext = (ServletContext) facesContext.getExternalContext().getContext();
        String logo = servletContext.getRealPath(logoPath);
        Image img = Image.getInstance(logo);

        table.addCell(Image.getInstance(img));

        table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
        table.addCell(new Phrase("New South West Facility Center",
                FontFactory.getFont(FontFactory.HELVETICA, 12, Font.BOLDITALIC, Color.BLACK)));
        table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_RIGHT);
        table.addCell(String.format("Page %d of", writer.getPageNumber()));
        PdfPCell cell = new PdfPCell(Image.getInstance(total));
        cell.setBorder(Rectangle.NO_BORDER);
        table.addCell(cell);
        table.writeSelectedRows(0, -1, 34, 803, writer.getDirectContent());
    } catch (DocumentException de) {
        throw new ExceptionConverter(de);
    } catch (IOException ex) {
        Logger.getLogger(TableHeader.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:com.tsp.gespro.bo.DegustacionBO.java

/**
 * Representacin impresa PDF/*from   w  w w . j  a  v a2s  .  c  om*/
 */
public ByteArrayOutputStream toPdf(UsuarioBO user) throws Exception {

    SimpleDateFormat fecha = new SimpleDateFormat("dd/MM/yyyy");
    SimpleDateFormat hora = new SimpleDateFormat("HH:mm:ss");
    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    PdfITextUtil obj = new PdfITextUtil();

    //Tamao de documento (Tamao Carta)
    com.lowagie.text.Document doc = new com.lowagie.text.Document(PageSize.LETTER);

    //Definicin de Fuentes a usar
    Font letraOcho = new Font(Font.HELVETICA, 8, Font.NORMAL);
    Font letraOchoBold = new Font(Font.HELVETICA, 8, Font.BOLD);
    Font letraNueve = new Font(Font.HELVETICA, 9, Font.NORMAL);
    Font letraNueveBold = new Font(Font.HELVETICA, 9, Font.BOLD);
    Font letraNueveBoldRojo = new Font(Font.TIMES_ROMAN, 9, Font.BOLD, Color.red);
    Font letraNueveBoldAzul = new Font(Font.TIMES_ROMAN, 9, Font.BOLD, Color.blue);
    Font letraOchoVerde = new Font(Font.TIMES_ROMAN, 8, Font.NORMAL, Color.green);
    Font letra14Bold = new Font(Font.HELVETICA, 14, Font.BOLD);

    String msgError = "";

    File fileImageLogo = null;
    try {
        if (user != null)
            fileImageLogo = new ImagenPersonalBO(this.conn)
                    .getFileImagenPersonalByEmpresa(user.getUser().getIdEmpresa());
    } catch (Exception ex) {
        ex.printStackTrace();
    }

    try {
        //Preparamos writer de PDF
        PdfWriter writer = PdfWriter.getInstance(doc, baos);
        EventPDF eventPDF = new EventPDF(doc, user, ReportBO.DEGUSTACION_REPRESENTACION_IMPRESA, fileImageLogo);
        writer.setPageEvent(eventPDF);

        //Ajustamos margenes de pgina
        //doc.setMargins(50, 50, 120, 50);
        //doc.setMargins(20, 20, 80, 20);
        doc.setMargins(10, 10, 150, 40);

        //Iniciamos documento
        doc.open();

        //Creamos tabla principal
        PdfPTable mainTable = new PdfPTable(1);
        mainTable.setTotalWidth(550);
        mainTable.setLockedWidth(true);

        //CONTENIDO -------------

        //SALTO DE L?NEA
        obj.agregaCelda(mainTable, letraOcho, " ", new boolean[] { false, false, false, false },
                Element.ALIGN_CENTER, Element.ALIGN_MIDDLE, 0, new int[0], 1);

        //Cabecera (Datos Generales)---------------------
        PdfPTable tAux = new PdfPTable(1);

        Cliente clienteDto = null;
        DatosUsuario datosUsuarioVendedor = null;

        try {
            if (this.degustacion.getIdCliente() > 0)
                clienteDto = new ClienteBO(this.degustacion.getIdCliente(), this.conn).getCliente();
            if (this.degustacion.getIdUsuario() > 0)
                datosUsuarioVendedor = new UsuarioBO(this.degustacion.getIdUsuario()).getDatosUsuario();
        } catch (Exception ex) {
            ex.printStackTrace();
        }

        //Datos informativos generales
        PdfPTable tInfoGeneral = new PdfPTable(1);
        tInfoGeneral.setTotalWidth(160);
        tInfoGeneral.setLockedWidth(true);

        obj.agregaCelda(tInfoGeneral, letraNueveBold, Color.lightGray, "ID Degustacin",
                new boolean[] { true, true, true, true }, Element.ALIGN_CENTER, Element.ALIGN_MIDDLE, 0,
                new int[0], 1);
        obj.agregaCelda(tInfoGeneral, letraNueveBoldRojo, "" + this.degustacion.getIdDegustacion(),
                new boolean[] { true, true, true, true }, Element.ALIGN_CENTER, Element.ALIGN_MIDDLE, 0,
                new int[0], 1);

        obj.agregaCelda(tInfoGeneral, letraNueveBold, Color.lightGray, "Fecha Degustacin",
                new boolean[] { true, true, true, true }, Element.ALIGN_CENTER, Element.ALIGN_MIDDLE, 0,
                new int[0], 1);
        obj.agregaCelda(tInfoGeneral, letraNueve,
                DateManage.dateToStringEspanol(this.degustacion.getFechaApertura()),
                new boolean[] { true, true, true, true }, Element.ALIGN_CENTER, Element.ALIGN_MIDDLE, 0,
                new int[0], 1);
        obj.agregaCelda(tInfoGeneral, letraNueveBold, Color.lightGray, "Promotor",
                new boolean[] { true, true, true, true }, Element.ALIGN_CENTER, Element.ALIGN_MIDDLE, 0,
                new int[0], 1);
        obj.agregaCelda(tInfoGeneral, letraNueve,
                datosUsuarioVendedor != null
                        ? (datosUsuarioVendedor.getNombre() + " " + datosUsuarioVendedor.getApellidoPat())
                        : "Sin vendedor asignado",
                new boolean[] { true, true, true, true }, Element.ALIGN_CENTER, Element.ALIGN_MIDDLE, 0,
                new int[0], 1);

        //Pintamos datos informativos Generales en la esquina superior derecha
        PdfContentByte cb = writer.getDirectContent();
        tInfoGeneral.writeSelectedRows(0, -1, doc.right() - 180, doc.top() + 100, cb);

        //Datos de Cliente/Prospecto
        PdfPTable tCliente = new PdfPTable(2);
        tCliente.setTotalWidth(550);
        tCliente.setLockedWidth(true);

        obj.agregaCelda(tCliente, letraNueveBold, Color.lightGray, "Cliente",
                new boolean[] { false, false, false, true }, Element.ALIGN_CENTER, Element.ALIGN_MIDDLE, 0,
                new int[0], 2);

        tAux = new PdfPTable(1);
        tAux.setTotalWidth(275);
        tAux.setLockedWidth(true);

        try {
            obj.agregaCelda(tAux, letraOcho,
                    "Nombre Comercial: " + (clienteDto != null ? clienteDto.getNombreComercial() : ""),
                    new boolean[] { false, true, false, false }, Element.ALIGN_LEFT, Element.ALIGN_TOP, 0,
                    new int[0], 1);
        } catch (Exception ex) {
            ex.printStackTrace();
        }

        obj.agregaTabla(tCliente, tAux, new boolean[] { false, false, false, false }, Element.ALIGN_LEFT,
                Element.ALIGN_TOP, 0, new int[0], 1);

        obj.agregaCelda(tCliente, letraOcho,
                "" + "DOMICILIO: \n" + (clienteDto != null ? "Calle: " + clienteDto.getCalle() : "") + " "
                        + (clienteDto != null ? clienteDto.getNumero() : "") + " "
                        + (clienteDto != null ? clienteDto.getNumeroInterior() : "")
                        + (clienteDto != null ? " Col: " + clienteDto.getColonia() : "")
                        + (clienteDto != null ? " \nDeleg./Municipio: " + clienteDto.getMunicipio() : "")
                        + (clienteDto != null ? " Estado: " + clienteDto.getEstado() : "")
                        + (clienteDto != null ? " \nC.P. " + clienteDto.getCodigoPostal() : ""),
                new boolean[] { false, true, false, true }, Element.ALIGN_LEFT, Element.ALIGN_TOP, 0,
                new int[0], 1);

        obj.agregaTabla(mainTable, tCliente, new boolean[] { true, true, true, true }, Element.ALIGN_CENTER,
                Element.ALIGN_TOP, 0, new int[0], 1);

        //FIN Cabecera (Datos Generales)-----------------

        //DOBLE SALTO DE L?NEA
        obj.agregaCelda(mainTable, letraOcho, null, " ", new boolean[] { false, false, false, false },
                Element.ALIGN_CENTER, Element.ALIGN_MIDDLE, 0, new int[0], 1);
        obj.agregaCelda(mainTable, letraOcho, null, " ", new boolean[] { false, false, false, false },
                Element.ALIGN_CENTER, Element.ALIGN_MIDDLE, 0, new int[0], 1);

        int colsDetalles = 6;
        PdfPTable tDetalles = new PdfPTable(colsDetalles);//6);
        tDetalles.setTotalWidth(550);
        tDetalles.setWidths(new int[] { 200, 70, 70, 70, 70, 70 });
        tDetalles.setLockedWidth(true);

        /*CABECERA*/
        obj.agregaCelda(tDetalles, letraNueveBold, Color.lightGray, "Producto Degustado",
                new boolean[] { true, true, true, true }, Element.ALIGN_CENTER, Element.ALIGN_MIDDLE, 15,
                new int[] { 5, 5, 5, 5 }, 1);
        obj.agregaCelda(tDetalles, letraNueveBold, Color.lightGray, "Hr Inicio",
                new boolean[] { true, true, true, true }, Element.ALIGN_CENTER, Element.ALIGN_MIDDLE, 15,
                new int[] { 5, 5, 5, 5 }, 1);
        obj.agregaCelda(tDetalles, letraNueveBold, Color.lightGray, "Hr Termino",
                new boolean[] { true, true, true, true }, Element.ALIGN_CENTER, Element.ALIGN_MIDDLE, 15,
                new int[] { 5, 5, 5, 5 }, 1);
        obj.agregaCelda(tDetalles, letraNueveBold, Color.lightGray, "Inventario Inicial",
                new boolean[] { true, true, true, true }, Element.ALIGN_CENTER, Element.ALIGN_MIDDLE, 15,
                new int[] { 5, 5, 5, 5 }, 1);
        obj.agregaCelda(tDetalles, letraNueveBold, Color.lightGray, "Inventario Final",
                new boolean[] { true, true, true, true }, Element.ALIGN_CENTER, Element.ALIGN_MIDDLE, 15,
                new int[] { 5, 5, 5, 5 }, 1);
        obj.agregaCelda(tDetalles, letraNueveBold, Color.lightGray, "Piezas Degustadas",
                new boolean[] { true, true, true, true }, Element.ALIGN_CENTER, Element.ALIGN_MIDDLE, 15,
                new int[] { 5, 5, 5, 5 }, 1);

        /*FIN DE CABECERA*/
        Degustacion[] degustacionDtos = new Degustacion[0];
        try {
            degustacionDtos = this.findDegustaciones(this.degustacion.getIdDegustacion(),
                    this.degustacion.getIdEmpresa(), -1, -1, "");
        } catch (Exception e) {
        }

        //Listado de Productos
        for (Degustacion item : degustacionDtos) {

            if (item != null) {

                Concepto conceptoDto = null;

                try {
                    ConceptoBO conceptoBO = new ConceptoBO(item.getIdConcepto(), this.conn);
                    conceptoDto = conceptoBO.getConcepto();
                } catch (Exception e) {
                }

                //Producto
                obj.agregaCelda(tDetalles, letraOcho, null, conceptoDto.getNombreDesencriptado(),
                        new boolean[] { true, true, true, true }, Element.ALIGN_JUSTIFIED, Element.ALIGN_TOP,
                        15, new int[] { 5, 5, 5, 5 }, 1);

                //Inicio
                obj.agregaCelda(tDetalles, letraOcho, null, hora.format(item.getFechaApertura()),
                        new boolean[] { true, true, true, true }, Element.ALIGN_JUSTIFIED, Element.ALIGN_TOP,
                        15, new int[] { 5, 5, 5, 5 }, 1);

                //Termino
                obj.agregaCelda(tDetalles, letraOcho, null, hora.format(item.getFechaCierre()),
                        new boolean[] { true, true, true, true }, Element.ALIGN_RIGHT, Element.ALIGN_TOP, 15,
                        new int[] { 5, 5, 5, 5 }, 1);

                //Inv inicial 
                obj.agregaCelda(tDetalles, letraOcho, null, "" + (item.getCantidad()),
                        new boolean[] { true, true, true, true }, Element.ALIGN_RIGHT, Element.ALIGN_TOP, 15,
                        new int[] { 5, 5, 5, 5 }, 1);

                //inv final 
                obj.agregaCelda(tDetalles, letraOcho, null, "" + (item.getCantidadCierre()),
                        new boolean[] { true, true, true, true }, Element.ALIGN_RIGHT, Element.ALIGN_TOP, 15,
                        new int[] { 5, 5, 5, 5 }, 1);

                //Piezas 
                obj.agregaCelda(tDetalles, letraOcho, null,
                        "" + (item.getCantidad() - item.getCantidadCierre()),
                        new boolean[] { true, true, true, true }, Element.ALIGN_RIGHT, Element.ALIGN_TOP, 15,
                        new int[] { 5, 5, 5, 5 }, 1);

            }
        }

        obj.agregaTabla(mainTable, tDetalles, new boolean[] { false, false, false, false },
                Element.ALIGN_CENTER, Element.ALIGN_TOP, 0, new int[0], 1);

        //DOBLE SALTO DE L?NEA
        obj.agregaCelda(mainTable, letraOcho, null, " ", new boolean[] { false, false, false, false },
                Element.ALIGN_CENTER, Element.ALIGN_MIDDLE, 0, new int[0], 1);
        obj.agregaCelda(mainTable, letraOcho, null, " ", new boolean[] { false, false, false, false },
                Element.ALIGN_CENTER, Element.ALIGN_MIDDLE, 0, new int[0], 1);

        /*prods Vendidos durante degustacion*/

        PdfPTable tVenta = new PdfPTable(4);
        tVenta.setTotalWidth(550);
        tVenta.setWidths(new int[] { 70, 140, 170, 120 });
        tVenta.setLockedWidth(true);

        obj.agregaCelda(tVenta, letraNueveBold, Color.lightGray, "Producto Vendido durante Degutacin",
                new boolean[] { true, true, true, true }, Element.ALIGN_CENTER, Element.ALIGN_MIDDLE, 15,
                new int[] { 5, 5, 5, 5 }, 4);

        Productosvendidos[] pedidoProductoDto = new Productosvendidos[0];

        String filtroBusqueda = " ID_PEDIDO IN ( SELECT ID_PEDIDO FROM sgfens_pedido WHERE ID_EMPRESA = '"
                + this.degustacion.getIdEmpresa() + "' AND ID_TIPO_PEDIDO = 2 AND ID_USUARIO_VENDEDOR = "
                + this.degustacion.getIdUsuario() + " AND " + " ID_ESTATUS_PEDIDO<>2 AND FECHA_PEDIDO BETWEEN '"
                + this.degustacion.getFechaApertura() + "'  AND '" + this.degustacion.getFechaCierre() + "') ";

        try {
            pedidoProductoDto = new ProductosvendidosDaoImpl().findByDynamicWhere(filtroBusqueda, null);
        } catch (Exception e) {
        }

        if (pedidoProductoDto.length > 0) {

            obj.agregaCelda(tVenta, letraOchoBold, null, "Cdigo", new boolean[] { true, true, true, true },
                    Element.ALIGN_CENTER, Element.ALIGN_MIDDLE, 15, new int[] { 5, 5, 5, 5 }, 1);
            obj.agregaCelda(tVenta, letraOchoBold, null, "Nombre", new boolean[] { true, true, true, true },
                    Element.ALIGN_CENTER, Element.ALIGN_MIDDLE, 15, new int[] { 5, 5, 5, 5 }, 1);
            obj.agregaCelda(tVenta, letraOchoBold, null, "Descripcin",
                    new boolean[] { true, true, true, true }, Element.ALIGN_CENTER, Element.ALIGN_MIDDLE, 15,
                    new int[] { 5, 5, 5, 5 }, 1);
            obj.agregaCelda(tVenta, letraOchoBold, null, "Unidades Vendidas",
                    new boolean[] { true, true, true, true }, Element.ALIGN_CENTER, Element.ALIGN_MIDDLE, 15,
                    new int[] { 5, 5, 5, 5 }, 1);

            for (Productosvendidos pedidoProd : pedidoProductoDto) {

                if (pedidoProd != null) {

                    Concepto conceptoDto = null;
                    try {
                        ConceptoBO conceptoBO = new ConceptoBO(pedidoProd.getIdConcepto(), this.conn);
                        conceptoDto = conceptoBO.getConcepto();
                    } catch (Exception e) {
                    }

                    //Cdigo
                    obj.agregaCelda(tVenta, letraOcho, null, conceptoDto.getIdentificacion(),
                            new boolean[] { true, true, true, true }, Element.ALIGN_JUSTIFIED,
                            Element.ALIGN_TOP, 15, new int[] { 5, 5, 5, 5 }, 1);

                    //Nombre
                    obj.agregaCelda(tVenta, letraOcho, null, conceptoDto.getNombreDesencriptado(),
                            new boolean[] { true, true, true, true }, Element.ALIGN_JUSTIFIED,
                            Element.ALIGN_TOP, 15, new int[] { 5, 5, 5, 5 }, 1);

                    //Descripcin
                    obj.agregaCelda(tVenta, letraOcho, null, conceptoDto.getDescripcion(),
                            new boolean[] { true, true, true, true }, Element.ALIGN_RIGHT, Element.ALIGN_TOP,
                            15, new int[] { 5, 5, 5, 5 }, 1);

                    //Unidades Vendidas 
                    obj.agregaCelda(tVenta, letraOcho, null, "" + (pedidoProd.getCantidad()),
                            new boolean[] { true, true, true, true }, Element.ALIGN_RIGHT, Element.ALIGN_TOP,
                            15, new int[] { 5, 5, 5, 5 }, 1);

                }

            }
        } else {

            obj.agregaCelda(tVenta, letraOcho, null, "No se registrarn datos.",
                    new boolean[] { true, true, true, true }, Element.ALIGN_CENTER, Element.ALIGN_MIDDLE, 15,
                    new int[] { 5, 5, 5, 5 }, 4);

        }

        obj.agregaTabla(mainTable, tVenta, new boolean[] { true, true, true, true }, Element.ALIGN_CENTER,
                Element.ALIGN_TOP, 0, new int[0], 1);

        //DOBLE SALTO DE L?NEA
        obj.agregaCelda(mainTable, letraOcho, null, " ", new boolean[] { false, false, false, false },
                Element.ALIGN_CENTER, Element.ALIGN_MIDDLE, 0, new int[0], 1);
        obj.agregaCelda(mainTable, letraOcho, null, " ", new boolean[] { false, false, false, false },
                Element.ALIGN_CENTER, Element.ALIGN_MIDDLE, 0, new int[0], 1);

        /*Comentarios Adicionales*/
        PdfPTable tComenst = new PdfPTable(1);
        tComenst.setTotalWidth(550);
        tComenst.setWidths(new int[] { 550 });
        tComenst.setLockedWidth(true);

        obj.agregaCelda(tComenst, letraNueveBold, Color.lightGray, "Comentarios",
                new boolean[] { true, true, true, true }, Element.ALIGN_CENTER, Element.ALIGN_MIDDLE, 15,
                new int[] { 5, 5, 5, 5 }, 2);

        obj.agregaCelda(tComenst, letraOcho, null, this.degustacion.getComentariosCierre(),
                new boolean[] { true, true, true, true }, Element.ALIGN_CENTER, Element.ALIGN_MIDDLE, 15,
                new int[] { 5, 5, 5, 5 }, 2);

        obj.agregaTabla(mainTable, tComenst, new boolean[] { true, true, true, true }, Element.ALIGN_CENTER,
                Element.ALIGN_TOP, 0, new int[0], 1);

        //FIN DE CONTENIDO --------

        //Aadimos tabla principal construida al documento
        doc.add(mainTable);
        mainTable.flushContent();

    } catch (Exception ex) {
        msgError = "No se ha podido generar la representacin impresa de la Degustacion en formato PDF:<br/>"
                + ex.toString();
    } finally {
        if (doc.isOpen())
            doc.close();
    }

    if (!msgError.equals("")) {
        throw new Exception(msgError);
    }

    return baos;

}

From source file:CPS.Core.TODOLists.PDFExporter.java

License:Open Source License

private Document prepareDocument(String filename, final String title, final String author, final String creator,
        final Rectangle pageSize) {

    System.out.println("DEBUG(PDFExporter): Creating document: " + filename);

    Document d = new Document();

    d.setPageSize(pageSize);/*from  w w  w .ja  v a 2  s .c om*/
    // TODO alter page orientation?  maybe useful for seed order worksheet

    d.addTitle(title);
    d.addAuthor(author);
    //        d.addSubject( );
    //        d.addKeywords( );
    d.addCreator(creator);

    // left, right, top, bottom - scale in points (~72 points/inch)
    d.setMargins(35, 35, 35, 44);

    try {
        PdfWriter writer = PdfWriter.getInstance(d, new FileOutputStream(filename));
        // add header and footer
        writer.setPageEvent(new PdfPageEventHelper() {
            public void onEndPage(PdfWriter writer, Document document) {
                try {
                    Rectangle page = document.getPageSize();

                    PdfPTable head = new PdfPTable(3);
                    head.getDefaultCell().setBorderWidth(0);
                    head.getDefaultCell().setHorizontalAlignment(PdfPCell.ALIGN_LEFT);
                    head.addCell(new Phrase(author, fontHeadFootItal));

                    head.getDefaultCell().setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
                    head.addCell(new Phrase(title, fontHeadFootReg));

                    head.getDefaultCell().setHorizontalAlignment(PdfPCell.ALIGN_RIGHT);
                    head.addCell("");

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

                    PdfPTable foot = new PdfPTable(3);

                    foot.getDefaultCell().setBorderWidth(0);
                    foot.getDefaultCell().setHorizontalAlignment(PdfPCell.ALIGN_LEFT);
                    foot.addCell(new Phrase(creator, fontHeadFootItal));

                    foot.getDefaultCell().setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
                    foot.addCell("");

                    foot.getDefaultCell().setHorizontalAlignment(PdfPCell.ALIGN_RIGHT);
                    foot.addCell(new Phrase("Page " + document.getPageNumber(), fontHeadFootReg));

                    foot.setTotalWidth(page.getWidth() - document.leftMargin() - document.rightMargin());
                    foot.writeSelectedRows(0, -1, document.leftMargin(), document.bottomMargin(),
                            writer.getDirectContent());
                } catch (Exception e) {
                    throw new ExceptionConverter(e);
                }
            }
        });
    } catch (Exception e) {
        e.printStackTrace();
    }

    return d;
}

From source file:is.idega.idegaweb.egov.printing.business.DocumentBusinessBean.java

License:Open Source License

public void createCommuneFooter(PdfWriter writer) throws Exception {

    PdfContentByte cb = writer.getDirectContent();
    Font nameFont = getDefaultParagraphFont();
    nameFont.setSize(9);/*www.  j av  a 2s  .co  m*/
    Font textFont = getDefaultTextFont();
    textFont.setSize(9);

    PdfPTable table = new PdfPTable(4);
    table.getDefaultCell().setBorder(Rectangle.NO_BORDER);
    table.getDefaultCell().setNoWrap(true);

    IWBundle iwb = getIWApplicationContext().getIWMainApplication()
            .getBundle(is.idega.idegaweb.egov.message.business.MessageConstants.IW_BUNDLE_IDENTIFIER);

    table.addCell(new Phrase(iwb.getProperty("commune.name_mailaddr", "Mailaddress"), nameFont));
    table.addCell(new Phrase(iwb.getProperty("commune.name_visitaddr", "Visitaddress"), nameFont));
    table.addCell(new Phrase(iwb.getProperty("commune.name_contact", "Contact"), nameFont));
    table.addCell(new Phrase(iwb.getProperty("commune.name_org_nr", "Organizationsnr"), nameFont));

    table.addCell(new Phrase(iwb.getProperty("commune.mail_name", "Mail name"), getTextFont()));
    table.addCell(new Phrase(iwb.getProperty("commune.visit_name", "Visit name"), textFont));
    table.addCell(new Phrase(iwb.getProperty("commune.website", "www.some-place.com"), textFont));
    table.addCell(new Phrase(iwb.getProperty("commune.org_number", "XXXXXX-XXXX"), textFont));

    table.addCell(new Phrase(iwb.getProperty("commune.mail_zip", "Zip code"), textFont));
    table.addCell(new Phrase(iwb.getProperty("commune.visit_streetaddr", "Street and number,"), textFont));
    table.addCell(new Phrase(iwb.getProperty("commune.support_email", "email@someplace.com"), textFont));
    table.addCell(new Phrase(" ", textFont));

    table.addCell(new Phrase(" ", textFont));
    table.addCell(new Phrase(iwb.getProperty("commune.visit_zip", "Visit zip"), textFont));
    table.addCell(new Phrase(iwb.getProperty("commune.office_phone", "office phone"), textFont));
    table.addCell(new Phrase(" ", textFont));

    int distFromBottomMM = 30;
    int[] widths = { 20, 20, 30, 20 };
    table.setWidths(widths);
    table.setTotalWidth(getPointsFromMM(210 - 25 - 20));
    table.writeSelectedRows(0, -1, getPointsFromMM(25), getPointsFromMM(distFromBottomMM), cb);

    PdfContentByte linebyte = new PdfContentByte(writer);
    // we add some crosses to visualize the destinations

    linebyte.moveTo(getPointsFromMM(25), getPointsFromMM(distFromBottomMM + 2));
    linebyte.lineTo(getPointsFromMM(210 - 25), getPointsFromMM(distFromBottomMM + 2));

    linebyte.stroke();

    // we add the template on different positions
    cb.add(linebyte);
}