Example usage for com.lowagie.text.pdf BaseFont getWidthPoint

List of usage examples for com.lowagie.text.pdf BaseFont getWidthPoint

Introduction

In this page you can find the example usage for com.lowagie.text.pdf BaseFont getWidthPoint.

Prototype

public float getWidthPoint(int char1, float fontSize) 

Source Link

Document

Gets the width of a char in points.

Usage

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  w ww.j a v  a2  s .  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.gov.jfrj.itextpdf.Documento.java

License:Open Source License

private static void showTextOnArc(PdfContentByte cb, String text, BaseFont font, float textHeight,
        float xCenter, float yCenter, float radius, boolean top) {
    float fTotal = 0;
    float aPos[] = new float[text.length()];
    for (int i = 0; i < text.length(); i++) {
        float f = font.getWidthPoint(text.substring(i, i + 1), textHeight);
        aPos[i] = f / 2 + fTotal;//w ww .ja va2s  .  c  o  m
        fTotal += f;
    }
    float fAscent = font.getAscentPoint(text, textHeight);

    for (int i = 0; i < text.length(); i++) {
        float theta;
        if (top)
            theta = (float) ((aPos[i] - fTotal / 2) / radius);
        else
            theta = (float) (-1 * (aPos[i] - fTotal / 2) / (radius - fAscent) + Math.PI);
        cb.showTextAligned(Element.ALIGN_CENTER, text.substring(i, i + 1),
                xCenter + radius * (float) Math.sin(theta), yCenter + radius * (float) Math.cos(theta),
                (float) ((-theta + (top ? 0 : Math.PI)) * 180 / Math.PI));
    }
    return;
}

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  ww  . j a  va  2s . c  o  m*/
 * @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:ca.sqlpower.architect.profile.output.ProfilePDFFormat.java

License:Open Source License

/**
 * @param widths The maximum width of each column's contents in
 * points.  THIS ARRAY WILL BE MODIFIED to the width of the widest
 * single word in the heading if it is wider than the existing
 * width value for that column.  Words are split using the default
 * settings for java.util.StringTokenizer.
 * @param headerTopNColumns reference to the null count/% inner table in the header
 * @param headerValueColumns reference to the unique count/% inner table in the header
 * @param headerLengthColumns reference to the length min/max/avg inner table in the header
 * @param headerUniqueColumns reference to the value min/max/avg inner table in the header
 * @param headerNullColumns reference to the top N Value/count inner table in the header
 * we will resert widths of these inner table after we have all rows
 *//* ww w  .j a  va 2  s  . c om*/
