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

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

Introduction

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

Prototype

public void setTotalWidth(float columnWidth[]) throws DocumentException 

Source Link

Document

Sets the full width of the table from the absolute column width.

Usage

From source file:biblivre3.administration.reports.BaseBiblivreReport.java

License:Open Source License

@Override
public void onEndPage(PdfWriter writer, Document document) {
    try {//from w w w  . jav  a  2  s. co  m
        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();// w w w.  j  a  v a2s . com
    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)
 *///from  ww w  . ja  v a2 s  .  c  o  m
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./*from  w w  w . j  a v  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:candelaria.presentacion.beans.DetalleFacturaControlador.java

public void imprimirFac() {
    //DateFormat dfDateFull = DateFormat.getDateInstance(DateFormat.FULL);
    try {/* www .j ava  2s  .com*/

        //Generamos el archivo PDF
        String directorioArchivos;
        ServletContext ctx = (ServletContext) FacesContext.getCurrentInstance().getExternalContext()
                .getContext();
        directorioArchivos = ctx.getRealPath("/") + "reports";
        String name = directorioArchivos + "/document-factura.pdf";
        Document document = new Document();
        PdfWriter.getInstance(document, new FileOutputStream(name));
        //PdfWriter writer = PdfWriter.getInstance(document,
        //new FileOutputStream("C:"));

        Paragraph paragraph = new Paragraph();
        Paragraph paragraph1 = new Paragraph();
        PdfPTable table = new PdfPTable(4);
        PdfPTable table1 = new PdfPTable(2);
        PdfPTable table2 = new PdfPTable(1);
        PdfPTable table3 = new PdfPTable(2);
        PdfPTable table5 = new PdfPTable(4);
        PdfPTable tablaF = new PdfPTable(1);
        PdfPTable tablaF1 = new PdfPTable(3);
        PdfPTable tablaF2 = new PdfPTable(3);

        paragraph.add("\n\n\n");
        paragraph.setAlignment(Paragraph.ALIGN_CENTER);

        paragraph.add("YUQUI OLGA");
        paragraph.setAlignment(Paragraph.ALIGN_CENTER);
        paragraph.add("\n");
        paragraph.add("Dir. La Candelaria Barrio Nuevo");
        paragraph.setAlignment(Paragraph.ALIGN_CENTER);
        paragraph.add("\n");
        paragraph.add("Telf: 3014019");
        paragraph.setAlignment(Paragraph.ALIGN_CENTER);
        paragraph.add("\n");
        paragraph.add("Penipe - Ecuador");
        paragraph.setAlignment(Paragraph.ALIGN_CENTER);
        paragraph.add("\n");
        paragraph.add("\n");
        paragraph.setAlignment(Paragraph.ALIGN_CENTER);
        paragraph.add("AUTORIZACION SRI __________ - RUC.: 0600750897001");
        paragraph.setAlignment(Paragraph.ALIGN_CENTER);
        paragraph.add("\n");
        paragraph.add("FACTURA: " + facturaSel.getId_factura());
        paragraph.setAlignment(Paragraph.ALIGN_CENTER);

        paragraph.add("\n\n\n");
        paragraph.setAlignment(Paragraph.ALIGN_CENTER);

        paragraph1.add("\n\n");
        paragraph.setAlignment(Paragraph.ALIGN_CENTER);

        document.open();

        //primera linea   
        PdfPCell cell5 = new PdfPCell(new Paragraph("Fecha: " + fecha_cambiada));
        //PdfPCell cell6 = new PdfPCell(new Paragraph("Factura #: " + facturaSel.getId_factura()));
        PdfPCell cell7 = new PdfPCell(new Paragraph("Cedula: " + facturaSel.getId_cliente().getRuc_cliente()));
        //segunda linea
        PdfPCell cell8 = new PdfPCell(
                new Paragraph("Nombre Cliente: " + facturaSel.getId_cliente().getNombres_cliente()
                        + facturaSel.getId_cliente().getApellidos_cliente()));
        //tercera fila
        PdfPCell cell9 = new PdfPCell(
                new Paragraph("Direccin: " + facturaSel.getId_cliente().getDireccion_cliente()));
        PdfPCell cell10 = new PdfPCell(
                new Paragraph("Tlefono: " + facturaSel.getId_cliente().getTelefono_cliente()));

        PdfPCell cellf1 = new PdfPCell(new Paragraph("SubTotal     " + totalHoja));
        PdfPCell cellf2 = new PdfPCell(new Paragraph("Impuesto Iva " + impuestoFactura));
        PdfPCell cellf21 = new PdfPCell(new Paragraph("___________________"));
        PdfPCell cellf22 = new PdfPCell(new Paragraph("___________________"));
        PdfPCell cellf3 = new PdfPCell(new Paragraph("TOTAL        " + totalFactura));
        PdfPCell cellf31 = new PdfPCell(new Paragraph("FIRMA AUTORIZADA"));
        PdfPCell cellf32 = new PdfPCell(new Paragraph("FIRMA CLIENTE"));
        PdfPCell cell11 = new PdfPCell(new Paragraph("Cantidad"));
        PdfPCell cell12 = new PdfPCell(new Paragraph("Descripcin"));
        PdfPCell cell13 = new PdfPCell(new Paragraph("V. Unitario"));
        PdfPCell cell14 = new PdfPCell(new Paragraph("V. Total"));

        cell5.setHorizontalAlignment(Element.ALIGN_LEFT);
        //cell6.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell7.setHorizontalAlignment(Element.ALIGN_RIGHT);

        cellf1.setHorizontalAlignment(Element.ALIGN_RIGHT);
        cellf2.setHorizontalAlignment(Element.ALIGN_RIGHT);
        cellf3.setHorizontalAlignment(Element.ALIGN_RIGHT);

        cellf21.setHorizontalAlignment(Element.ALIGN_CENTER);
        cellf31.setHorizontalAlignment(Element.ALIGN_CENTER);
        cellf22.setHorizontalAlignment(Element.ALIGN_CENTER);
        cellf32.setHorizontalAlignment(Element.ALIGN_CENTER);

        cell8.setHorizontalAlignment(Element.ALIGN_LEFT);
        cell9.setHorizontalAlignment(Element.ALIGN_LEFT);
        cell10.setHorizontalAlignment(Element.ALIGN_RIGHT);

        cellf21.setBorder(Rectangle.NO_BORDER);
        cellf31.setBorder(Rectangle.NO_BORDER);
        cellf22.setBorder(Rectangle.NO_BORDER);
        cellf32.setBorder(Rectangle.NO_BORDER);

        cell5.setBorder(Rectangle.NO_BORDER);
        //cell6.setBorder(Rectangle.NO_BORDER);
        cell7.setBorder(Rectangle.NO_BORDER);
        cell8.setBorder(Rectangle.NO_BORDER);

        cell9.setBorder(Rectangle.NO_BORDER);
        cell10.setBorder(Rectangle.NO_BORDER);
        //cell7.setBorder(Rectangle.NO_BORDER);
        //cell8.setBorder(Rectangle.NO_BORDER);

        cell11.setBorder(Rectangle.NO_BORDER);
        cell12.setBorder(Rectangle.NO_BORDER);
        cell13.setBorder(Rectangle.NO_BORDER);
        cell14.setBorder(Rectangle.NO_BORDER);

        cellf1.setBorder(Rectangle.NO_BORDER);
        cellf2.setBorder(Rectangle.NO_BORDER);
        cellf3.setBorder(Rectangle.NO_BORDER);

        cell11.setHorizontalAlignment(Element.ALIGN_LEFT);
        cell12.setHorizontalAlignment(Element.ALIGN_LEFT);
        cell13.setHorizontalAlignment(Element.ALIGN_RIGHT);
        cell14.setHorizontalAlignment(Element.ALIGN_RIGHT);

        table1.addCell(cell5);
        //table1.addCell(cell6);
        table1.addCell(cell7);
        //aadir segunda fila
        table2.addCell(cell8);
        //aadir tercera fila
        table3.addCell(cell9);
        table3.addCell(cell10);
        //aadir cuarta fila
        table5.addCell(cell11);
        table5.addCell(cell12);
        table5.addCell(cell13);
        table5.addCell(cell14);
        tablaF.addCell(cellf1);

        tablaF1.addCell(cellf21);
        tablaF1.addCell(cellf22);
        tablaF1.addCell(cellf2);
        tablaF2.addCell(cellf31);
        tablaF2.addCell(cellf32);
        tablaF2.addCell(cellf3);

        for (int x = 0; x < lstDetalleFactura.size(); x++) {

            PdfPCell cell1 = new PdfPCell(new Paragraph("" + lstDetalleFactura.get(x).getCantidad()));
            PdfPCell cell2 = new PdfPCell(new Paragraph(
                    "" + lstDetalleFactura.get(x).getId_producto().getId_categoria().getNombre_producto()));
            PdfPCell cell3 = new PdfPCell(new Paragraph(
                    "" + lstDetalleFactura.get(x).getId_producto().getId_categoria().getPrecio_producto()));
            PdfPCell cell4 = new PdfPCell(new Paragraph("" + lstDetalleFactura.get(x).getValor_total()));
            /* Chunk chunk = new Chunk(
             "\n" + lstDetalles.get(x).getCantidadDet() + "       " + lstDetalles.get(x).getIdSer().getNombreSer() + "             " + lstDetalles.get(x).getIdSer().getPrecioSer()
             + "                          " + lstDetalles.get(x).getPrecio());*/

            cell1.setBorder(Rectangle.NO_BORDER);
            cell2.setBorder(Rectangle.NO_BORDER);
            cell3.setBorder(Rectangle.NO_BORDER);
            cell4.setBorder(Rectangle.NO_BORDER);

            cell1.setHorizontalAlignment(Element.ALIGN_LEFT);
            cell2.setHorizontalAlignment(Element.ALIGN_LEFT);
            cell3.setHorizontalAlignment(Element.ALIGN_RIGHT);
            cell4.setHorizontalAlignment(Element.ALIGN_RIGHT);

            cell1.setMinimumHeight(10f);
            cell2.setMinimumHeight(5f);

            table.setTotalWidth(100f);
            table.addCell(cell1);
            table.addCell(cell2);
            table.addCell(cell3);
            table.addCell(cell4);

            //aadir primera fila
            table.setSpacingBefore(30f);
            table.setSpacingAfter(50f);

            //paragraph4.add(chunk);
            //paragraph4.setAlignment(Paragraph.ALIGN_JUSTIFIED_ALL);
        }

        document.add(paragraph);
        document.add(table1);
        document.add(table2);
        document.add(table3);
        document.add(paragraph1);
        document.add(table5);
        document.add(table);
        document.add(tablaF);
        document.add(tablaF1);
        document.add(tablaF2);
        //document.setFooter(event);

        document.close();
        //----------------------------
        //Abrimos el archivo PDF
        FacesContext context = FacesContext.getCurrentInstance();
        HttpServletResponse response = (HttpServletResponse) context.getExternalContext().getResponse();
        response.setContentType("application/pdf");
        response.setHeader("Content-disposition", "inline=filename=" + name);
        try {
            response.getOutputStream().write(Util.getBytesFromFile(new File(name)));
            response.getOutputStream().flush();
            response.getOutputStream().close();
            context.responseComplete();

        } catch (IOException e) {
            e.printStackTrace();
        }

    } catch (Exception e) {
        e.printStackTrace();
    }

}

