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

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

Introduction

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

Prototype

public PdfPCell getDefaultCell() 

Source Link

Document

Gets the default PdfPCell that will be used as reference for all the addCell methods except addCell(PdfPCell).

Usage

From source file:com.huateng.system.util.PdfUtil.java

License:Open Source License

public static void create(String mchtId, String selMchtId, String path, List<Object[]> list,
        LinkedHashMap<String, List<Object[]>> map, Set<String> set) throws Exception {

    BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);

    ////  www .ja  va2s  . c om
    Font font17 = new Font(bfChinese, 17, Font.BOLD);
    Font font8 = new Font(bfChinese, 8, Font.NORMAL);
    Font font9 = new Font(bfChinese, 9, Font.NORMAL);
    Font font9Bold = new Font(bfChinese, 9, Font.BOLD);
    Font font8Red = new Font(bfChinese, 8, Font.NORMAL);
    font8Red.setColor(Color.RED);
    Font font8Green = new Font(bfChinese, 8, Font.NORMAL);
    font8Green.setColor(Color.GREEN);

    logger.info("Starting build document...");

    Document document = new Document(PageSize.A4, 36, 36, 36, 36);
    PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(path));
    document.open();
    LINECANVAS border = new LINECANVAS();

    //
    float[] widths = { 0.1f, 0.35f, 0.35f, 0.1f, 0.1f };
    PdfPTable table = new PdfPTable(widths);
    table.setWidthPercentage(100);
    table.getDefaultCell().setBorder(PdfPCell.NO_BORDER);
    table.getDefaultCell().setFixedHeight(12);

    //CELL
    PdfPCell cellMchntId = new PdfPCell(new Paragraph(mchtId, font8));
    cellMchntId.setBorder(PdfPCell.BOTTOM);
    cellMchntId.setHorizontalAlignment(Element.ALIGN_CENTER);

    PdfPCell cellMchntName = new PdfPCell(new Paragraph(InformationUtil.getMchtName(mchtId), font8));
    cellMchntName.setBorder(PdfPCell.BOTTOM);
    cellMchntName.setHorizontalAlignment(Element.ALIGN_CENTER);

    String point = InformationUtil.getCurPaperPoint(selMchtId);
    PdfPCell cellPoint;
    cellPoint = new PdfPCell(new Paragraph(point, font8Red));
    cellPoint.setBorder(PdfPCell.NO_BORDER);
    cellPoint.setHorizontalAlignment(Element.ALIGN_CENTER);

    PdfPCell cellLevel;
    String level = InformationUtil.getCurPaperLevel(selMchtId);
    if (Integer.valueOf(point) >= 60) {
        cellLevel = new PdfPCell(new Paragraph(level, font8Green));
    } else {
        cellLevel = new PdfPCell(new Paragraph(level, font8Red));
    }
    cellLevel.setBorder(PdfPCell.NO_BORDER);
    cellLevel.setHorizontalAlignment(Element.ALIGN_CENTER);

    //
    Image img = Image.getInstance(
            ServletActionContext.getServletContext().getResource("/ext/resources/images/Title_logo.gif"));
    img.scalePercent(70);
    float w = img.getScaledWidth();
    float h = img.getScaledHeight();
    writer.getDirectContent().addImage(img, w, 0, 0, h, 36, PageSize.A4.getHeight() - 36 - h);

    //
    PdfPCell cell = new PdfPCell(new Paragraph("?", font17));
    cell.setHorizontalAlignment(Element.ALIGN_CENTER);
    cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
    cell.setColspan(5);
    cell.setFixedHeight(h);
    cell.setBorder(PdfPCell.NO_BORDER);
    table.addCell(cell);

    cell = new PdfPCell();
    cell.setFixedHeight(20);
    cell.setColspan(5);
    cell.setBorder(PdfPCell.NO_BORDER);
    table.addCell(cell);

    table.addCell(new Paragraph("?", font8));
    table.addCell(cellMchntId);
    table.addCell(" ");
    table.addCell(new Paragraph(": ", font8));
    table.addCell(cellPoint);

    table.addCell(new Paragraph("??", font8));
    table.addCell(cellMchntName);
    table.addCell(" ");
    table.addCell(new Paragraph(": ", font8));
    table.addCell(cellLevel);

    document.add(table);
    document.add(new Paragraph("\n\n"));

    //?
    PdfPTable t = new PdfPTable(1);

    Iterator<Object[]> it0 = list.iterator();
    int i = 1;
    while (it0.hasNext()) {
        Object[] obj = it0.next();
        PdfPCell c = new PdfPCell();
        c.addElement(new Paragraph("Q" + String.valueOf(i++) + "" + obj[1].toString(), font9Bold));
        List<Object[]> opts = map.get(obj[0].toString());
        String opt = "";
        Iterator<Object[]> it1 = opts.iterator();
        while (it1.hasNext()) {
            Object[] o = it1.next();
            if (set.contains(o[0])) {
                opt += "? ";
                opt += o[1].toString();
                opt += "         ";
            } else {
                opt += " ";
                opt += o[1].toString();
                opt += "         ";
            }
        }
        c.addElement(new Paragraph(opt.trim(), font9));
        c.setBorder(PdfPCell.NO_BORDER);
        if (i - 1 != list.size()) {
            c.setCellEvent(border);
        }
        t.addCell(c);
    }

    PdfPTable oTable = new PdfPTable(1);
    oTable.setWidthPercentage(100);
    PdfPCell ce = new PdfPCell(t);
    ce.setBorderColor(Color.GRAY);
    oTable.addCell(ce);

    document.add(oTable);

    document.close();

    logger.info("Finish build document...");
}