private void addHeaderRow(TableProfileResult result, ProfileTableStructure profile, BaseFont bf,
        float titleFSize, float colHeadingFSize, float[] widths)
        throws DocumentException, IOException, SQLObjectException {

    int ncols = headings.length;

    Font titleFont = new Font(bf, titleFSize, Font.BOLD);
    Font colHeadingFont = new Font(bf, colHeadingFSize);
    PdfPTable table = profile.getMainTable();
    SQLTable sqlTable = result.getProfiledObject();

    //        TableProfileResult tProfile = (TableProfileResult) pm.getResult(sqlTable);
    PdfPTable infoTable = new PdfPTable(2);
    StringBuffer heading = new StringBuffer();
    heading.append("Connection: ").append(sqlTable.getParentDatabase().getName()).append("\n");
    heading.append("Table: ").append(SQLObjectUtils.toQualifiedName(sqlTable, SQLDatabase.class));
    if (result.getException() != null) {
        heading.append("\nProfiling Error");
        if (result.getException() != null) {
            heading.append(":\n").append(result.getException());
            StackTraceElement[] stackTrace = result.getException().getStackTrace();
            for (int i = 0; i < STACK_TRACE_LENGTH && i < stackTrace.length; i++) {
                StackTraceElement element = stackTrace[i];
                heading.append("\n   ").append(element.getFileName()).append(".").append(element.getClassName())
                        .append(".").append(element.getMethodName()).append("(").append(element.getLineNumber())
                        .append(")");
            }
            if (stackTrace.length > STACK_TRACE_LENGTH) {
                heading.append("\n   ... ").append(stackTrace.length).append(" more");
            }
        }
    } else {
        PdfPCell infoCell;

        infoCell = new PdfPCell(new Phrase("Row Count:", colHeadingFont));
        infoCell.setBorder(Rectangle.NO_BORDER);
        infoCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
        infoTable.addCell(infoCell);

        infoCell = new PdfPCell(new Phrase(String.valueOf(result.getRowCount()), colHeadingFont));
        infoCell.setBorder(Rectangle.NO_BORDER);
        infoTable.addCell(infoCell);

        infoCell = new PdfPCell(new Phrase("Create Date:", colHeadingFont));
        infoCell.setBorder(Rectangle.NO_BORDER);
        infoCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
        infoTable.addCell(infoCell);

        DateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        infoCell = new PdfPCell(new Phrase(df.format(new Date(result.getCreateStartTime())), colHeadingFont));
        infoCell.setBorder(Rectangle.NO_BORDER);
        infoTable.addCell(infoCell);

        infoCell = new PdfPCell(new Phrase("Elapsed:", colHeadingFont));
        infoCell.setBorder(Rectangle.NO_BORDER);
        infoCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
        infoTable.addCell(infoCell);

        infoCell = new PdfPCell(new Phrase(result.getTimeToCreate() + "ms", colHeadingFont));
        infoCell.setBorder(Rectangle.NO_BORDER);
        infoTable.addCell(infoCell);
    }

    PdfPCell hcell = new PdfPCell(new Phrase(heading.toString(), titleFont));
    hcell.setColspan(ncols - 3);
    hcell.setBorder(Rectangle.NO_BORDER);
    hcell.setVerticalAlignment(Element.ALIGN_BOTTOM);
    table.addCell(hcell);

    hcell = new PdfPCell(infoTable);
    hcell.setColspan(3);
    hcell.setBorder(Rectangle.NO_BORDER);
    table.addCell(hcell);

    if (sqlTable.getColumns().size() > 0) {

        int colNo = 0;
        // column name
        Phrase colTitle = new Phrase("Column Name", colHeadingFont);
        PdfPCell cell = new PdfPCell(colTitle);
        cell.setBorder(Rectangle.BOTTOM | Rectangle.TOP);
        cell.setBorderWidth(2);
        cell.setBackgroundColor(new Color(200, 200, 200));
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        table.addCell(cell);
        // ensure column width is at least enough for widest word in heading
        widths[colNo] = Math.max(widths[colNo], bf.getWidthPoint(colTitle.content(), colHeadingFSize));
        colNo++;

        // date type
        colTitle = new Phrase("Data Type", colHeadingFont);
        cell = new PdfPCell(colTitle);
        cell.setBorder(Rectangle.BOTTOM | Rectangle.TOP);
        cell.setBorderWidth(2);
        cell.setBackgroundColor(new Color(200, 200, 200));
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        table.addCell(cell);
        widths[colNo] = Math.max(widths[colNo], bf.getWidthPoint(colTitle.content(), colHeadingFSize));
        colNo++;

        // null count and %
        colTitle = new Phrase("NULL", colHeadingFont);
        cell = new PdfPCell(colTitle);
        cell.setColspan(2);
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        profile.getInnerTableNullColumn().addCell(cell);

        colTitle = new Phrase("#", colHeadingFont);
        cell = new PdfPCell(colTitle);
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        profile.getInnerTableNullColumn().addCell(cell);
        widths[colNo] = Math.max(widths[colNo], bf.getWidthPoint(colTitle.content(), colHeadingFSize));
        colNo++;

        colTitle = new Phrase("%", colHeadingFont);
        cell = new PdfPCell(colTitle);
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        profile.getInnerTableNullColumn().addCell(cell);
        widths[colNo] = Math.max(widths[colNo], bf.getWidthPoint(colTitle.content(), colHeadingFSize));
        colNo++;

        cell = new PdfPCell(profile.getInnerTableNullColumn());
        cell.setColspan(2);
        cell.setBackgroundColor(new Color(200, 200, 200));
        cell.setBorderWidth(2);
        cell.setBorder(Rectangle.TOP | Rectangle.BOTTOM);
        table.addCell(cell);

        // unique count and %
        colTitle = new Phrase("Unique", colHeadingFont);
        cell = new PdfPCell(colTitle);
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell.setColspan(2);
        profile.getInnerTableUniqueColumn().addCell(cell);

        colTitle = new Phrase("#", colHeadingFont);
        cell = new PdfPCell(colTitle);
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        profile.getInnerTableUniqueColumn().addCell(cell);
        widths[colNo] = Math.max(widths[colNo], bf.getWidthPoint(colTitle.content(), colHeadingFSize));
        colNo++;

        colTitle = new Phrase("%", colHeadingFont);
        cell = new PdfPCell(colTitle);
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        profile.getInnerTableUniqueColumn().addCell(cell);
        widths[colNo] = Math.max(widths[colNo], bf.getWidthPoint(colTitle.content(), colHeadingFSize));
        colNo++;

        cell = new PdfPCell(profile.getInnerTableUniqueColumn());
        cell.setColspan(2);
        cell.setBackgroundColor(new Color(200, 200, 200));
        cell.setBorder(Rectangle.TOP | Rectangle.BOTTOM);
        cell.setBorderWidth(2);
        table.addCell(cell);

        // length max/min/avg
        colTitle = new Phrase("Length", colHeadingFont);
        cell = new PdfPCell(colTitle);
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell.setColspan(3);
        profile.getInnerTableLengthColumn().addCell(cell);

        colTitle = new Phrase("Min", colHeadingFont);
        cell = new PdfPCell(colTitle);
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        profile.getInnerTableLengthColumn().addCell(cell);
        widths[colNo] = Math.max(widths[colNo], bf.getWidthPoint(colTitle.content(), colHeadingFSize));
        colNo++;

        colTitle = new Phrase("Max", colHeadingFont);
        cell = new PdfPCell(colTitle);
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        profile.getInnerTableLengthColumn().addCell(cell);
        widths[colNo] = Math.max(widths[colNo], bf.getWidthPoint(colTitle.content(), colHeadingFSize));
        colNo++;

        colTitle = new Phrase("Avg", colHeadingFont);
        cell = new PdfPCell(colTitle);
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        profile.getInnerTableLengthColumn().addCell(cell);
        widths[colNo] = Math.max(widths[colNo], bf.getWidthPoint(colTitle.content(), colHeadingFSize));
        colNo++;

        cell = new PdfPCell(profile.getInnerTableLengthColumn());
        cell.setColspan(3);
        cell.setBackgroundColor(new Color(200, 200, 200));
        cell.setBorderWidth(2);
        cell.setBorder(Rectangle.TOP | Rectangle.BOTTOM);
        table.addCell(cell);

        // value max/min/avg
        colTitle = new Phrase("Value", colHeadingFont);
        cell = new PdfPCell(colTitle);
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell.setColspan(3);
        profile.getInnerTableValueColumn().addCell(cell);

        colTitle = new Phrase("Min", colHeadingFont);
        cell = new PdfPCell(colTitle);
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        profile.getInnerTableValueColumn().addCell(cell);
        widths[colNo] = Math.max(widths[colNo], bf.getWidthPoint(colTitle.content(), colHeadingFSize));
        colNo++;

        colTitle = new Phrase("Max", colHeadingFont);
        cell = new PdfPCell(colTitle);
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        profile.getInnerTableValueColumn().addCell(cell);
        widths[colNo] = Math.max(widths[colNo], bf.getWidthPoint(colTitle.content(), colHeadingFSize));
        colNo++;

        colTitle = new Phrase("Avg", colHeadingFont);
        cell = new PdfPCell(colTitle);
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        profile.getInnerTableValueColumn().addCell(cell);
        widths[colNo] = Math.max(widths[colNo], bf.getWidthPoint(colTitle.content(), colHeadingFSize));
        colNo++;

        cell = new PdfPCell(profile.getInnerTableValueColumn());
        cell.setColspan(3);
        cell.setBackgroundColor(new Color(200, 200, 200));
        cell.setBorderWidth(2);
        cell.setBorder(Rectangle.TOP | Rectangle.BOTTOM);
        table.addCell(cell);

        // top n
        colTitle = new Phrase("Top N", colHeadingFont);
        cell = new PdfPCell(colTitle);
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell.setColspan(2);
        profile.getInnerTableTopNColumn().addCell(cell);

        colTitle = new Phrase("Values", colHeadingFont);
        cell = new PdfPCell(colTitle);
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        profile.getInnerTableTopNColumn().addCell(cell);
        widths[colNo] = Math.max(widths[colNo], bf.getWidthPoint(colTitle.content(), colHeadingFSize));
        colNo++;

        colTitle = new Phrase("#", colHeadingFont);
        cell = new PdfPCell(colTitle);
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        profile.getInnerTableTopNColumn().addCell(cell);
        widths[colNo] = Math.max(widths[colNo], bf.getWidthPoint(colTitle.content(), colHeadingFSize));
        colNo++;

        cell = new PdfPCell(profile.getInnerTableTopNColumn());
        cell.setColspan(2);
        cell.setBackgroundColor(new Color(200, 200, 200));
        cell.setBorderWidth(2);
        cell.setBorder(Rectangle.TOP | Rectangle.BOTTOM);
        table.addCell(cell);

    } else {
        hcell = new PdfPCell(new Phrase("No Column Found in the table", titleFont));
        hcell.setColspan(ncols);
        hcell.setBorder(Rectangle.BOTTOM);
        hcell.setVerticalAlignment(Element.ALIGN_LEFT);
        table.addCell(hcell);
    }
    table.setHeaderRows(2);
}

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