From source file:ch.gpb.elexis.kgexporter.pdf.PdfHandler.java

License:Open Source License

public static PdfPTable createTable2(LinkedList<String[]> laborBlatt) throws DocumentException, IOException {
    int noOfCols = laborBlatt.get(0)[0].length();
    PdfPTable table = new PdfPTable(noOfCols);

    float[] colWidths = new float[noOfCols];
    colWidths[0] = 200f;/*from w w w  .  j  a  v  a  2 s . c om*/
    for (int i = 1; i < colWidths.length; i++) {
        colWidths[i] = 40f;
    }

    table.setTotalWidth(colWidths);
    table.setLockedWidth(true);

    // the cell object
    PdfPCell cell;

    for (String[] strings : laborBlatt) {

        for (int i = 0; i < strings.length; i++) {
            System.out.print(i + ":" + strings[i]);
            cell = new PdfPCell(new Phrase(strings[i], fontTimesSmall));

            cell.setUseBorderPadding(true);
            //
            // Setting cell's border width and color
            //
            cell.setBorderWidth(0.5f);

            table.addCell(cell);

        }
        //System.out.println("----------");
        //System.out.println();
    }

    // we add a cell with colspan 3
    return table;
}

From source file:com.aryjr.nheengatu.testes.AbsolutePosition.java