From source file:com.huateng.system.util.PdfUtil.java

License:Open Source License

public static void create(String path, List<Object[]> list, LinkedHashMap<String, List<Object[]>> map)
        throws Exception {

    BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);

    ///* w w w.  j av a 2 s.  co m*/
    Font font17 = new Font(bfChinese, 17, Font.BOLD);
    Font font8 = new Font(bfChinese, 8, Font.NORMAL);
    Font font10 = new Font(bfChinese, 10, Font.NORMAL);
    Font font10Bold = new Font(bfChinese, 10, Font.BOLD);
    Font font8Red = new Font(bfChinese, 8, Font.NORMAL);
    font8Red.setColor(Color.RED);
    Font font8Green = new Font(bfChinese, 8, Font.NORMAL);
    font8Green.setColor(Color.GREEN);

    logger.info("Starting build document...");

    Document document = new Document(PageSize.A4, 36, 36, 36, 36);
    PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(path));
    document.open();
    LINECANVAS border = new LINECANVAS();

    //
    float[] widths = { 0.1f, 0.35f, 0.55f };
    PdfPTable table = new PdfPTable(widths);
    table.setWidthPercentage(100);
    table.getDefaultCell().setBorder(PdfPCell.NO_BORDER);
    table.getDefaultCell().setFixedHeight(12);

    //CELL
    PdfPCell cellMchntId = new PdfPCell(new Paragraph("XXXXXXXXXXXXXXX", font8));
    cellMchntId.setBorder(PdfPCell.BOTTOM);
    cellMchntId.setHorizontalAlignment(Element.ALIGN_CENTER);

    PdfPCell cellMchntName = new PdfPCell(new Paragraph("?", font8));
    cellMchntName.setBorder(PdfPCell.BOTTOM);
    cellMchntName.setHorizontalAlignment(Element.ALIGN_CENTER);

    //
    Image img = Image.getInstance(
            ServletActionContext.getServletContext().getResource("/ext/resources/images/Title_logo.gif"));
    img.scalePercent(70);
    float w = img.getScaledWidth();
    float h = img.getScaledHeight();
    writer.getDirectContent().addImage(img, w, 0, 0, h, 36, PageSize.A4.getHeight() - 36 - h);

    //
    PdfPCell cell = new PdfPCell(new Paragraph("?", font17));
    cell.setHorizontalAlignment(Element.ALIGN_CENTER);
    cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
    cell.setColspan(3);
    cell.setFixedHeight(h);
    cell.setBorder(PdfPCell.NO_BORDER);
    table.addCell(cell);

    cell = new PdfPCell();
    cell.setFixedHeight(20);
    cell.setColspan(3);
    cell.setBorder(PdfPCell.NO_BORDER);
    table.addCell(cell);

    table.addCell(new Paragraph("?", font8));
    table.addCell(cellMchntId);
    table.addCell(" ");

    table.addCell(new Paragraph("??", font8));
    table.addCell(cellMchntName);
    table.addCell(" ");

    document.add(table);
    document.add(new Paragraph("\n\n"));

    //?
    PdfPTable t = new PdfPTable(1);

    Iterator<Object[]> it0 = list.iterator();
    int i = 1;
    while (it0.hasNext()) {
        Object[] obj = it0.next();
        PdfPCell c = new PdfPCell();
        c.addElement(new Paragraph("Q" + String.valueOf(i++) + "" + obj[1].toString(), font10Bold));
        List<Object[]> opts = map.get(obj[0].toString());
        String opt = "";
        Iterator<Object[]> it1 = opts.iterator();
        while (it1.hasNext()) {
            Object[] o = it1.next();
            opt += " ";
            opt += o[1].toString();
            opt += "         ";
        }
        c.addElement(new Paragraph(opt.trim(), font10));
        c.setBorder(PdfPCell.NO_BORDER);
        if (i - 1 != list.size()) {
            c.setCellEvent(border);
        }
        t.addCell(c);
    }

    PdfPTable oTable = new PdfPTable(1);
    oTable.setWidthPercentage(100);
    PdfPCell ce = new PdfPCell(t);
    ce.setBorderColor(Color.GRAY);
    oTable.addCell(ce);

    document.add(oTable);

    document.close();

    logger.info("Finish build document...");
}