License:Open Source License

private void addBodyRow(TableProfileResult tProfile, ColumnProfileResult result, DDLGenerator ddlg,
        PdfPTable table, BaseFont bf, Font f, float fsize, float[] widths)
        throws DocumentException, IOException, SQLObjectException, SQLException {

    SQLColumn col = result.getProfiledObject();

    int rowCount = -1;
    if (tProfile != null && tProfile.getException() == null) {
        rowCount = tProfile.getRowCount();
    }/*from w  w  w . ja v  a2  s  .co  m*/
    java.util.List<ColumnValueCount> topTen = null;

    boolean errorColumnProfiling = false;
    Exception columnException = null;
    if (result != null && result.getException() == null) {
        topTen = result.getValueCount();
    } else {
        errorColumnProfiling = true;
        if (result != null && result.getException() != null) {
            columnException = result.getException();
            logger.debug("Exception " + columnException + " on column " + col.getName());
        }
    }

    DecimalFormat pctFormat = new DecimalFormat("0%");

    DecimalFormat df = new DecimalFormat("#,##0.00");
    df.setMaximumFractionDigits(col.getScale());
    df.setMinimumFractionDigits(col.getScale());

    DecimalFormat adf = new DecimalFormat("#,##0.00");
    adf.setMaximumFractionDigits(Math.max(2, col.getScale()));
    adf.setMinimumFractionDigits(Math.max(2, col.getScale()));

    DecimalFormat aldf = new DecimalFormat("#,##0.0");
    aldf.setMaximumFractionDigits(1);
    aldf.setMinimumFractionDigits(0);

    boolean errorSpanRemaining = false;
    for (int colNo = 0; colNo < totalColumn; colNo++) {

        String contents;
        int alignment;

        if (headings[colNo].equalsIgnoreCase("table name")) {
            String fqTableName = SQLObjectUtils.toQualifiedName(col.getParent(), SQLDatabase.class);
            if (tProfile == null || tProfile.getException() != null) {
                contents = fqTableName + "\nProfiling Error:\n";
                if (tProfile != null && tProfile.getException() != null) {
                    contents += tProfile.getException();
                    errorSpanRemaining = true;
                }
            } else {
                contents = fqTableName;
            }
            alignment = Element.ALIGN_LEFT;
        } else if (headings[colNo].equalsIgnoreCase("row count")) {
            contents = String.valueOf(rowCount);
            alignment = Element.ALIGN_RIGHT;
        } else if (headings[colNo].equalsIgnoreCase("column name")) {
            contents = col.getName();
            alignment = Element.ALIGN_LEFT;
        } else if (headings[colNo].equalsIgnoreCase("data type")) {
            contents = ddlg.columnType(col);
            alignment = Element.ALIGN_LEFT;
        } else if (headings[colNo].equalsIgnoreCase("null count")) {

            if (errorColumnProfiling) {
                if (result == null) {
                    contents = "Column Profiling Not Found\n";
                } else {
                    contents = "Column Profiling Error:\n";
                    if (columnException != null) {
                        contents += columnException;
                        errorSpanRemaining = true;
                    }
                }
                alignment = Element.ALIGN_LEFT;
            } else {
                if (col.isDefinitelyNullable()) {
                    contents = String.valueOf(result.getNullCount());
                } else {
                    contents = "---";
                }
                alignment = Element.ALIGN_RIGHT;
            }
        } else if (headings[colNo].equalsIgnoreCase("% null")) {
            if (errorColumnProfiling) {
                continue;
            } else {
                if (col.isDefinitelyNullable()) {
                    if (rowCount <= 0) {
                        contents = "N/A";
                        alignment = Element.ALIGN_CENTER;
                    } else {
                        contents = pctFormat.format(result.getNullCount() / (double) rowCount);
                        alignment = Element.ALIGN_RIGHT;
                    }
                } else {
                    contents = "---";
                    alignment = Element.ALIGN_CENTER;
                }
            }
        } else if (headings[colNo].equalsIgnoreCase("Unique Count")) {
            if (!errorColumnProfiling) {
                contents = String.valueOf(result.getDistinctValueCount());
                alignment = Element.ALIGN_RIGHT;
            } else {
                continue;
            }
        } else if (headings[colNo].equalsIgnoreCase("% unique")) {
            if (!errorColumnProfiling) {
                if (rowCount == 0) {
                    contents = "N/A";
                    alignment = Element.ALIGN_CENTER;
                } else {
                    contents = pctFormat.format(result.getDistinctValueCount() / (double) rowCount);
                    alignment = Element.ALIGN_RIGHT;
                }
            } else {
                continue;
            }
        } else if (headings[colNo].equalsIgnoreCase("Min Length")) {
            if (!errorColumnProfiling) {
                contents = String.valueOf(result.getMinLength());
                alignment = Element.ALIGN_RIGHT;
            } else {
                contents = "";
                alignment = Element.ALIGN_LEFT;
            }
        } else if (headings[colNo].equalsIgnoreCase("Max Length")) {
            if (!errorColumnProfiling) {
                contents = String.valueOf(result.getMaxLength());
                alignment = Element.ALIGN_RIGHT;
            } else {
                contents = "";
                alignment = Element.ALIGN_LEFT;
            }
        } else if (headings[colNo].equalsIgnoreCase("avg Length")) {
            if (!errorColumnProfiling) {
                contents = aldf.format(result.getAvgLength());
                alignment = Element.ALIGN_RIGHT;
            } else {
                contents = "";
                alignment = Element.ALIGN_LEFT;
            }
        } else if (headings[colNo].equalsIgnoreCase("Min value")) {
            if (!errorColumnProfiling) {
                if (result.getMinValue() == null) {
                    alignment = Element.ALIGN_CENTER;
                    contents = "";
                } else if (result.getMinValue() instanceof Number) {
                    alignment = Element.ALIGN_RIGHT;
                    contents = df.format((Number) result.getMinValue());
                } else {
                    alignment = Element.ALIGN_LEFT;
                    contents = String.valueOf(result.getMinValue());
                }
                alignment = Element.ALIGN_LEFT;
            } else {
                contents = "";
                alignment = Element.ALIGN_LEFT;
            }
        } else if (headings[colNo].equalsIgnoreCase("Max value")) {
            if (!errorColumnProfiling) {
                if (result.getMaxValue() == null) {
                    alignment = Element.ALIGN_CENTER;
                    contents = "";
                } else if (result.getMaxValue() instanceof Number) {
                    alignment = Element.ALIGN_RIGHT;
                    contents = df.format((Number) result.getMaxValue());
                } else {
                    alignment = Element.ALIGN_LEFT;
                    contents = String.valueOf(result.getMaxValue());
                }
                alignment = Element.ALIGN_LEFT;
            } else {
                contents = "";
                alignment = Element.ALIGN_LEFT;
            }
        } else if (headings[colNo].equalsIgnoreCase("avg value")) {
            if (!errorColumnProfiling) {
                if (result.getAvgValue() == null) {
                    alignment = Element.ALIGN_CENTER;
                    contents = "";
                } else if (result.getAvgValue() instanceof Number) {
                    alignment = Element.ALIGN_RIGHT;
                    contents = adf.format((Number) result.getAvgValue());
                } else {
                    alignment = Element.ALIGN_LEFT;
                    contents = String.valueOf(result.getAvgValue());
                }
            } else {
                contents = "";
                alignment = Element.ALIGN_LEFT;
            }
        } else if (headings[colNo].equalsIgnoreCase("Top N Values")) {
            if (!errorColumnProfiling && topTen != null) {
                StringBuffer sb = new StringBuffer();
                for (ColumnValueCount cvc : topTen) {
                    sb.append(cvc.getValue()).append("\n");
                }
                contents = sb.toString();
                alignment = Element.ALIGN_LEFT;
            } else {
                contents = "";
                alignment = Element.ALIGN_LEFT;
            }
        } else if (headings[colNo].equalsIgnoreCase("Count")) {
            if (!errorColumnProfiling) {
                StringBuffer sb = new StringBuffer();
                for (ColumnValueCount cvc : topTen) {
                    sb.append(cvc.getCount()).append("\n");
                }
                contents = sb.toString();
                alignment = Element.ALIGN_RIGHT;
            } else {
                contents = "";
                alignment = Element.ALIGN_LEFT;
            }
        } else {
            throw new IllegalStateException("I don't know about column " + colNo);
        }

        StringBuffer truncContents = new StringBuffer(contents.length());

        // update column width to reflect the widest cell
        for (String contentLine : contents.split("\n")) {
            String newLine;
            if (truncateLength >= 0 && !errorSpanRemaining) {
                if (bf.getWidthPoint(contentLine, fsize) < truncateLength) {
                    newLine = contentLine + "\n";
                } else {
                    double currentLength = bf.getWidthPoint("...", fsize);
                    int stringPosition = 0;
                    for (; stringPosition < contentLine.length(); stringPosition++) {
                        if (currentLength > truncateLength) {
                            break;
                        }
                        currentLength = bf.getWidthPoint(contentLine.substring(0, stringPosition) + "...",
                                fsize);
                        stringPosition++;
                    }
                    newLine = contentLine.substring(0, stringPosition - 1) + "...\n";
                }
            } else {
                newLine = contentLine + "\n";
            }
            truncContents.append(newLine);
            if (!errorSpanRemaining) {
                widths[colNo] = Math.max(widths[colNo], bf.getWidthPoint(newLine, fsize));
                logger.debug("width is now " + widths[colNo] + " for column " + colNo);
            }
        }

        PdfPCell cell;
        if (headings[colNo].equalsIgnoreCase("Top N Values") || headings[colNo].equalsIgnoreCase("Count")) {
            cell = new PdfPCell(new Paragraph(truncContents.toString(), f));
            cell.setNoWrap(true);
        } else if (headings[colNo].equalsIgnoreCase("null count") && errorColumnProfiling) {
            cell = new PdfPCell(new Paragraph(truncContents.toString(), f));
            cell.setColspan(4);
        } else {
            Phrase phr = new Phrase(truncContents.toString(), f);
            cell = new PdfPCell(phr);

        }
        //            cell.setBorder(Rectangle.NO_BORDER);
        cell.setHorizontalAlignment(alignment);
        if (errorSpanRemaining) {
            cell.setColspan(totalColumn - colNo);
        }
        table.addCell(cell);
        if (errorSpanRemaining) {
            break;
        }
    }
}