License:Open Source License

private static PdfPTable createTable() {
    final PdfPTable table = new PdfPTable(3);
    table.setTotalWidth(200);
    PdfPCell cell = new PdfPCell(new Paragraph("header with colspan 3"));
    cell.setColspan(3);/*  w  ww  .jav  a 2 s . co  m*/
    table.addCell(cell);
    table.addCell("1.1");
    table.addCell("2.1");
    table.addCell("3.1");
    table.addCell("1.2");
    table.addCell("2.2");
    table.addCell("3.2");
    cell = new PdfPCell(new Paragraph("cell test1"));
    cell.setBorderColor(new Color(255, 0, 0));
    table.addCell(cell);
    cell = new PdfPCell(new Paragraph("cell test2"));
    cell.setColspan(2);
    cell.setBackgroundColor(new Color(0xC0, 0xC0, 0xC0));
    table.addCell(cell);
    return table;
}

From source file:com.krawler.esp.servlets.AppraisalDetails.java

License:Open Source License

private ByteArrayOutputStream AppraisalDetail(HttpServletRequest request, Session session, boolean isEmm)
        throws JSONException, SessionExpiredException, DocumentException, ServiceException, IOException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    String[] colHeader = { "Employee Name", "Appraisal Cycle Name", "Appraisal Cycle Start Date",
            "Appraisal Cycle End Date", "Total No. of Appraisals", "No. of Appraisals submitted",
            "Overall Self Comment", "Overall Appraiser Comments", "Overall Competency Score", "Competencies" };
    String[] dataIndex = { "empname", "appcylename", "appcylestdate", "appcylendate", "totalappraisal",
            "appraisalsubmitted", "empcomment", "mancom", "manavgwght", "" };
    String[] compHeader = { "Name", "Description", "Self Appraisal Score", "Self Appraisal Comment",
            "Appraiser Competency Score", "Appraiser Comments" };
    String[] compDataIndex = { "comptename", "comptdesc", "selfcompscore", "selfcomment", "compmanwght" };
    String[] compGoalHeader = { "Goals", "Assigned By", "Appraiser Rating", "Appraiser Comment", "Self Rating",
            "Self Comments" };
    String[] compGoalDataIndex = { "gname", "assignedby", "gmanrat", "mangoalcomment", "gemprat",
            "empgoalcomment" };
    String managerComments = "";
    String scoreAvg = "";
    String companyid = null;/*from  w w w .ja va2s  .c o m*/
    Transaction tx = null;
    PdfWriter writer = null;
    try {
        Document document = new Document(PageSize.A4.rotate(), 25, 25, 25, 25);
        writer = PdfWriter.getInstance(document, baos);
        writer.setPageEvent(new EndPage());
        document.open();
        java.awt.Color tColor = new Color(9, 9, 9);
        fontSmallBold.setColor(tColor);
        Paragraph p = new Paragraph();

        PdfPTable table = new PdfPTable(2);
        table.setWidthPercentage(100);
        table.setWidths(new float[] { 55, 75 });

        PdfPTable mainTable = new PdfPTable(1);
        mainTable.setTotalWidth(90);
        mainTable.setWidthPercentage(100);
        mainTable.setSpacingBefore(20);

        PdfPCell headcell = null;
        headcell = new PdfPCell(new Paragraph("Appraisal Details", fontHeadingMediumBold));
        headcell.setBackgroundColor(new Color(0xEEEEEE));
        headcell.setPadding(5);
        mainTable.addCell(headcell);
        document.add(mainTable);

        String str = hrmsManager.getAppraisalReport(session, request);
        JSONObject jobjTemplate = new JSONObject(str);
        com.krawler.utils.json.base.JSONArray jarr = jobjTemplate.getJSONArray("data");
        String goalstr = "";
        User user = (User) session.get(User.class, request.getParameter("userid"));
        companyid = user.getCompany().getCompanyID();
        if (hrmsManager.checkModule("goal", session, request, companyid))
            goalstr = hrmsManager.getAppraisalReportGoalsforGrid(session, request);
        com.krawler.utils.json.base.JSONArray jarr2 = jarr.getJSONObject(0).getJSONArray("data");
        JSONObject jobjAppraisal = new JSONObject(jarr2.getString(0));
        jarr = jobjAppraisal.getJSONArray("competencies");
        int headlen = colHeader.length;
        if (jarr.length() < 1) {
            headlen = headlen - 1;
        }
        for (int i = 0; i < headlen; i++) {
            PdfPCell pcell = new PdfPCell(new Paragraph(colHeader[i], fontMediumBold));
            pcell.setBorder(0);
            if (i == 0)
                pcell.setPaddingTop(10);
            pcell.setPaddingLeft(15);
            pcell.setPaddingBottom(4);
            pcell.setBorderColor(new Color(0xF2F2F2));
            pcell.setHorizontalAlignment(Element.ALIGN_LEFT);
            pcell.setVerticalAlignment(Element.ALIGN_LEFT);
            table.addCell(pcell);

            if (!dataIndex[i].equals("mancom")) {
                pcell = new PdfPCell(new Paragraph(!dataIndex[i].equals("")
                        ? !jobjAppraisal.isNull(dataIndex[i]) ? jobjAppraisal.getString(dataIndex[i]) : ""
                        : "", fontSmallRegular));
                if (i == 0)
                    pcell.setPaddingTop(10);
                pcell.setBorder(0);
                pcell.setPaddingLeft(10);
                pcell.setPaddingBottom(4);
                pcell.setBorderColor(new Color(0xF2F2F2));
                pcell.setHorizontalAlignment(Element.ALIGN_LEFT);
                pcell.setVerticalAlignment(Element.ALIGN_LEFT);
                table.addCell(pcell);
            } else {
                if (!jobjAppraisal.isNull(dataIndex[i])) {
                    String[] spl = jobjAppraisal.getString(dataIndex[i]).split(",");
                    String strData = "";
                    for (int counter = 0; counter < spl.length; counter++) {
                        strData += spl[counter] + " \n";
                    }
                    pcell = new PdfPCell(new Paragraph(strData, fontSmallRegular));
                    if (i == 0)
                        pcell.setPaddingTop(10);
                    pcell.setBorder(0);
                    pcell.setPaddingLeft(10);
                    pcell.setPaddingBottom(4);
                    pcell.setBorderColor(new Color(0xF2F2F2));
                    pcell.setHorizontalAlignment(Element.ALIGN_LEFT);
                    pcell.setVerticalAlignment(Element.ALIGN_LEFT);
                    table.addCell(pcell);
                }
            }
        }

        document.add(table);

        PdfPTable compTable = new PdfPTable(6);
        compTable.setWidthPercentage(100);
        compTable.setWidths(new float[] { 50, 60, 30, 50, 42, 70 });
        compTable.setSpacingBefore(20);
        compTable.setHeaderRows(1);

        for (int i = 0; i < compHeader.length; i++) {
            PdfPCell pcell = new PdfPCell(new Paragraph(compHeader[i], fontMediumBold));
            pcell.setBorder(0);
            pcell.setBorder(PdfPCell.BOX);
            pcell.setPadding(4);
            pcell.setBorderColor(Color.GRAY);
            pcell.setHorizontalAlignment(Element.ALIGN_CENTER);
            compTable.addCell(pcell);
        }

        for (int i = 0; i < jarr.length(); i++) {
            jobjAppraisal = jarr.getJSONObject(i);
            for (int k = 0; k < compHeader.length; k++) {
                if (k != compHeader.length - 1) {
                    scoreAvg = "";
                    if (!jobjAppraisal.isNull(compDataIndex[k]) && compDataIndex[k].equals("compmanwght")) {
                        scoreAvg = jobjAppraisal.getString("nominalRat");
                        Font font = new Font(Font.HELVETICA, 8, Font.BOLD, Color.BLACK);
                        Chunk chunk1 = new Chunk(jobjAppraisal.getString(compDataIndex[k]) + "\n\n",
                                fontSmallRegular);
                        Chunk chunk2 = null;
                        if (!StringUtil.isNullOrEmpty(request.getParameter("pdfEmail"))) {
                            //                                user=(User)session.get(User.class,request.getParameter("userid"));
                            //                                companyid=user.getCompany().getCompanyID();
                            if (hrmsManager.checkModule("modaverage", session, request, companyid)) {
                                chunk2 = new Chunk("[Mod Avg:  " + scoreAvg + " ]", font);
                            } else {
                                chunk2 = new Chunk("[Avg:  " + scoreAvg + " ]", font);
                            }
                        } else {
                            if (hrmsManager.checkModule("modaverage", session, request)) {
                                chunk2 = new Chunk("[Mod Avg:  " + scoreAvg + " ]", font);
                            } else {
                                chunk2 = new Chunk("[Avg:  " + scoreAvg + " ]", font);
                            }
                        }
                        Phrase phrase1 = new Phrase();
                        phrase1.add(chunk1);
                        phrase1.add(chunk2);

                        p = new Paragraph();
                        p.add(phrase1);
                    }
                    PdfPCell pcell = new PdfPCell();
                    if (!scoreAvg.equals("")) {
                        pcell = new PdfPCell(new Paragraph(p));
                        pcell.setPadding(0);
                        pcell.setPaddingTop(2);
                        pcell.setPaddingBottom(4);
                    } else {
                        if (!jobjAppraisal.isNull(compDataIndex[k])) {
                            String htmlStr = jobjAppraisal.getString(compDataIndex[k]);
                            htmlStr = htmlStr.replaceAll("\n", "<br>");
                            StyleSheet st = new StyleSheet();
                            st.loadTagStyle("body", "face", "HELVETICA");
                            st.loadTagStyle("body", "size", "1");
                            st.loadTagStyle("body", "leading", "8,0");
                            HTMLWorker worker = new HTMLWorker(document);
                            StringReader stringReader = new StringReader(htmlStr);
                            ArrayList listStr = HTMLWorker.parseToList(stringReader, st);
                            pcell.setPadding(4);
                            for (int htmlCount = 0; htmlCount < listStr.size(); ++htmlCount) {
                                if (!listStr.get(htmlCount).toString().equals("[]"))
                                    pcell.addElement((Element) listStr.get(htmlCount));
                            }
                        } else
                            pcell = new PdfPCell(new Paragraph(
                                    !jobjAppraisal.isNull(compDataIndex[k])
                                            ? hrmsManager.serverHTMLStripper(
                                                    jobjAppraisal.getString(compDataIndex[k]))
                                            : "",
                                    fontSmallRegular));
                    }
                    pcell.setBorder(PdfPCell.BOTTOM | PdfPCell.LEFT | PdfPCell.RIGHT);
                    pcell.setBorderColor(Color.GRAY);
                    pcell.setHorizontalAlignment(
                            compDataIndex[k].equals("comptename") || compDataIndex[k].equals("comptdesc")
                                    || compDataIndex[k].equals("selfcomment") ? Element.ALIGN_LEFT
                                            : Element.ALIGN_CENTER);
                    pcell.setVerticalAlignment(
                            compDataIndex[k].equals("comptdesc") || compDataIndex[k].equals("comptdesc")
                                    || compDataIndex[k].equals("selfcomment") ? Element.ALIGN_LEFT
                                            : Element.ALIGN_CENTER);
                    compTable.addCell(pcell);

                } else {
                    jarr2 = jobjAppraisal.getJSONArray("comments");
                    managerComments = "";
                    int commentCount = 1;
                    for (int j = jarr2.length() - 1; j >= 0; j--) {
                        jobjTemplate = jarr2.getJSONObject(j);
                        managerComments += commentCount + ")  " + jobjTemplate.getString("managercomment")
                                + "\n\n";
                        commentCount++;
                    }
                    PdfPCell pcell = new PdfPCell(new Paragraph(managerComments, fontSmallRegular));
                    pcell.setBorder(PdfPCell.BOTTOM | PdfPCell.LEFT | PdfPCell.RIGHT);
                    pcell.setPadding(4);
                    pcell.setBorderColor(Color.GRAY);
                    pcell.setHorizontalAlignment(Element.ALIGN_LEFT);
                    pcell.setVerticalAlignment(Element.ALIGN_LEFT);
                    compTable.addCell(pcell);
                }
            }
        }

        PdfPTable helpTable = new PdfPTable(1);
        helpTable.setTotalWidth(90);
        helpTable.setWidthPercentage(100);
        helpTable.setSpacingBefore(20);

        PdfPCell pcell = new PdfPCell(new Paragraph(
                "Mod Avg. : Average of ratings after excluding a minimum and a maximum rating. For e.g, mod average of 2, 3, 2, 4, 5, 3 is (2+3+4+3)/4",
                helpFont));
        pcell.setBorder(0);
        pcell.setPadding(4);
        pcell.setHorizontalAlignment(Element.ALIGN_LEFT);
        helpTable.addCell(pcell);

        document.add(compTable);
        if (!StringUtil.isNullOrEmpty(request.getParameter("pdfEmail"))) {
            if (hrmsManager.checkModule("modaverage", session, request, companyid)) {
                document.add(helpTable);
            }
        } else {
            if (hrmsManager.checkModule("modaverage", session, request)) {
                document.add(helpTable);
            }
        }

        if (!StringUtil.isNullOrEmpty(goalstr)) {
            PdfPTable compgTable = new PdfPTable(6);
            compgTable.setWidthPercentage(100);
            compgTable.setWidths(new float[] { 50, 60, 30, 50, 42, 70 });
            compgTable.setSpacingBefore(20);
            compgTable.setHeaderRows(1);
            for (int i = 0; i < compGoalHeader.length; i++) {
                PdfPCell pgcell = new PdfPCell(new Paragraph(compGoalHeader[i], fontMediumBold));
                pgcell.setBorder(0);
                pgcell.setBorder(PdfPCell.BOX);
                pgcell.setPadding(4);
                pgcell.setBorderColor(Color.GRAY);
                pgcell.setHorizontalAlignment(Element.ALIGN_CENTER);
                compgTable.addCell(pgcell);
            }
            JSONObject jobjTemplates = new JSONObject(goalstr);
            com.krawler.utils.json.base.JSONArray jarr11 = jobjTemplates.getJSONArray("data");
            JSONObject jobjl = new JSONObject();
            for (int i = 0; i < jarr11.length(); i++) {
                jobjl = jarr11.getJSONObject(i);
                for (int k = 0; k < compGoalHeader.length; k++) {
                    pcell = new PdfPCell(
                            new Paragraph(
                                    !jobjl.isNull(compGoalDataIndex[k]) ? StringUtil
                                            .serverHTMLStripper(jobjl.getString(compGoalDataIndex[k])) : "",
                                    fontSmallRegular));
                    pcell.setBorder(PdfPCell.BOTTOM | PdfPCell.LEFT | PdfPCell.RIGHT);
                    pcell.setBorderColor(Color.GRAY);
                    pcell.setPadding(4);
                    pcell.setHorizontalAlignment(Element.ALIGN_CENTER);
                    pcell.setVerticalAlignment(Element.ALIGN_CENTER);
                    compgTable.addCell(pcell);
                }
            }
            document.add(compgTable);

            document.newPage();
            document.close();
        }
        if (!StringUtil.isNullOrEmpty(request.getParameter("pdfEmail"))) {
            String ipaddr = "";
            if (StringUtil.isNullOrEmpty(request.getHeader("x-real-ip"))) {
                ipaddr = request.getRemoteAddr();
            } else {
                ipaddr = request.getHeader("x-real-ip");
            }
            User u = (User) session.get(User.class, request.getParameter("d"));
            User u1 = (User) session.get(User.class, request.getParameter("userid"));
            Appraisalcycle appcy = (Appraisalcycle) session.get(Appraisalcycle.class,
                    request.getParameter("appraisalcycid"));
            //AuditAction action = (AuditAction) session.load(AuditAction.class, AuditAction.Appraisal_Report_Download);
            String details = "";
            if (StringUtil.equal(request.getParameter("d"), request.getParameter("userid"))) {
                details = "User " + u.getFirstName() + " " + u.getLastName() + " has downloaded self"
                        + " appraisal report for appraisal cycle " + appcy.getCyclename()
                        + " through email link";
            } else {
                details = "Reviewer " + u.getFirstName() + " " + u.getLastName() + " has downloaded "
                        + u1.getFirstName() + " " + u1.getLastName() + "'s"
                        + " appraisal report for appraisal cycle " + appcy.getCyclename()
                        + " through email link";
            }
            tx = session.beginTransaction();
            //@@ProfileHandler.insertAuditLog(session, action, details, ipaddr, u);
            tx.commit();
        } else {
            String details = "";
            User u = null;
            String appCycleID = request.getParameter("appraisalcycid");
            Appraisalcycle appcy = (Appraisalcycle) session.get(Appraisalcycle.class, appCycleID);
            String userID = request.getParameter("userid");
            if (StringUtil.isNullOrEmpty(userID)) {
                userID = AuthHandler.getUserid(request);
                u = (User) session.get(User.class, userID);
                details = "User " + AuthHandler.getFullName(u) + " has downloaded self"
                        + " appraisal report for appraisal cycle " + appcy.getCyclename()
                        + " through Deskera HRMS";
            } else {
                u = (User) session.get(User.class, userID);

                details = "Reviewer "
                        + AuthHandler
                                .getFullName((User) session.get(User.class, AuthHandler.getUserid(request)))
                        + " has downloaded " + AuthHandler.getFullName(u) + "'s"
                        + " appraisal report for appraisal cycle " + appcy.getCyclename()
                        + " through Deskera HRMS";
            }
            tx = session.beginTransaction();
            //@@ProfileHandler.insertAuditLog(session, AuditAction.Appraisal_Report_Download,details,request);
            tx.commit();
        }
    } catch (DocumentException ex) {
        throw ServiceException.FAILURE("AppraisalDetails.AppraisalDetail", ex);
    } catch (JSONException e) {
        throw ServiceException.FAILURE("AppraisalDetails.AppraisalDetail", e);
    } catch (Exception ex) {
        if (tx != null) {
            tx.rollback();
        }
        throw ServiceException.FAILURE(ex.getMessage(), ex);
    } finally {
        writer.close();
    }
    return baos;

}