From source file:com.itn.excelDao.PdfView.java

@Override
protected void buildPdfDocument(Map<String, Object> model, Document document, PdfWriter writer,
        HttpServletRequest request, HttpServletResponse response) throws Exception {

    //Users user = (Users) model.get("user");
    List<Users> userlist = (List<Users>) model.get("allUsers");

    PdfPTable table = new PdfPTable(4);
    table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
    table.getDefaultCell().setVerticalAlignment(Element.ALIGN_MIDDLE);
    table.getDefaultCell().setBackgroundColor(Color.lightGray);

    table.addCell("ID");
    table.addCell("First Name");
    table.addCell("Last Name");
    table.addCell("Email");

    for (Users users : userlist) {
        table.addCell(users.getId().toString());
        table.addCell(users.getFirstName());
        table.addCell(users.getLastName());
        table.addCell(users.getEmail());
    }/*from ww w . ja v  a 2  s .  co  m*/

    document.add(table);

}

From source file:com.jk.framework.desktop.swing.dao.TableModelPdfBuilder.java

License:Apache License

/**
 * Creates the pdf table./*from w  w w  .  j  a va 2s .  c  o m*/
 *
 * @return the pdf P table
 * @throws DocumentException
 *             the document exception
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 */
public PdfPTable createPdfTable() throws DocumentException, IOException {
    final Font font = getFont();
    int columnCount = 0;
    for (int i = 0; i < this.model.getColumnCount(); i++) {
        if (this.model.isVisible(i)) {
            columnCount++;
        }
    }
    final PdfPTable pdfPTable = new PdfPTable(columnCount);
    pdfPTable.setRunDirection(getRunDirection());
    pdfPTable.getDefaultCell().setRunDirection(getRunDirection());
    pdfPTable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
    pdfPTable.getDefaultCell().setVerticalAlignment(Element.ALIGN_MIDDLE);
    pdfPTable.getDefaultCell().setNoWrap(true);

    createPdfHeaders(pdfPTable, font);
    loadDataTable(pdfPTable, font);
    return pdfPTable;

}

From source file:com.orange.atk.compModel.PDFGenerator.java

License:Apache License

/**
 * @see com.orange.atk.results.logger.documentGenerator.DocumentGenerator#dumpInStream(boolean, interpreter.logger.DocumentLogger)
 *//* w w  w. j a  v  a2 s.c o m*/