From source file:com.estate.pdf.PageBorder.java

public void draw(Document doc, int iconNum, String pageNum, String toolName) {
    try {/*  ww w.j  av a2  s .co m*/
        PdfContentByte cb = writer.getDirectContentUnder();
        BaseFont fontBold = BaseFont.createFont(Locations.getFontLocation() + "timesbd.ttf", BaseFont.CP1252,
                BaseFont.EMBEDDED);
        BaseFont font = BaseFont.createFont(Locations.getFontLocation() + "times.ttf", BaseFont.CP1252,
                BaseFont.EMBEDDED);
        Rectangle rct = new Rectangle(doc.getPageSize());
        float iconBase = (1.25f * 72); // This is the base of the icons on
        // the page
        Image icon = Image.getInstance(Locations.getImageLocation() + icons[iconNum]);
        // Image box = Image.getInstance(Locations.ImageLocation() +
        // "blueBOX.png");
        icon.scalePercent(23);
        float scale = .23f;
        float iconLeft = (icon.getWidth() / 2) * scale;
        float boxSize = (.1875f * 72);

        // Adjust the top
        rct.setTop(rct.getTop() - (.5f * 72));

        // Place the Icon
        icon.setAbsolutePosition((1.25f * 72) - iconLeft, rct.getTop() - iconBase);
        doc.add(icon);

        // Set our line color
        cb.setRGBColorStroke(0, 72, 117);

        cb.setLineWidth(.75f);

        // do the bottom line
        cb.moveTo(1.25f * 72, (.5f * 72));
        cb.lineTo(rct.getRight() - (.5f * 72), (.5f * 72));

        cb.moveTo(1.25f * 72, (.5f * 72));
        cb.lineTo(1.25f * 72, rct.getTop());

        // stroke the lines
        cb.stroke();

        // Do the lower left box
        cb.rectangle((1.25f - 0.09375f) * 72, (.5f - 0.09375f) * 72, boxSize, boxSize);
        cb.setRGBColorFill(0, 72, 117);
        cb.closePathFillStroke();

        // Do the lower right box
        Rectangle pnRect = new Rectangle(0, 0);
        pnRect.setLeft(rct.getRight() - ((.5f + 0.09375f) * 72));
        pnRect.setTop((.5f - 0.09375f) * 72);
        pnRect.setRight(pnRect.getLeft() + boxSize);
        pnRect.setBottom(pnRect.getTop() - boxSize);

        // cb.rectangle(rct.getRight() - ((.5f + 0.09375f) * 72), (.5f -
        // 0.09375f) * 72, (.1875f * 72), (.1875f * 72));
        cb.rectangle(pnRect.getLeft(), pnRect.getTop(), boxSize, boxSize);
        cb.setRGBColorFill(0, 72, 117);
        cb.closePathFillStroke();

        // Now we do the page number if one is supplied.
        if (pageNum.length() > 0) {
            float pnHeight = fontBold.getAscentPoint(pageNum, 9) - fontBold.getDescentPoint(pageNum, 9);
            float pnWidth = fontBold.getWidthPoint(pageNum, 9);

            float l = pnRect.getLeft() + ((boxSize - pnWidth) / 2);
            float b = pnRect.getTop() + ((boxSize - pnHeight) / 2);

            cb.beginText();
            cb.setFontAndSize(fontBold, 9);
            cb.setRGBColorFill(255, 255, 255);
            cb.setTextMatrix(l, b);
            cb.showText(pageNum);
            cb.endText();

        }

        // Display the copyright
        SimpleDateFormat df = new SimpleDateFormat("yyyy");
        char cs = 0x00a9; // Unicode for the copyright symbol
        String copyRight = com.estate.constants.StringConstants.copyRight + cs + " " + df.format(new Date());
        float crWidth;
        float crLeft;

        crWidth = font.getWidthPoint(copyRight, 8);
        cb.beginText();

        cb.setFontAndSize(font, 8);
        cb.setRGBColorFill(0, 0, 0);

        crLeft = (doc.getPageSize().getRight() - crWidth) / 2;
        cb.setTextMatrix(crLeft, .375f * 72); // Place the base of the
        // copyright at 3/8" up from
        // the bottom
        cb.showText(copyRight);
        cb.endText();

        if (toolName.length() > 0) {
            cb.beginText();

            cb.setFontAndSize(font, 8);
            cb.setRGBColorFill(0, 0, 0);

            cb.setTextMatrix((1.25f * 72) + boxSize, .375f * 72);
            cb.showText(toolName);
            cb.endText();
        }

        // Fix a licensee at left
        cb.beginText();
        cb.setFontAndSize(font, 8);
        cb.setRGBColorFill(0, 0, 0);
        cb.showTextAligned(PdfContentByte.ALIGN_RIGHT, " Licensee: " + getLicense(), (10.2f * 72), .375f * 72,
                0);
        cb.endText();
    } catch (Exception e) {
        System.out.println(e.getMessage());
    }
}