From source file:com.krawler.esp.servlets.ExportMPXServlet.java

License:Open Source License

public static PdfPTable createPdfTable(ArrayList header, ArrayList widths, ArrayList tabCol, Document doc)
        throws DocumentException {
    PdfPTable temp = new PdfPTable(header.size());
    float[] wid = new float[widths.size()];
    String[] cols = new String[header.size()];
    for (int i = 0; i < widths.size(); i++) {
        wid[i] = (float) (Integer.parseInt(widths.get(i).toString()));
        cols[i] = header.get(i).toString();
    }/* w  w w  .j av a  2s.c om*/
    temp.setWidthPercentage(wid, doc.getPageSize());
    temp.setTotalWidth(100);
    Font fnt1 = new Font();
    fnt1.setStyle(Font.NORMAL);
    addPdfRowToTable(cols, temp, fnt1, 0);
    temp.setHeaderRows(1);
    tabCol.add(cols);
    return temp;
}

From source file:com.krawler.esp.servlets.ExportProjectReportServlet.java

License:Open Source License

private int addTable(int stcol, int stpcol, int strow, int stprow, JSONArray store, String[] colwidth2,
        String[] colHeader, Document document) throws JSONException, DocumentException {

    java.awt.Color tColor = new Color(Integer.parseInt(config.getString("textColor"), 16));
    fontSmallBold.setColor(tColor);/*from  w  ww  . ja v  a 2 s .  c  o  m*/

    com.krawler.utils.json.base.JSONObject colWidth = config.getJSONObject("colWidth");
    JSONArray widths = colWidth.getJSONArray("data");
    ArrayList arr = new ArrayList();
    PdfPTable table;
    float[] f = new float[widths.length() + 1];//[(stpcol - stcol) + 1];
    float[] tcol = new float[(stpcol - stcol) + 1];

    if (widths.length() == 0) {
        f[0] = 10;
        for (int k = 1; k < f.length; k++) {
            f[k] = 20;
        }
        tcol[0] = 10;
    } else {
        for (int i = 0; i < widths.length(); i++) {
            JSONObject temp = widths.getJSONObject(i);
            arr.add(temp.getInt("width"));
        }

        f[0] = 30;
        for (int k = 1; k < f.length; k++) {
            if (!config.getBoolean("landscape") && (Integer) arr.get(k - 1) > 550) {
                f[k] = 550;
            } else {
                f[k] = (Integer) arr.get(k - 1);
            }
        }
        //            table = new PdfPTable(f);
        //            table.setTotalWidth(90);
        // table.setWidthPercentage(f,document.getPageSize());
        tcol[0] = 30;
    }
    int i = 1;
    for (int k = stcol; k < stpcol; k++) {
        tcol[i] = f[k + 1];
        i++;
    }

    table = new PdfPTable(tcol);
    table.setTotalWidth(90);
    table.setWidthPercentage(tcol, document.getPageSize());

    table.setSpacingBefore(15);
    Font f1 = FontFactory.getFont("Helvetica", 8, Font.NORMAL, tColor);
    PdfPCell h2 = new PdfPCell(new Paragraph("No.", fontSmallBold));
    if (config.getBoolean("gridBorder")) {
        h2.setBorder(PdfPCell.BOX);
    } else {
        h2.setBorder(0);
    }
    h2.setPadding(4);
    h2.setBorderColor(Color.GRAY);
    h2.setHorizontalAlignment(Element.ALIGN_CENTER);
    table.addCell(h2);
    int stpcol1 = 0;
    for (int hcol = stcol; hcol < stpcol; hcol++) {
        PdfPCell h1 = new PdfPCell(new Paragraph(colHeader[hcol], fontSmallBold));
        h1.setHorizontalAlignment(Element.ALIGN_CENTER);
        if (config.getBoolean("gridBorder")) {
            h1.setBorder(PdfPCell.BOX);
        } else {
            h1.setBorder(0);
        }
        h1.setBorderColor(Color.GRAY);
        h1.setPadding(4);
        table.addCell(h1);
    }
    table.setHeaderRows(1);

    for (int row = strow; row < stprow; row++) {
        h2 = new PdfPCell(new Paragraph(String.valueOf(row + 1), f1));
        if (config.getBoolean("gridBorder")) {
            h2.setBorder(PdfPCell.BOTTOM | PdfPCell.LEFT | PdfPCell.RIGHT);
        } else {
            h2.setBorder(0);
        }
        h2.setPadding(4);
        h2.setBorderColor(Color.GRAY);
        h2.setHorizontalAlignment(Element.ALIGN_CENTER);
        h2.setVerticalAlignment(Element.ALIGN_CENTER);
        table.addCell(h2);

        for (int col = stcol; col < stpcol; col++) {
            Paragraph para = null;
            if (store.getJSONObject(row).has(colwidth2[col]))
                para = new Paragraph(store.getJSONObject(row).getString(colwidth2[col]), f1);
            else
                para = new Paragraph("", f1);
            //                    Paragraph para = new Paragraph(store.getJSONObject(row).getString(colwidth2[col]), f1);
            PdfPCell h1 = new PdfPCell(para);
            if (config.getBoolean("gridBorder")) {
                h1.setBorder(PdfPCell.BOTTOM | PdfPCell.LEFT | PdfPCell.RIGHT);
            } else {
                h1.setBorder(0);
            }
            h1.setPadding(4);
            h1.setBorderColor(Color.GRAY);
            h1.setHorizontalAlignment(Element.ALIGN_CENTER);
            h1.setVerticalAlignment(Element.ALIGN_CENTER);
            table.addCell(h1);
        }

    }
    document.add(table);
    document.newPage();

    /* add instance of OnStartPage*/
    if (widths.length() != 0) {
        if (stpcol != colwidth2.length) {
            float twidth = 0;
            stpcol1 = stpcol;

            int docwidth;
            if (config.getBoolean("landscape"))
                docwidth = 800;
            else
                docwidth = 600;

            while (twidth < docwidth && stpcol1 < f.length) {
                twidth += f[stpcol1];
                stpcol1++;
            }
            stpcol1--;

            addTable(stpcol, stpcol1, strow, stprow, store, colwidth2, colHeader, document);
        }

    } else {
        if (stpcol != colwidth2.length) {
            if ((colwidth2.length - stpcol) > showColumns) { // column limit
                stpcol1 = stpcol + 5;
            } else {
                stpcol1 = (colwidth2.length - stpcol) + stpcol;
            }
            addTable(stpcol, stpcol1, strow, stprow, store, colwidth2, colHeader, document);
        }
    }
    return stpcol;
}