public void dumpInStream(boolean isParseErrorHappened, /*DocumentLogger dl,*/ org.w3c.dom.Document xmlDoc,
        Model model3) {
    long endTime = new Date().getTime();
    // step 1: creation of a document-object
    Document document = new Document();
    PdfWriter writer = null;

    // step 2:
    // we create a writer that listens to the document
    // and directs a PDF-stream to the outputStream
    try {
        writer = PdfWriter.getInstance(document, outputStream);
    } catch (DocumentException e1) {
        e1.printStackTrace();
        return;
    }
    writer.setViewerPreferences(PdfWriter.PageModeUseOutlines);
    // step 3: we open the document
    document.open();
    document.addTitle("REPORT");
    document.addCreationDate();

    HeaderFooter headerPage = new HeaderFooter(new Phrase("ScreenShot report"), false);
    HeaderFooter footerPage = new HeaderFooter(new Phrase(" - "), new Phrase(" - "));
    headerPage.setAlignment(Element.ALIGN_CENTER);
    footerPage.setAlignment(Element.ALIGN_CENTER);
    document.setHeader(headerPage);
    document.setFooter(footerPage);

    // Chapter 1 : Summary
    // Section 1 : Informations

    Chunk c = new Chunk("Summary");
    c.setBackground(ORANGE_COLOR, 200, 3f, 200f, 3f);
    c.setFont(FONT_PAR_TITLE);

    Paragraph title1 = new Paragraph(c);
    title1.setAlignment("CENTER");
    title1.setLeading(20);
    Chapter chapter1 = new Chapter(title1, 1);
    chapter1.setNumberDepth(0);

    Paragraph title11 = new Paragraph("Informations");
    Section section1 = chapter1.addSection(title11);
    Paragraph pSum = new Paragraph();
    pSum.add("Author : " + author);
    pSum.add(Chunk.NEWLINE);
    pSum.add("Group : " + group);
    pSum.add(Chunk.NEWLINE);
    pSum.add("Script : " + script);
    pSum.add(Chunk.NEWLINE);
    pSum.add("Reference directory: " + model3.getRefDirectory());
    pSum.add(Chunk.NEWLINE);
    pSum.add("Test directory: " + model3.getTestDirectory());
    pSum.add(Chunk.NEWLINE);
    SimpleDateFormat formatter = new SimpleDateFormat("MMMMM dd, yyyy - hh:mm aaa");
    String dateString = formatter.format(endTime);
    pSum.add("Date : " + dateString);
    pSum.add(Chunk.NEWLINE);
    pSum.add(Chunk.NEWLINE);
    if (model3.getNbFail() > 0) {
        pSum.add(model3.getNbFail() + "/" + model3.getNbImages() + " images didn't succeed the test.");
    } else {
        pSum.add("All images (" + model3.getNbImages() + ") have succeed this comparaison.");
    }
    pSum.add(Chunk.NEWLINE);
    pSum.setIndentationLeft(20);
    section1.add(pSum);
    section1.add(new Paragraph(Chunk.NEXTPAGE));

    try {
        document.add(chapter1);
    } catch (DocumentException e) {
        e.printStackTrace();
    }
    document.newPage();

    if (isParseErrorHappened) {
        document.close();
        return;
    }

    // Add generated pictures
    Chunk c3 = new Chunk("ScreenShots");
    c3.setBackground(ORANGE_COLOR, 200, 3f, 200f, 3f);
    c3.setFont(FONT_PAR_TITLE);
    Paragraph p3 = new Paragraph(c3);
    p3.setAlignment("CENTER");
    p3.setLeading(20);
    Chapter chapter3 = new Chapter(p3, 1);
    chapter3.setNumberDepth(0);

    NodeList imgs = xmlDoc.getElementsByTagName("img");
    for (int i = 0; i < imgs.getLength(); i++) {
        org.w3c.dom.Element eImg = (org.w3c.dom.Element) imgs.item(i);
        if (eImg.getElementsByTagName("Pass").item(0).getTextContent().equals(Model.FAIL)) {

            org.w3c.dom.Element eRef = (org.w3c.dom.Element) eImg.getElementsByTagName("Ref").item(0);
            org.w3c.dom.Element eTest = (org.w3c.dom.Element) eImg.getElementsByTagName("Test").item(0);
            Paragraph pScreen = new Paragraph(eTest.getAttributes().getNamedItem("name").getNodeValue() + " "
                    + eImg.getElementsByTagName("Pass").item(0).getTextContent());
            Section section31 = chapter3.addSection(pScreen);
            PdfPTable scTable = null;
            scTable = new PdfPTable(2);
            scTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
            scTable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
            scTable.getDefaultCell().setPadding(5);
            if (new File(eRef.getTextContent()).exists()) {
                Image refImg;
                try {
                    refImg = Image.getInstance(eRef.getTextContent());
                    refImg.scaleToFit(310, 260);
                    refImg.setAlignment(Element.ALIGN_BASELINE);
                    scTable.addCell(refImg);
                } catch (BadElementException e) {
                    e.printStackTrace();
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                } catch (DOMException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
            if (new File(eTest.getTextContent()).exists()) {
                Image testImg;
                try {
                    BufferedImage bi = ImageIO.read(new File(eTest.getTextContent()));
                    Graphics2D g2d = (Graphics2D) bi.getGraphics();
                    g2d.setStroke(new BasicStroke(1.5f));
                    g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.6f));

                    Boolean2D dif = model3.getCouplesComparaison().get(i).getDifWithMask();
                    //               if (squarable){
                    g2d.setColor(Color.red);
                    int w = bi.getWidth();
                    int h = bi.getHeight();
                    //TODO: Gurvan, Maybe we need to have the list of masks in the report?
                    Mask mask = model3.getCouplesComparaison().get(i).getMaskSum();
                    //g2d.drawRect(0, 0, mask.getWidth()*2*sampleWidth, mask.getHeight()*2*sampleHeight);
                    for (int x = 0; x < mask.getWidth(); x++) {

                        for (int y = 0; y < mask.getHeight(); y++) {

                            if (mask.getCell(x, y)) {
                                g2d.setColor(Color.blue);
                                ////Logger.getLogger(this.getClass() ).debug("grise");
                                g2d.fillRect(x * 2 * Mask.getCELL_HALF_SIZE(), y * 2 * Mask.getCELL_HALF_SIZE(),
                                        2 * Mask.getCELL_HALF_SIZE(), 2 * Mask.getCELL_HALF_SIZE());
                            }

                            if (!dif.get(x, y)) {
                                g2d.setColor(Color.green);
                                g2d.fillRect(x * 2 * Mask.getCELL_HALF_SIZE(), y * 2 * Mask.getCELL_HALF_SIZE(),
                                        2 * Mask.getCELL_HALF_SIZE(), 2 * Mask.getCELL_HALF_SIZE());
                            }
                        }
                    }
                    testImg = Image.getInstance(bi, null);
                    testImg.scaleToFit(310, 260);
                    testImg.setAlignment(Element.ALIGN_BASELINE);
                    scTable.addCell(testImg);
                    section31.add(Chunk.NEWLINE);
                    section31.add(scTable);
                } catch (BadElementException e) {
                    e.printStackTrace();
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                } catch (DOMException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
            section31.add(new Paragraph("Reference screenshot description : "
                    + eImg.getElementsByTagName("RefDescription").item(0).getTextContent()));
            section31.add(Chunk.NEWLINE);

            section31
                    .add(new Paragraph("Mask : " + eImg.getElementsByTagName("Mask").item(0).getTextContent()));
            section31.add(Chunk.NEWLINE);

            section31.add(new Paragraph(
                    "Comment : " + eImg.getElementsByTagName("Comment").item(0).getTextContent()));
            section31.add(new Paragraph(Chunk.NEXTPAGE));

        }
    }
    try {
        document.add(chapter3);
    } catch (DocumentException e) {
        e.printStackTrace();
    }
    document.newPage();

    // step 5: we close the document
    document.close();
}

From source file:com.prime.location.billing.InvoicedBillingManager.java

/**
 * Print invoice//from  w  ww.j a v a  2  s. co m
 */
public void printInvoice() {
    try { //catch better your exceptions, this is just an example
        FacesContext context = FacesContext.getCurrentInstance();

        Document pdf = new Document(PageSize.A4, 5f, 5f, 75f, 45f);

        String fileName = "PDFFile";

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        PdfWriter writer = PdfWriter.getInstance(pdf, baos);
        TableHeader event = new TableHeader();
        event.setHeader("Header Here");
        writer.setPageEvent(event);

        if (!pdf.isOpen()) {
            pdf.open();
        }

        PdfPCell cell;

        PdfPTable header = new PdfPTable(new float[] { 1, 2, 1 });
        cell = new PdfPCell(new Paragraph("INVOICE",
                FontFactory.getFont(FontFactory.HELVETICA, 16, Font.BOLDITALIC, Color.BLACK)));
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell.setColspan(3);
        cell.setBorder(Rectangle.NO_BORDER);
        header.addCell(cell);
        header.setTotalWidth(527);
        header.setLockedWidth(true);

        cell = new PdfPCell(new Phrase("Agency: " + selectedAgency.getDescription()));
        cell.setColspan(2);
        cell.setBorder(Rectangle.NO_BORDER);
        header.addCell(cell);

        cell = new PdfPCell(new Phrase("Invoice#: " + selectedInvoice.getId()));
        cell.setBorder(Rectangle.NO_BORDER);
        cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
        header.addCell(cell);

        cell = new PdfPCell(
                new Phrase("Date: " + DateUtility.dateTimeFormat(selectedInvoice.getInvoiceDate())));
        cell.setColspan(3);
        cell.setBorder(Rectangle.NO_BORDER);
        cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
        header.addCell(cell);

        pdf.add(header);

        PdfPTable table = new PdfPTable(new float[] { 1, 3, 2, 1 });
        table.setSpacingBefore(15f);

        table.setTotalWidth(527);
        table.setLockedWidth(true);
        //table.setWidths(new int[]{3, 1, 1});

        table.getDefaultCell().setBackgroundColor(Color.LIGHT_GRAY);

        table.addCell("Date");
        table.addCell("Name");
        table.addCell("Service");
        table.addCell("Rate");

        table.getDefaultCell().setBackgroundColor(null);

        cell = new PdfPCell(new Phrase("Total(US$): "));
        cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
        cell.setColspan(3);
        cell.setBackgroundColor(Color.LIGHT_GRAY);
        table.addCell(cell);

        cell = new PdfPCell(new Phrase(new DecimalFormat("###,###.###").format(selectedInvoice.getAmount())));
        cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
        cell.setBackgroundColor(Color.LIGHT_GRAY);
        table.addCell(cell);

        // There are three special rows
        table.setHeaderRows(2);
        // One of them is a footer
        table.setFooterRows(1);
        Font f = FontFactory.getFont(FontFactory.HELVETICA, 10);
        //add remaining
        for (AgencyBilling billing : selectedInvoice.getBillings()) {
            table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_LEFT);
            table.getDefaultCell().setVerticalAlignment(Element.ALIGN_MIDDLE);
            table.getDefaultCell().setIndent(2);
            table.getDefaultCell().setFixedHeight(20);

            table.addCell(new Phrase(DateUtility.dateFormat(billing.getBillingDate()), f));
            table.addCell(new Phrase(billing.getPerson().getName(), f));
            table.addCell(new Phrase(billing.getTariff().getTariffType().getDescription(), f));
            cell = new PdfPCell(new Phrase(new DecimalFormat("###,###.###").format(billing.getRate()), f));
            cell.setHorizontalAlignment(Element.ALIGN_RIGHT);

            table.addCell(cell);

        }

        pdf.add(table);

        writer.getAcroForm().setNeedAppearances(true);

        //document.add(new Phrase(TEXT));
        //Keep modifying your pdf file (add pages and more)
        pdf.close();

        writePDFToResponse(context.getExternalContext(), baos, fileName);

        context.responseComplete();

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

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

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

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

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

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

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

}

From source file:com.qcadoo.mes.costCalculation.print.CostCalculationPdfService.java

License:Open Source License

@Override
protected void buildPdfContent(final Document document, final Entity entity, final Locale locale)
        throws DocumentException {
    String documentTitle = translationService.translate("costCalculation.costCalculationDetails.report.title",
            locale);//from  w  ww.j  a  v  a 2 s .  c o  m
    String documentAuthor = translationService.translate("qcadooReport.commons.generatedBy.label", locale);

    pdfHelper.addDocumentHeader(document, "", documentTitle, documentAuthor, new Date());

    DataDefinition dataDefCostCalculation = dataDefinitionService
            .get(CostCalculationConstants.PLUGIN_IDENTIFIER, CostCalculationConstants.MODEL_COST_CALCULATION);
    Entity costCalculation = dataDefCostCalculation.find("where id = " + entity.getId().toString())
            .uniqueResult();

    PdfPTable leftPanelColumn = addLeftPanelToReport(costCalculation, locale);

    PdfPTable rightPanelColumn = addRightPanelToReport(costCalculation, locale);

    PdfPTable panelTable = pdfHelper.createPanelTable(2);

    panelTable.getDefaultCell().setVerticalAlignment(Element.ALIGN_TOP);
    panelTable.addCell(leftPanelColumn);
    panelTable.addCell(rightPanelColumn);
    panelTable.setSpacingAfter(20);
    panelTable.setSpacingBefore(20);

    panelTable.setTableEvent(null);
    panelTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);

    document.add(panelTable);

    document.add(new Paragraph(
            translationService.translate("costCalculation.costCalculationDetails.report.paragraph", locale),
            FontUtils.getDejavuBold11Dark()));
    PdfPTable materialsTable = addMaterialsTable(costCalculation, locale);
    document.add(materialsTable);

    document.add(Chunk.NEWLINE);
    document.add(new Paragraph(
            translationService.translate("costCalculation.costCalculationDetails.report.paragraph2", locale),
            FontUtils.getDejavuBold11Dark()));

    CalculateOperationCostMode calculateOperationCostMode = CalculateOperationCostMode
            .parseString(costCalculation.getStringField(CostCalculationFields.CALCULATE_OPERATION_COSTS_MODE));

    if (CalculateOperationCostMode.HOURLY.equals(calculateOperationCostMode)) {
        document.add(addHourlyCostsTable(costCalculation, locale));
    } else if (CalculateOperationCostMode.PIECEWORK.equals(calculateOperationCostMode)) {
        document.add(addTableAboutPieceworkCost(costCalculation, locale));
    } else {
        throw new IllegalStateException("Unsupported CalculateOperationCostMode");
    }

    printMaterialAndOperationNorms(document, costCalculation, locale);
}

From source file:com.qcadoo.mes.costCalculation.print.CostCalculationPdfService.java

License:Open Source License

public PdfPTable addLeftPanelToReport(final Entity costCalculation, final Locale locale) {
    PdfPTable leftPanelColumn = pdfHelper.createPanelTable(1);
    leftPanelColumn.getDefaultCell().setVerticalAlignment(Element.ALIGN_TOP);

    Entity order = costCalculation.getBelongsToField(CostCalculationFields.ORDER);
    String calculateOperationCostsMode = costCalculation
            .getStringField(CostCalculationFields.CALCULATE_OPERATION_COSTS_MODE);
    String calculateMaterialCostsMode = costCalculation
            .getStringField(CostCalculationFields.CALCULATE_MATERIAL_COSTS_MODE);

    pdfHelper.addTableCellAsTwoColumnsTable(leftPanelColumn,
            translationService.translate("costCalculation.costCalculation.number.label", locale) + ":",
            costCalculation.getStringField(CostCalculationFields.NUMBER));
    pdfHelper.addTableCellAsTwoColumnsTable(leftPanelColumn,
            translationService.translate("costCalculation.costCalculation.product.label", locale) + ":",
            costCalculation.getBelongsToField(CostCalculationFields.PRODUCT)
                    .getStringField(ProductFields.NAME));
    pdfHelper.addTableCellAsTwoColumnsTable(leftPanelColumn,
            translationService.translate("costCalculation.costCalculation.technology.label", locale) + ":",
            costCalculation.getBelongsToField(CostCalculationFields.TECHNOLOGY)
                    .getStringField(TechnologyFields.NAME));
    pdfHelper.addTableCellAsTwoColumnsTable(leftPanelColumn,
            translationService.translate("costCalculation.costCalculation.quantity.label", locale) + ":",
            numberService.format(costCalculation.getField(CostCalculationFields.QUANTITY)));
    pdfHelper.addTableCellAsTwoColumnsTable(leftPanelColumn,
            translationService.translate("costCalculation.costCalculation.order.label", locale) + ":",
            order == null ? "" : order.getStringField(OrderFields.NAME));

    leftPanelColumn.addCell(new Phrase(
            translationService.translate(
                    "costCalculation.costCalculationDetails.window.mainTab.form.parameters", locale) + ":",
            FontUtils.getDejavuBold10Dark()));

    if (!CalculateOperationCostMode.PIECEWORK.getStringValue().equals(calculateOperationCostsMode)) {
        pdfHelper.addTableCellAsTwoColumnsTable(leftPanelColumn,
                L_TAB_IN_TEXT + translationService.translate(
                        "costCalculation.costCalculationDetails.report.columnHeader.includeAdditionalTime",
                        locale) + ":",
                costCalculation.getBooleanField(CostCalculationFields.INCLUDE_ADDITIONAL_TIME)
                        ? translationService.translate("qcadooView.true", locale)
                        : translationService.translate("qcadooView.false", locale));

        pdfHelper.addTableCellAsTwoColumnsTable(leftPanelColumn,
                L_TAB_IN_TEXT + translationService.translate("costCalculation.costCalculation.includeTPZ.label",
                        locale) + ":",
                costCalculation.getBooleanField(CostCalculationFields.INCLUDE_TPZ)
                        ? translationService.translate("qcadooView.true", locale)
                        : translationService.translate("qcadooView.false", locale));
    }//w  w w .  j  av a  2s  . c  o m

    Object reportData = calculateMaterialCostsMode;
    pdfHelper.addTableCellAsTwoColumnsTable(leftPanelColumn,
            L_TAB_IN_TEXT + translationService
                    .translate("costCalculation.costCalculation.calculateMaterialCostsMode.label", locale),
            reportData == null ? translationService.translate("qcadooView.form.blankComboBoxValue", locale)
                    : translationService
                            .translate("costCalculation.costCalculation.calculateMaterialCostsMode.value."
                                    + reportData.toString(), locale));

    reportData = calculateOperationCostsMode;
    pdfHelper.addTableCellAsTwoColumnsTable(leftPanelColumn,
            L_TAB_IN_TEXT + translationService
                    .translate("costCalculation.costCalculation.calculateOperationCostsMode.label", locale),
            reportData == null ? translationService.translate("qcadooView.form.blankComboBoxValue", locale)
                    : translationService
                            .translate("costCalculation.costCalculation.calculateOperationCostsMode.value."
                                    + reportData.toString(), locale));

    reportData = costCalculation.getStringField(CostCalculationFields.DESCRIPTION);
    pdfHelper.addTableCellAsTwoColumnsTable(leftPanelColumn, L_TAB_IN_TEXT
            + translationService.translate("costCalculation.costCalculation.description.label", locale) + ":",
            (reportData == null ? "" : reportData));

    return leftPanelColumn;
}

From source file:com.qcadoo.mes.costCalculation.print.CostCalculationPdfService.java

License:Open Source License

public PdfPTable addRightPanelToReport(final Entity costCalculation, final Locale locale) {
    PdfPTable rightPanelColumn = pdfHelper.createPanelTable(1);
    rightPanelColumn.getDefaultCell().setVerticalAlignment(Element.ALIGN_TOP);

    rightPanelColumn.addCell(new Phrase(translationService.translate(
            "costCalculation.costCalculationDetails.window.mainTab.form.technicalProductionCost", locale) + ":",
            FontUtils.getDejavuBold10Dark()));

    Object reportData = costCalculation.getDecimalField(CostCalculationFields.TOTAL_MATERIAL_COSTS);
    pdfHelper.addTableCellAsTwoColumnsTable(rightPanelColumn,
            L_TAB_IN_TEXT + translationService
                    .translate("costCalculation.costCalculation.totalMaterialCosts.label", locale) + ":",
            (reportData == null ? "" : numberService.format(reportData)) + " "
                    + currencyService.getCurrencyAlphabeticCode());

    reportData = costCalculation.getDecimalField(CostCalculationFields.TOTAL_MACHINE_HOURLY_COSTS);
    pdfHelper.addTableCellAsTwoColumnsTable(rightPanelColumn,
            L_TAB_IN_TEXT + translationService
                    .translate("costCalculation.costCalculation.totalMachineHourlyCosts.label", locale) + ":",
            (reportData == null ? "" : numberService.format(reportData)) + " "
                    + currencyService.getCurrencyAlphabeticCode());

    reportData = costCalculation.getDecimalField(CostCalculationFields.TOTAL_LABOR_HOURLY_COSTS);
    pdfHelper.addTableCellAsTwoColumnsTable(rightPanelColumn,
            L_TAB_IN_TEXT + translationService
                    .translate("costCalculation.costCalculation.totalLaborHourlyCosts.label", locale) + ":",
            (reportData == null ? "" : numberService.format(reportData)) + " "
                    + currencyService.getCurrencyAlphabeticCode());

    reportData = costCalculation.getDecimalField(CostCalculationFields.TOTAL_TECHNICAL_PRODUCTION_COSTS);
    pdfHelper.addTableCellAsTwoColumnsTable(rightPanelColumn,
            L_TAB_IN_TEXT/*  w  ww . j a v a 2 s.  co  m*/
                    + translationService.translate(
                            "costCalculation.costCalculation.totalTechnicalProductionCosts.label", locale)
                    + ":",
            (reportData == null ? "" : numberService.format(reportData)) + " "
                    + currencyService.getCurrencyAlphabeticCode());

    rightPanelColumn.addCell(new Phrase(translationService
            .translate("costCalculation.costCalculationDetails.window.mainTab.form.overheads", locale) + ":",
            FontUtils.getDejavuBold10Dark()));

    reportData = costCalculation.getDecimalField(CostCalculationFields.PRODUCTION_COST_MARGIN);
    Object reportData2 = costCalculation.getDecimalField(CostCalculationFields.PRODUCTION_COST_MARGIN_VALUE);
    pdfHelper.addTableCellAsTwoColumnsTable(rightPanelColumn,
            L_TAB_IN_TEXT + translationService
                    .translate("costCalculation.costCalculation.productionCostMargin.label", locale) + ":",
            (reportData == null ? ""
                    : numberService.format(reportData) + (reportData2 == null ? ""
                            : " %\n (" + "= " + reportData2.toString() + " "
                                    + currencyService.getCurrencyAlphabeticCode() + ")")));

    reportData = costCalculation.getDecimalField(CostCalculationFields.MATERIAL_COST_MARGIN);
    reportData2 = costCalculation.getDecimalField(CostCalculationFields.MATERIAL_COST_MARGIN_VALUE);
    pdfHelper.addTableCellAsTwoColumnsTable(rightPanelColumn,
            L_TAB_IN_TEXT + translationService
                    .translate("costCalculation.costCalculation.materialCostMargin.label", locale) + ":",
            (reportData == null ? ""
                    : numberService.format(reportData) + (reportData2 == null ? ""
                            : " %\n (" + "= " + reportData2.toString() + " "
                                    + currencyService.getCurrencyAlphabeticCode() + ")")));

    reportData = costCalculation.getDecimalField(CostCalculationFields.ADDITIONAL_OVERHEAD);
    pdfHelper.addTableCellAsTwoColumnsTable(rightPanelColumn,
            L_TAB_IN_TEXT + translationService
                    .translate("costCalculation.costCalculation.additionalOverhead.label", locale) + ":",
            (reportData == null ? "" : numberService.format(reportData)) + " "
                    + currencyService.getCurrencyAlphabeticCode());

    reportData = costCalculation.getDecimalField(CostCalculationFields.TOTAL_COSTS);
    rightPanelColumn.addCell(new Phrase(translationService
            .translate("costCalculation.costCalculationDetails.window.mainTab.form.totalCost", locale) + ":",
            FontUtils.getDejavuBold10Dark()));

    pdfHelper.addTableCellAsTable(rightPanelColumn, L_TAB_IN_TEXT
            + translationService.translate("costCalculation.costCalculation.totalCosts.label", locale) + ":",
            (reportData == null ? "" : numberService.format(reportData)) + " "
                    + currencyService.getCurrencyAlphabeticCode(),
            FontUtils.getDejavuBold10Dark(), FontUtils.getDejavuRegular10Dark(), 2);

    reportData = costCalculation.getDecimalField(CostCalculationFields.TOTAL_COST_PER_UNIT);
    pdfHelper.addTableCellAsTable(rightPanelColumn,
            L_TAB_IN_TEXT + translationService
                    .translate("costCalculation.costCalculation.totalCostPerUnit.label", locale) + ":",
            (reportData == null ? "" : numberService.format(reportData)) + " "
                    + currencyService.getCurrencyAlphabeticCode(),
            FontUtils.getDejavuBold10Dark(), FontUtils.getDejavuRegular10Dark(), 2);

    return rightPanelColumn;
}