From source file:com.estate.pdf.PageBorder.java

public void drawNoBorder(Document doc, String pageNum) {
    try {//w  w  w  . j av a2s .c o m
        PdfContentByte cb = writer.getDirectContentUnder();
        BaseFont fontBold = BaseFont.createFont(Locations.getFontLocation() + "timesbd.ttf", BaseFont.CP1252,
                BaseFont.EMBEDDED);
        BaseFont font = BaseFont.createFont(Locations.getFontLocation() + "times.ttf", BaseFont.CP1252,
                BaseFont.EMBEDDED);
        Rectangle rct = new Rectangle(doc.getPageSize());
        float boxSize = (.1875f * 72);

        // Adjust the top
        rct.setTop(rct.getTop() - (.5f * 72));

        // Do the lower right box
        Rectangle pnRect = new Rectangle(0, 0);
        pnRect.setLeft(rct.getRight() - ((.5f + 0.09375f) * 72));
        pnRect.setTop(((.5f - 0.09375f) * 72) - 9);
        pnRect.setRight(pnRect.getLeft() + boxSize);
        pnRect.setBottom(pnRect.getTop() - boxSize);

        cb.rectangle(pnRect.getLeft(), pnRect.getTop(), boxSize, boxSize);
        cb.setRGBColorFill(0, 72, 117);
        cb.closePathFillStroke();

        // Now we do the page number if one is supplied.
        if (pageNum.length() > 0) {
            float pnHeight = fontBold.getAscentPoint(pageNum, 9) - fontBold.getDescentPoint(pageNum, 9) - 4.5f;
            float pnWidth = fontBold.getWidthPoint(pageNum, 9);

            float l = pnRect.getLeft() + ((boxSize - pnWidth) / 2);
            float b = pnRect.getTop() + ((boxSize - pnHeight) / 2) - 4.5f;

            cb.beginText();
            cb.setFontAndSize(fontBold, 9);
            cb.setRGBColorFill(255, 255, 255);
            cb.setTextMatrix(l, b);
            cb.showText(pageNum);
            cb.endText();
        }

        // Display the copyright
        SimpleDateFormat df = new SimpleDateFormat("yyyy");
        char cs = 0x00a9; // Unicode for the copyright symbol
        String copyRight = "Advanced Practice Network " + cs + " " + df.format(new Date());
        float crWidth;
        float crLeft;

        crWidth = font.getWidthPoint(copyRight, 8);
        cb.beginText();

        cb.setFontAndSize(font, 8);
        cb.setRGBColorFill(0, 0, 0);

        crLeft = (doc.getPageSize().getRight() - crWidth) / 2;
        cb.setTextMatrix(crLeft, .375f * 72); // Place the base of the
        // copyright at 3/8" up from
        // the bottom
        cb.showText(copyRight);
        cb.endText();

        if (license != null) {
            // Fix a licensee at left
            cb.beginText();
            cb.setFontAndSize(font, 8);
            cb.setRGBColorFill(0, 0, 0);
            cb.showTextAligned(PdfContentByte.ALIGN_RIGHT, " Licensee: " + getLicense(), (10.2f * 72),
                    .375f * 72, 0);
            cb.endText();
        }

    } catch (Exception e) {
        System.out.println(e.getMessage());
    }
}

