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

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

Introduction

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

Prototype

public PdfPTable(PdfPTable table) 

Source Link

Document

Constructs a copy of a PdfPTable.

Usage

From source file:bucks.RedeemInvoice.java

License:Open Source License

void generateInvoice(HttpServletResponse res, Redeem redeem) {

    ///*w w  w.  j a  v  a2s . co m*/
    // paper size legal (A4) 8.5 x 11
    // page 1-inch = 72 points
    //
    String spacer = "   \n";
    User user = redeem.getUser();
    Vendor vendor = redeem.getVendor();
    List<Buck> bk_bucks = redeem.getBk_bucks();
    List<Buck> gc5_bucks = redeem.getGc5_bucks();
    List<Buck> gc20_bucks = redeem.getGc20_bucks();
    List<Buck> gc_bucks = redeem.getGc_bucks();
    List<Dispute> disputes = redeem.getDisputes();
    int bk_total = 0, gc5_total = 0, gc20_total = 0, total = 0;
    if (bk_bucks.size() > 0) {
        bk_total = bk_bucks.size() * 3;
    }
    if (gc5_bucks.size() > 0) {
        gc5_total = gc5_bucks.size() * 5;
    }
    if (gc20_bucks.size() > 0) {
        gc20_total = gc20_bucks.size() * 20;
    }
    total = bk_total + gc5_total + gc20_total;
    String vendor_name = "";
    if (vendor != null) {
        vendor_name = vendor.getCleanName();
    }
    ServletOutputStream out = null;
    String filename = "invoice_" + vendor_name + "_" + redeem.getId() + ".pdf";
    try {
        // space
        //         
        Rectangle pageSize = new Rectangle(612, 792); // 8.5" X 11"
        Document document = new Document(pageSize, 36, 36, 18, 18);// 18,18,54,35         
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        PdfWriter writer = PdfWriter.getInstance(document, baos);
        document.open();
        Image image = Image.getInstance(imageUrl);
        // image = Image.getInstance(byte bytes[]);// generated image
        image.scalePercent(20f);
        Font fnt = new Font(Font.TIMES_ROMAN, 12, Font.NORMAL);
        Font fntb = new Font(Font.TIMES_ROMAN, 12, Font.BOLD);
        Font fntb2 = new Font(Font.TIMES_ROMAN, 14, Font.BOLD);

        //
        Phrase spacePhrase = new Phrase();
        Chunk ch = new Chunk(spacer, fnt);
        spacePhrase.add(ch);

        float[] widths = { 15f, 85f }; // percentages
        PdfPTable headTable = new PdfPTable(widths);
        headTable.setWidthPercentage(100);
        headTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
        headTable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
        // image.setWidthPercentage(15.0f);
        PdfPCell cell = new PdfPCell(image);
        cell.setBorder(Rectangle.NO_BORDER);
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        // cell.setFixedHeight(46f);
        headTable.addCell(cell);

        Phrase phrase = new Phrase();
        ch = new Chunk(
                "City of Bloomington Community Farmers Market\n Gift Certificates/Market Bucks Invoice\n ",
                fntb2);
        phrase.add(ch);
        Paragraph pp = new Paragraph();
        pp.setIndentationLeft(20);
        pp.setAlignment(Element.ALIGN_LEFT);
        pp.add(phrase);
        cell = new PdfPCell(pp);
        cell.setBorder(Rectangle.NO_BORDER);
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        headTable.addCell(cell);
        document.add(headTable);
        //
        float[] widths3 = { 50f, 50f }; // percentages
        PdfPTable table = new PdfPTable(widths3);
        table.setWidthPercentage(100);
        table.getDefaultCell().setBorder(Rectangle.NO_BORDER);
        table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
        phrase = new Phrase();
        ch = new Chunk(" Vendor Name: ", fntb);
        phrase.add(ch);
        ch = new Chunk(vendor.getFullName(), fnt);
        phrase.add(ch);
        cell = new PdfPCell(phrase);
        cell.setHorizontalAlignment(Element.ALIGN_LEFT);
        cell.setBorder(Rectangle.NO_BORDER);
        table.addCell(cell);
        //         
        phrase = new Phrase();
        ch = new Chunk("Date: ", fntb);
        phrase.add(ch);
        ch = new Chunk(redeem.getDate(), fnt);
        phrase.add(ch);
        cell = new PdfPCell(phrase);
        cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
        cell.setBorder(Rectangle.NO_BORDER);
        table.addCell(cell);
        phrase = new Phrase();
        ch = new Chunk(" Vendor Number: ", fntb);
        phrase.add(ch);
        ch = new Chunk(vendor.getId(), fnt);
        phrase.add(ch);
        cell = new PdfPCell(phrase);
        cell.setHorizontalAlignment(Element.ALIGN_LEFT);
        cell.setBorder(Rectangle.NO_BORDER);
        table.addCell(cell);
        phrase = new Phrase(); // empty cell
        ch = new Chunk(" ", fntb);
        phrase.add(ch);
        cell = new PdfPCell(phrase);
        cell.setHorizontalAlignment(Element.ALIGN_LEFT);
        cell.setBorder(Rectangle.NO_BORDER);
        table.addCell(cell);
        table.addCell(cell); // extra space
        table.addCell(cell);
        document.add(table);
        //
        phrase = new Phrase(new Chunk("\n", fnt));
        document.add(phrase);
        //
        float[] widths2 = { 30f, 25f, 15f, 15f, 15f }; // percentages
        table = new PdfPTable(widths2);
        table.setWidthPercentage(90);
        // table.getDefaultCell().setBorder(Rectangle.NO_BORDER);
        table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
        table.getDefaultCell().setVerticalAlignment(Element.ALIGN_MIDDLE);
        // table.getDefaultCell().setPadding(5);
        phrase = new Phrase();
        ch = new Chunk("Type of Voucher", fntb);
        phrase.add(ch);
        cell = new PdfPCell(phrase);
        cell.setBorderWidth(2f);
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        cell.setPadding(4);
        cell.setLeading(2f, 1.2f);
        table.addCell(cell);
        //
        phrase = new Phrase();
        ch = new Chunk("City Account Number", fntb);
        phrase.add(ch);
        cell = new PdfPCell(phrase);
        cell.setBorderWidth(2f);
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        cell.setPadding(4);
        cell.setLeading(2f, 1.2f);
        table.addCell(cell);
        //
        phrase = new Phrase();
        ch = new Chunk("Quantity", fntb);
        phrase.add(ch);
        cell = new PdfPCell(phrase);
        cell.setBorderWidth(2f);
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        cell.setPadding(4);
        cell.setLeading(2f, 1.2f);
        table.addCell(cell);

        phrase = new Phrase();
        ch = new Chunk("Multiply", fntb);
        phrase.add(ch);
        cell = new PdfPCell(phrase);
        cell.setBorderWidth(2f);
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        cell.setPadding(4);
        cell.setLeading(2f, 1.2f);
        table.addCell(cell);

        phrase = new Phrase();
        ch = new Chunk("Value", fntb);
        phrase.add(ch);
        cell = new PdfPCell(phrase);
        cell.setBorderWidth(2f);
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell.setVerticalAlignment(Element.ALIGN_CENTER);
        cell.setPadding(4);
        cell.setLeading(2f, 1.2f);
        table.addCell(cell);
        //
        // second row
        phrase = new Phrase();
        ch = new Chunk("Market Bucks", fnt);
        phrase.add(ch);
        cell = new PdfPCell(phrase);
        table.addCell(cell);
        //
        phrase = new Phrase();
        ch = new Chunk("201-18-1865003-47240", fnt);
        phrase.add(ch);
        cell = new PdfPCell(phrase);
        table.addCell(cell);
        //
        phrase = new Phrase();
        String str = " ";
        if (bk_bucks.size() > 0) {
            str = "" + bk_bucks.size();
        }
        ch = new Chunk(str, fnt);
        phrase.add(ch);
        cell = new PdfPCell(phrase);
        cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
        cell.setVerticalAlignment(Element.ALIGN_CENTER);
        cell.setPadding(4);
        table.addCell(cell);

        phrase = new Phrase();
        ch = new Chunk("x $3.00 = ", fnt);
        phrase.add(ch);
        cell = new PdfPCell(phrase);
        table.addCell(cell);

        phrase = new Phrase();
        str = " ";
        if (bk_total > 0) {
            str = "$" + bk_total + ".00";
        }
        ch = new Chunk(str, fnt);
        phrase.add(ch);
        cell = new PdfPCell(phrase);
        cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
        cell.setVerticalAlignment(Element.ALIGN_CENTER);
        cell.setPadding(4);
        table.addCell(cell);
        //
        // 3rd row
        phrase = new Phrase();
        ch = new Chunk("$5 Gift Cerificates", fnt);
        phrase.add(ch);
        cell = new PdfPCell(phrase);
        table.addCell(cell);
        //
        phrase = new Phrase();
        ch = new Chunk("201-18-1865003-47230", fnt);
        phrase.add(ch);
        cell = new PdfPCell(phrase);
        table.addCell(cell);
        //
        phrase = new Phrase();
        str = " ";
        if (gc5_bucks.size() > 0) {
            str = "" + gc5_bucks.size();
        }
        ch = new Chunk(str, fnt);
        phrase.add(ch);
        cell = new PdfPCell(phrase);
        cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
        cell.setVerticalAlignment(Element.ALIGN_CENTER);
        cell.setPadding(4);
        table.addCell(cell);

        phrase = new Phrase();
        ch = new Chunk("x $5.00 = ", fnt);
        phrase.add(ch);
        cell = new PdfPCell(phrase);
        table.addCell(cell);

        phrase = new Phrase();
        str = " ";
        if (gc5_total > 0) {
            str = "$" + gc5_total + ".00";
        }
        ch = new Chunk(str, fnt);
        phrase.add(ch);
        cell = new PdfPCell(phrase);
        cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
        cell.setVerticalAlignment(Element.ALIGN_CENTER);
        cell.setPadding(4);
        table.addCell(cell);
        //
        // 4th row
        phrase = new Phrase();
        ch = new Chunk("$20 Gift Certificates", fnt);
        phrase.add(ch);
        cell = new PdfPCell(phrase);
        table.addCell(cell);
        //
        phrase = new Phrase();
        ch = new Chunk("201-18-1865003-47230", fnt);
        phrase.add(ch);
        cell = new PdfPCell(phrase);
        table.addCell(cell);
        //
        phrase = new Phrase();
        str = " ";
        if (gc20_bucks.size() > 0) {
            str = "" + gc20_bucks.size();
        }
        ch = new Chunk(str, fnt);
        phrase.add(ch);
        cell = new PdfPCell(phrase);
        cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
        cell.setVerticalAlignment(Element.ALIGN_CENTER);
        cell.setPadding(4);
        table.addCell(cell);

        phrase = new Phrase();
        ch = new Chunk("x $20.00 = ", fnt);
        phrase.add(ch);
        cell = new PdfPCell(phrase);
        table.addCell(cell);
        str = " ";
        if (gc20_total > 0) {
            str = "$" + gc20_total + ".00";
        }
        phrase = new Phrase();
        ch = new Chunk(str, fnt);
        phrase.add(ch);
        cell = new PdfPCell(phrase);
        cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
        cell.setVerticalAlignment(Element.ALIGN_CENTER);
        cell.setPadding(4);
        table.addCell(cell);
        //
        // 5th row total
        phrase = new Phrase();
        ch = new Chunk(" Total Value: ", fntb);
        phrase.add(ch);
        cell = new PdfPCell(phrase);
        cell.setColspan(4);
        cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
        cell.setVerticalAlignment(Element.ALIGN_CENTER);
        cell.setBorderWidth(2f);
        cell.setPadding(4);
        cell.setLeading(2f, 1.2f);
        table.addCell(cell);
        //
        phrase = new Phrase();
        ch = new Chunk("$" + total + ".00", fntb);
        phrase.add(ch);
        cell = new PdfPCell(phrase);
        cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
        cell.setVerticalAlignment(Element.ALIGN_CENTER);
        cell.setBorderWidth(2f);
        cell.setPadding(4);
        cell.setLeading(2f, 1.2f);
        table.addCell(cell);
        document.add(table);
        //
        //
        float[] withs5 = { 100f };
        table = new PdfPTable(withs5);
        table.setWidthPercentage(100);
        cell = new PdfPCell(new Phrase(" "));
        cell.setBorder(Rectangle.BOTTOM);
        // cell.setBorderColorBottom(Color.BLACK);
        cell.setBorderWidthBottom(2f);
        table.addCell(cell);
        document.add(table);
        //
        ch = new Chunk("\n", fnt);
        phrase = new Phrase();
        phrase.add(ch);
        document.add(phrase);
        //
        // float[] widths3 = {50f, 50f}; // percentages
        table = new PdfPTable(widths3);
        table.setWidthPercentage(100);
        // table.getDefaultCell().setBorder(Rectangle.NO_BORDER);
        table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
        phrase = new Phrase();
        ch = new Chunk(" Data Entry Completed by: ", fntb);
        phrase.add(ch);
        ch = new Chunk(user.getFullName(), fnt);
        phrase.add(ch);
        cell = new PdfPCell(phrase);
        cell.setHorizontalAlignment(Element.ALIGN_LEFT);
        table.addCell(cell);
        //
        phrase = new Phrase();
        ch = new Chunk(" Invoice Number: ", fntb);
        phrase.add(ch);
        ch = new Chunk(redeem.getId(), fnt);
        phrase.add(ch);
        cell = new PdfPCell(phrase);
        cell.setHorizontalAlignment(Element.ALIGN_LEFT);
        table.addCell(cell);
        document.add(table);
        document.add(spacePhrase);
        document.add(spacePhrase);
        //
        // adding bucks and GC
        //
        float[] widths4 = { 100f }; // percentages
        table = new PdfPTable(widths4);
        table.setWidthPercentage(100);
        // table.getDefaultCell().setBorder(Rectangle.NO_BORDER);
        table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_LEFT);
        int row = 1, col = 1;
        if (bk_bucks.size() > 0) {
            phrase = new Phrase();
            ch = new Chunk(" Market Bucks ", fntb);
            phrase.add(ch);
            cell = new PdfPCell(phrase);
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setBorderWidth(2f);
            table.addCell(cell);
            phrase = new Phrase();
            for (Buck one : bk_bucks) {
                ch = new Chunk("" + one.getId() + " ", fntb);
                phrase.add(ch);
                col++;
                if (col > 15) {
                    row++;
                    col = 1;
                    cell = new PdfPCell(phrase);
                    cell.setHorizontalAlignment(Element.ALIGN_LEFT);
                    table.addCell(cell);
                    phrase = new Phrase();
                }
            }
            if (col > 1) {
                cell = new PdfPCell(phrase);
                cell.setHorizontalAlignment(Element.ALIGN_LEFT);
                table.addCell(cell);
            }
            if (row < 10) {
                for (int j = 0; j < 2; j++) {
                    phrase = new Phrase();
                    ch = new Chunk(" ", fntb);
                    phrase.add(ch);
                    cell = new PdfPCell(phrase);
                    cell.setHorizontalAlignment(Element.ALIGN_LEFT);
                    table.addCell(cell);
                    row++;
                }
            }
        }
        col = 1;
        if (gc_bucks.size() > 0) {
            phrase = new Phrase();
            ch = new Chunk(" Gift Certificates ", fntb);
            phrase.add(ch);
            cell = new PdfPCell(phrase);
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setBorderWidth(2f);
            table.addCell(cell);
            phrase = new Phrase();
            for (Buck one : gc_bucks) {
                ch = new Chunk("" + one.getId() + " ", fntb);
                phrase.add(ch);
                col++;
                if (col > 15) {
                    row++;
                    col = 1;
                    cell = new PdfPCell(phrase);
                    cell.setHorizontalAlignment(Element.ALIGN_LEFT);
                    table.addCell(cell);
                    phrase = new Phrase();
                }
            }
            if (col > 1) {
                cell = new PdfPCell(phrase);
                cell.setHorizontalAlignment(Element.ALIGN_LEFT);
                table.addCell(cell);
            }
            if (row < 15) {
                for (int j = 0; j < 2; j++) {
                    phrase = new Phrase();
                    ch = new Chunk(" ", fntb);
                    phrase.add(ch);
                    cell = new PdfPCell(phrase);
                    cell.setHorizontalAlignment(Element.ALIGN_LEFT);
                    table.addCell(cell);
                    row++;
                }
            }
        }
        if (disputes != null && disputes.size() > 0) {
            phrase = new Phrase();
            ch = new Chunk(" Disputed Market Bucks and/or Gift Certificates (number: reason)", fntb);
            phrase.add(ch);
            cell = new PdfPCell(phrase);
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setBorderWidth(2f);
            table.addCell(cell);
            row++;
            for (Dispute one : disputes) {
                phrase = new Phrase();
                ch = new Chunk(one.getBuck_id() + ": " + one.getReason(), fnt);
                phrase.add(ch);
                if (one.hasNotes()) {
                    ch = new Chunk("\nNotice: " + one.getNotes(), fnt);
                    phrase.add(ch);
                    row++;
                }
                cell = new PdfPCell(phrase);
                cell.setHorizontalAlignment(Element.ALIGN_LEFT);
                table.addCell(cell);
                row++;
            }
        }
        if (redeem.hasNotes()) {
            phrase = new Phrase();
            ch = new Chunk("\nNotice: " + redeem.getNotes(), fnt);
            phrase.add(ch);
            cell = new PdfPCell(phrase);
            cell.setHorizontalAlignment(Element.ALIGN_LEFT);
            table.addCell(cell);
            row++;
        }
        if (row < 18) {
            for (int j = row; j < 18; j++) {
                phrase = new Phrase();
                ch = new Chunk(" ", fntb);
                phrase.add(ch);
                cell = new PdfPCell(phrase);
                cell.setHorizontalAlignment(Element.ALIGN_LEFT);
                table.addCell(cell);
            }
        }

        document.add(table);
        document.close();
        writer.close();
        res.setHeader("Expires", "0");
        res.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
        res.setHeader("Pragma", "public");
        //
        // setting the content type
        res.setHeader("Content-Disposition", " attachment; filename=" + filename);
        res.setContentType("application/pdf");
        //
        // the contentlength is needed for MSIE!!!
        res.setContentLength(baos.size());
        //
        out = res.getOutputStream();
        if (out != null) {
            baos.writeTo(out);
        }
    } catch (Exception ex) {
        System.err.println(ex);
    }
}

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