From source file:de.tr1.cooperator.manager.web.CreateSubscriberListAction.java

License:Open Source License

/**
 * This method is called by the struts-framework if the submit-button is pressed.
 * It creates a PDF-File and puts in into the output-stream of the response.
 *///from  www  .  jav a 2s.  com
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {

    CreateSubscriberListForm myForm = (CreateSubscriberListForm) form;
    boolean bSortByName;

    if (myForm.getSortBy().equals(myForm.SORTBYPN))
        bSortByName = false;
    else
        bSortByName = true;

    //create Collection for the results...
    Event eEvent = EventManager.getInstance().getEventByID(myForm.getEventID());
    Collection cSubscriberList = UserManager.getInstance().getUsersByCollection(eEvent.getSubscriberList());
    Collection cExamResults = EventResultManager.getInstance().getResults(eEvent.getID());

    Iterator cSubscriberListIT = cSubscriberList.iterator();
    Collection cSubscriberResultList = new ArrayList();

    while (cSubscriberListIT.hasNext()) {
        User CurUser = (User) cSubscriberListIT.next();
        String UserPNR = CurUser.getPersonalNumber();

        Iterator cExamResultsIT = cExamResults.iterator();
        ExamResult curExamResult = null;
        String ResultUserPNR = null;
        while (cExamResultsIT.hasNext()) {
            curExamResult = (ExamResult) cExamResultsIT.next();

            ResultUserPNR = curExamResult.getUserPersonalNumber();
            if (UserPNR.equals(ResultUserPNR))
                break;
        }

        if (UserPNR.equals(ResultUserPNR)) {
            if (bSortByName) {
                UserResultSortByName URS = new UserResultSortByName(CurUser, "" + curExamResult.getResult());
                cSubscriberResultList.add(URS);
            } else {
                UserResultSortByPersonalNumber URS = new UserResultSortByPersonalNumber(CurUser,
                        "" + curExamResult.getResult());
                cSubscriberResultList.add(URS);
            }
        } else {
            if (bSortByName) {
                UserResultSortByName URS = new UserResultSortByName(CurUser, "-");
                cSubscriberResultList.add(URS);
            } else {
                UserResultSortByPersonalNumber URS = new UserResultSortByPersonalNumber(CurUser, "-");
                cSubscriberResultList.add(URS);
            }
        }

    }

    //sort List
    Collections.sort((List) cSubscriberResultList);

    BaseFont bf;
    //36pt = 0.5inch
    Document document = new Document(PageSize.A4, 36, 36, 72, 72);

    try {
        bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
    } catch (Exception e) {
        Log.addLog("CreateSubscriberListAction: Error creating BaseFont: " + e);
        //2do: add ErrorMessage and return to inputFormular!
        return mapping.findForward("GeneralFailure");
    }

    //calculate the number of cols and their width
    int cols = 0;
    ArrayList alWidth = new ArrayList();
    float boldItalicFactor = 1.2f;
    if (myForm.getShowNumber())
        alWidth.add(new Float(boldItalicFactor * bf.getWidthPoint(TABLEHEADER_NUMBER, TABLEHEADER_FONTSIZE)));

    if (myForm.getShowPersonalNumber())
        alWidth.add(new Float(
                boldItalicFactor * bf.getWidthPoint(TABLEHEADER_PERSONALNUMBER, TABLEHEADER_FONTSIZE)));

    if (myForm.getShowName())
        alWidth.add(new Float(boldItalicFactor * bf.getWidthPoint(TABLEHEADER_NAME, TABLEHEADER_FONTSIZE)));

    if (myForm.getShowEmail())
        alWidth.add(new Float(boldItalicFactor * bf.getWidthPoint(TABLEHEADER_EMAIL, TABLEHEADER_FONTSIZE)));

    if (myForm.getShowResult())
        alWidth.add(new Float(boldItalicFactor * bf.getWidthPoint(TABLEHEADER_RESULT, TABLEHEADER_FONTSIZE)));

    if (myForm.getAddInfoField())
        alWidth.add(new Float(boldItalicFactor * bf.getWidthPoint(TABLEHEADER_INFO, TABLEHEADER_FONTSIZE)));

    if (myForm.getAddSignField())
        alWidth.add(new Float(boldItalicFactor * bf.getWidthPoint(TABLEHEADER_SIGN, TABLEHEADER_FONTSIZE)));

    cols = alWidth.size();

    float totalWidth = 0;
    //calculate the whole length
    Iterator alIterator = alWidth.iterator();
    for (; alIterator.hasNext(); totalWidth += ((Float) alIterator.next()).floatValue())
        ;

    //calculate relativ width for the table
    float[] width = new float[cols];
    alIterator = alWidth.iterator();
    int i = 0;
    while (alIterator.hasNext()) {
        float pixLength = ((Float) alIterator.next()).floatValue();
        //alWidthRelativ.add( new Float( pixLength/totalWidth ) );
        width[i] = pixLength / totalWidth;
        i++;
    }

    //needed for the shrink (enlarge?)
    float shrinkFactor;

    try {
        //1st: set correct outputstream
        PdfWriter writer = PdfWriter.getInstance(document, response.getOutputStream());

        //1.5st: set content-stuff
        response.setContentType("application/pdf");

        //2nd: set EventManager for PageEvents to Helper
        writer.setPageEvent(
                new CreateSubscriberListActionHelper(myForm.getHeaderLeft(), myForm.getHeaderRight()));

        //3rd: open document for editing the content
        document.open();

        //4th: add content
        Phrase pInfoText = new Phrase(myForm.getInfoText(), new Font(bf, 12, Font.BOLD));
        document.add(pInfoText);

        //PdfPTable( cols )
        PdfPTable table = new PdfPTable(width);

        float documentWidth = document.right() - document.left();
        if (documentWidth < totalWidth) {
            table.setTotalWidth(documentWidth);
            shrinkFactor = documentWidth / totalWidth;
        } else {
            table.setTotalWidth(totalWidth);
            shrinkFactor = 1;
        }
        table.setLockedWidth(true);

        Font headerFont = new Font(bf, TABLEHEADER_FONTSIZE * shrinkFactor, Font.BOLDITALIC);
        Font cellFont = new Font(bf, TABLECELL_FONTSIZE * shrinkFactor, Font.NORMAL);

        if (myForm.getShowNumber())
            table.addCell(new Phrase(TABLEHEADER_NUMBER, headerFont));
        if (myForm.getShowPersonalNumber())
            table.addCell(new Phrase(TABLEHEADER_PERSONALNUMBER, headerFont));
        if (myForm.getShowName())
            table.addCell(new Phrase(TABLEHEADER_NAME, headerFont));
        if (myForm.getShowEmail())
            table.addCell(new Phrase(TABLEHEADER_EMAIL, headerFont));
        if (myForm.getShowResult())
            table.addCell(new Phrase(TABLEHEADER_RESULT, headerFont));
        if (myForm.getAddInfoField())
            table.addCell(new Phrase(TABLEHEADER_INFO, headerFont));
        if (myForm.getAddSignField())
            table.addCell(new Phrase(TABLEHEADER_SIGN, headerFont));

        //fill table
        Iterator iSRL = cSubscriberResultList.iterator();
        int counter = 1;
        while (iSRL.hasNext()) {
            UserResult curResult = (UserResult) iSRL.next();

            table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_RIGHT);
            if (myForm.getShowNumber())
                table.addCell(new Phrase("" + counter++, cellFont));

            table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
            if (myForm.getShowPersonalNumber())
                table.addCell(new Phrase(curResult.getPersonalNumber(), cellFont));

            table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_LEFT);
            if (myForm.getShowName())
                table.addCell(new Phrase(curResult.getSurname() + ", " + curResult.getFirstName(), cellFont));
            if (myForm.getShowEmail())
                table.addCell(new Phrase(curResult.getEmailAddress(), cellFont));
            if (myForm.getShowResult())
                table.addCell(new Phrase(curResult.getResult(), cellFont));
            if (myForm.getAddInfoField())
                table.addCell(new Phrase("", cellFont));
            if (myForm.getAddSignField())
                table.addCell(new Phrase("", cellFont));
        }

        //set how many rows are header...
        table.setHeaderRows(1);

        document.add(table);

        //5th: close document, write the output to the stream...
        document.close();
    } catch (Exception de) {
        Log.addLog("CreateSubscriberListAction: Error creating PDF: " + de);
    }

    //we dont need to return a forward, because we write directly to the outputstream!
    return null;
}

From source file:edtscol.client.Imprime.java

License:CeCILL license

private void ecrireTexteHor(String texte, float x, float y, float l, float h, float ph, float pv, int szf) {
    float x1, y1;
    try {//from   www  . j  a  v a 2s  .c om
        BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
        cb.setFontAndSize(bf, szf);
        x1 = x + ph;
        y1 = y - pv;
        if (bf.getWidthPoint(texte, szf) > l) {
            cesure(bf, szf, texte, x1, y1, l, h);
        } else {
            cb.beginText();
            cb.setTextMatrix(x1, y1);
            cb.showText(texte);
            cb.endText();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:edtscol.client.Imprime.java

License:CeCILL license

private void cesure(BaseFont bf, int szf, String texte, float x, float y, float l, float h) {
    float x1 = x;
    float y1 = y;
    int lg = texte.length();
    int ic = 1;/*  ww  w.j  a  v a 2 s  .co m*/
    int pav = 0;
    while (ic < lg) {
        while (bf.getWidthPoint(texte.substring(pav, ic), szf) < l) {
            ic++;
            if (ic > lg) {
                break;
            }
        }
        cb.beginText();
        cb.setTextMatrix(x1, y1);
        cb.showText(texte.substring(pav, ic - 1));
        cb.endText();
        y1 = y1 - szf;
        pav = ic - 1;
        if (y1 < y - h + szf) {
            break;
        }
    }
}