License:Open Source License

/**
 * Outputs a PDF file report of the data in drs to the given
 * output stream.//  w w  w .ja v  a 2 s. com
 * @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
 *//*from   www .j a  va  2s  .  co  m*/
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:candelaria.presentacion.beans.DetalleFacturaControlador.java

public void imprimirFac() {
    //DateFormat dfDateFull = DateFormat.getDateInstance(DateFormat.FULL);
    try {//from w ww .  ja va 2  s  .c om

        //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;// w ww.java2 s .co  m
    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:classroom.filmfestival_b.Movies12.java

@SuppressWarnings("unchecked")
public static void main(String[] args) {

    // step 1/*w  w w .j  a  va  2 s. c o  m*/
    Document document = new Document();
    try {
        // step 2
        OutputStream os = new FileOutputStream(RESULT);
        PdfWriter.getInstance(document, os);
        // step 3
        document.open();
        // step 4
        Session session = (Session) MySessionFactory.currentSession();
        Query q = session.createQuery("from FilmTitle order by title");
        java.util.List<FilmTitle> results = q.list();

        PdfPTable table = new PdfPTable(2);
        table.setWidths(new float[] { 1, 5 });
        File f;
        Image img;
        Paragraph p;
        Chunk c;
        Font bold = new Font(Font.HELVETICA, 12, Font.BOLD);
        Font italic = new Font(Font.HELVETICA, 12, Font.ITALIC);
        for (FilmTitle movie : results) {
            f = new File("resources/classroom/filmposters/" + movie.getFilmId() + ".jpg");
            if (f.exists()) {
                img = Image.getInstance(f.getPath());
                table.addCell(img);
            } else {
                table.addCell("");
            }
            p = new Paragraph(20);
            c = new Chunk(movie.getTitle(), bold);
            c.setAnchor("http://cinema.lowagie.com/titel.php?id=" + movie.getFilmId());
            p.add(c);
            c = new Chunk(" (" + movie.getYear() + ") ", italic);
            p.add(c);
            c = new Chunk("IMDB");
            c.setAnchor("http://www.imdb.com/title/tt" + movie.getImdb());
            p.add(c);
            table.addCell(p);
        }
        document.add(table);
        // step 5
        document.close();
    } catch (IOException e) {
        LOGGER.error("IOException: ", e);
    } catch (DocumentException e) {
        LOGGER.error("DocumentException: ", e);
    }
}

From source file:classroom.filmfestival_b.Movies13.java

@SuppressWarnings("unchecked")
public static void main(String[] args) {

    // step 1//from w  w  w  . j a va  2 s .  c  o  m
    Document document = new Document();
    try {
        // step 2
        OutputStream os = new FileOutputStream(RESULT);
        PdfWriter.getInstance(document, os);
        // step 3
        document.open();
        // step 4
        Session session = (Session) MySessionFactory.currentSession();
        Query q = session.createQuery("from FilmTitle order by title");
        java.util.List<FilmTitle> results = q.list();

        PdfPTable table = new PdfPTable(2);
        table.setWidths(new float[] { 1, 5 });
        File f;
        Paragraph p;
        Chunk c;
        PdfPCell cell;
        Font bold = new Font(Font.HELVETICA, 12, Font.BOLD);
        Font italic = new Font(Font.HELVETICA, 12, Font.ITALIC);
        for (FilmTitle movie : results) {
            f = new File("resources/classroom/filmposters/" + movie.getFilmId() + ".jpg");
            if (f.exists()) {
                cell = new PdfPCell(Image.getInstance(f.getPath()), true);
                cell.setPadding(2);
            } else {
                cell = new PdfPCell();
            }
            table.addCell(cell);
            p = new Paragraph(20);
            c = new Chunk(movie.getTitle(), bold);
            c.setAnchor("http://cinema.lowagie.com/titel.php?id=" + movie.getFilmId());
            p.add(c);
            c = new Chunk(" (" + movie.getYear() + ") ", italic);
            p.add(c);
            c = new Chunk("IMDB");
            c.setAnchor("http://www.imdb.com/title/tt" + movie.getImdb());
            p.add(c);
            cell = new PdfPCell();
            cell.setUseAscender(true);
            cell.setUseDescender(true);
            cell.addElement(p);
            Set<DirectorName> directors = movie.getDirectorNames();
            List list = new List();
            for (DirectorName director : directors) {
                list.add(director.getName());
            }
            cell.addElement(list);
            table.addCell(cell);
        }
        document.add(table);
        // step 5
        document.close();
    } catch (IOException e) {
        LOGGER.error("IOException: ", e);
    } catch (DocumentException e) {
        LOGGER.error("DocumentException: ", e);
    }
}

From source file:classroom.filmfestival_b.Movies14.java

@SuppressWarnings("unchecked")
public static void main(String[] args) {

    // step 1//  w  w w  .  j  a  v a 2 s  . co  m
    Document document = new Document();
    try {
        // step 2
        OutputStream os = new FileOutputStream(RESULT);
        PdfWriter.getInstance(document, os);
        // step 3
        document.open();
        // step 4
        Session session = (Session) MySessionFactory.currentSession();
        Query q = session.createQuery("from FilmTitle order by title");
        java.util.List<FilmTitle> results = q.list();

        PdfPTable table = new PdfPTable(2);
        table.setWidths(new float[] { 1, 5 });
        File f;
        Paragraph p;
        Chunk c;
        PdfPCell cell = new PdfPCell();
        Font bold = new Font(Font.HELVETICA, 12, Font.BOLD);
        Font italic = new Font(Font.HELVETICA, 12, Font.ITALIC);
        p = new Paragraph("FILMFESTIVAL", bold);
        p.setAlignment(Element.ALIGN_CENTER);
        cell.addElement(p);
        cell.setColspan(2);
        cell.setBorder(PdfPCell.NO_BORDER);
        table.addCell(cell);
        cell = new PdfPCell();
        cell.setFixedHeight(20);
        cell.setColspan(2);
        cell.setBorder(PdfPCell.NO_BORDER);
        cell.setCellEvent(new Movies14().new PageCell());
        table.addCell(cell);
        table.setHeaderRows(2);
        table.setFooterRows(1);
        for (FilmTitle movie : results) {
            f = new File("resources/classroom/filmposters/" + movie.getFilmId() + ".jpg");
            if (f.exists()) {
                cell = new PdfPCell(Image.getInstance(f.getPath()), true);
                cell.setPadding(2);
            } else {
                cell = new PdfPCell();
            }
            table.addCell(cell);
            p = new Paragraph(20);
            c = new Chunk(movie.getTitle(), bold);
            c.setAnchor("http://cinema.lowagie.com/titel.php?id=" + movie.getFilmId());
            p.add(c);
            c = new Chunk(" (" + movie.getYear() + ") ", italic);
            p.add(c);
            c = new Chunk("IMDB");
            c.setAnchor("http://www.imdb.com/title/tt" + movie.getImdb());
            p.add(c);
            cell = new PdfPCell();
            cell.setUseAscender(true);
            cell.setUseDescender(true);
            cell.addElement(p);
            Set<DirectorName> directors = movie.getDirectorNames();
            List list = new List();
            for (DirectorName director : directors) {
                list.add(director.getName());
            }
            cell.addElement(list);
            table.addCell(cell);
        }
        document.add(table);
        // step 5
        document.close();
    } catch (IOException e) {
        LOGGER.error("IOException: ", e);
    } catch (DocumentException e) {
        LOGGER.error("DocumentException: ", e);
    }
}

From source file:classroom.filmfestival_b.Movies15.java

@SuppressWarnings("unchecked")
public static void main(String[] args) {

    // step 1//  w  ww  .ja v a 2  s.c  o m
    Document document = new Document();
    try {
        // step 2
        OutputStream os = new FileOutputStream(RESULT);
        PdfWriter writer = PdfWriter.getInstance(document, os);
        // step 3
        document.open();
        // step 4
        Session session = (Session) MySessionFactory.currentSession();
        Query q = session.createQuery("from FilmTitle order by title");
        java.util.List<FilmTitle> results = q.list();

        PdfPTable table = new PdfPTable(2);
        table.setComplete(false);
        table.setWidths(new float[] { 1, 5 });
        File f;
        Paragraph p;
        Chunk c;
        PdfPCell cell = new PdfPCell();
        Font bold = new Font(Font.HELVETICA, 12, Font.BOLD);
        Font italic = new Font(Font.HELVETICA, 12, Font.ITALIC);
        p = new Paragraph("FILMFESTIVAL", bold);
        p.setAlignment(Element.ALIGN_CENTER);
        cell.addElement(p);
        cell.setColspan(2);
        cell.setBorder(PdfPCell.NO_BORDER);
        table.addCell(cell);
        cell = new PdfPCell();
        cell.setFixedHeight(20);
        cell.setColspan(2);
        cell.setBorder(PdfPCell.NO_BORDER);
        cell.setCellEvent(new Movies14().new PageCell());
        table.addCell(cell);
        table.setHeaderRows(2);
        table.setFooterRows(1);
        int counter = 10;
        for (FilmTitle movie : results) {
            f = new File("resources/classroom/filmposters/" + movie.getFilmId() + ".jpg");
            if (f.exists()) {
                cell = new PdfPCell(Image.getInstance(f.getPath()), true);
                cell.setPadding(2);
            } else {
                cell = new PdfPCell();
            }
            table.addCell(cell);
            p = new Paragraph(20);
            c = new Chunk(movie.getTitle(), bold);
            c.setAnchor("http://cinema.lowagie.com/titel.php?id=" + movie.getFilmId());
            p.add(c);
            c = new Chunk(" (" + movie.getYear() + ") ", italic);
            p.add(c);
            c = new Chunk("IMDB");
            c.setAnchor("http://www.imdb.com/title/tt" + movie.getImdb());
            p.add(c);
            cell = new PdfPCell();
            cell.setUseAscender(true);
            cell.setUseDescender(true);
            cell.addElement(p);
            Set<DirectorName> directors = movie.getDirectorNames();
            List list = new List();
            for (DirectorName director : directors) {
                list.add(director.getName());
            }
            cell.addElement(list);
            table.addCell(cell);
            if (counter % 10 == 0) {
                document.add(table);
            }
            System.out.println(writer.getPageNumber());
            counter++;
        }
        table.setComplete(true);
        document.add(table);
        // step 5
        document.close();
    } catch (IOException e) {
        LOGGER.error("IOException: ", e);
    } catch (DocumentException e) {
        LOGGER.error("DocumentException: ", e);
    }
}

From source file:classroom.filmfestival_c.Movies16.java

@SuppressWarnings("unchecked")
public static void main(String[] args) {

    // step 1/*from w ww . ja va 2  s. co m*/
    Document document = new Document();
    try {
        // step 2
        OutputStream os = new FileOutputStream(RESULT);
        PdfWriter.getInstance(document, os);
        // step 3
        document.open();
        // step 4
        PdfPTable table;
        PdfPCell cell;
        Chunk imdb;

        Session session = (Session) MySessionFactory.currentSession();
        Query q = session.createQuery(
                "select distinct festival.id.day from FestivalScreening as festival order by festival.id.day");
        java.util.List<Date> days = q.list();
        java.util.List<FestivalScreening> screenings;

        for (Date day : days) {
            GregorianCalendar gc = new GregorianCalendar();
            gc.setTime(day);
            if (gc.get(GregorianCalendar.YEAR) != YEAR)
                continue;

            table = new PdfPTable(new float[] { 7, 1, 2, 1 });
            cell = new PdfPCell(new Phrase(day.toString(), NORMALWHITE));
            cell.setBackgroundColor(BLACK);
            cell.setColspan(4);
            table.addCell(cell);

            q = session.createQuery("from FestivalScreening where id.day=? order by id.time, id.place");
            q.setDate(0, day);
            screenings = q.list();
            for (FestivalScreening screening : screenings) {
                table.addCell(screening.getFilmTitle().getTitle());
                table.addCell(screening.getId().getPlace().toString());
                cell = new PdfPCell(new Phrase(screening.getId().getTime().toString()));
                if (screening.getPress() == 1) {
                    cell.setBackgroundColor(SILVER);
                }
                table.addCell(cell);
                if (screening.getFilmTitle().getImdb().startsWith("?")) {
                    table.addCell("");
                } else {
                    imdb = new Chunk("imdb");
                    imdb.setAnchor("http://imdb.com/title/tt" + screening.getFilmTitle().getImdb());
                    table.addCell(new Phrase(imdb));
                }
            }

            document.add(table);
        }

        // step 5
        document.close();
    } catch (IOException e) {
        LOGGER.error("IOException: ", e);
    } catch (DocumentException e) {
        LOGGER.error("DocumentException: ", e);
    }
}