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

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

Introduction

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

Prototype

public void setWidthPercentage(float widthPercentage) 

Source Link

Document

Sets the width percentage that the table will occupy in the page.

Usage

From source file:mitm.common.pdf.MessagePDFBuilder.java

License:Open Source License

public void buildPDF(MimeMessage message, String replyURL, OutputStream pdfStream)
        throws DocumentException, MessagingException, IOException {
    Document document = createDocument();

    PdfWriter pdfWriter = createPdfWriter(document, pdfStream);

    document.open();//from www.j  a  v a  2 s. c o  m

    String[] froms = null;

    try {
        froms = EmailAddressUtils.addressesToStrings(message.getFrom(), true /* mime decode */);
    } catch (MessagingException e) {
        logger.warn("From address is not a valid email address.");
    }

    if (froms != null) {
        for (String from : froms) {
            document.addAuthor(from);
        }
    }

    String subject = null;

    try {
        subject = message.getSubject();
    } catch (MessagingException e) {
        logger.error("Error getting subject.", e);
    }

    if (subject != null) {
        document.addSubject(subject);
        document.addTitle(subject);
    }

    String[] tos = null;

    try {
        tos = EmailAddressUtils.addressesToStrings(message.getRecipients(RecipientType.TO),
                true /* mime decode */);
    } catch (MessagingException e) {
        logger.warn("To is not a valid email address.");
    }

    String[] ccs = null;

    try {
        ccs = EmailAddressUtils.addressesToStrings(message.getRecipients(RecipientType.CC),
                true /* mime decode */);
    } catch (MessagingException e) {
        logger.warn("CC is not a valid email address.");
    }

    Date sentDate = null;

    try {
        sentDate = message.getSentDate();
    } catch (MessagingException e) {
        logger.error("Error getting sent date.", e);
    }

    Collection<Part> attachments = new LinkedList<Part>();

    String body = BodyPartUtils.getPlainBodyAndAttachments(message, attachments);

    attachments = preprocessAttachments(attachments);

    if (body == null) {
        body = MISSING_BODY;
    }

    /*
     * PDF does not have tab support so we convert tabs to spaces
     */
    body = StringReplaceUtils.replaceTabsWithSpaces(body, tabWidth);

    PdfPTable headerTable = new PdfPTable(2);

    headerTable.setHorizontalAlignment(Element.ALIGN_LEFT);
    headerTable.setWidthPercentage(100);
    headerTable.setWidths(new int[] { 1, 6 });
    headerTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);

    Font headerFont = createHeaderFont();

    FontSelector headerFontSelector = createHeaderFontSelector();

    PdfPCell cell = new PdfPCell(new Paragraph("From:", headerFont));
    cell.setBorder(Rectangle.NO_BORDER);
    cell.setHorizontalAlignment(Element.ALIGN_RIGHT);

    headerTable.addCell(cell);

    String decodedFroms = StringUtils.defaultString(StringUtils.join(froms, ", "));

    headerTable.addCell(headerFontSelector.process(decodedFroms));

    cell = new PdfPCell(new Paragraph("To:", headerFont));
    cell.setBorder(Rectangle.NO_BORDER);
    cell.setHorizontalAlignment(Element.ALIGN_RIGHT);

    headerTable.addCell(cell);
    headerTable.addCell(headerFontSelector.process(StringUtils.defaultString(StringUtils.join(tos, ", "))));

    cell = new PdfPCell(new Paragraph("CC:", headerFont));
    cell.setBorder(Rectangle.NO_BORDER);
    cell.setHorizontalAlignment(Element.ALIGN_RIGHT);

    headerTable.addCell(cell);
    headerTable.addCell(headerFontSelector.process(StringUtils.defaultString(StringUtils.join(ccs, ", "))));

    cell = new PdfPCell(new Paragraph("Subject:", headerFont));
    cell.setBorder(Rectangle.NO_BORDER);
    cell.setHorizontalAlignment(Element.ALIGN_RIGHT);

    headerTable.addCell(cell);
    headerTable.addCell(headerFontSelector.process(StringUtils.defaultString(subject)));

    cell = new PdfPCell(new Paragraph("Date:", headerFont));
    cell.setBorder(Rectangle.NO_BORDER);
    cell.setHorizontalAlignment(Element.ALIGN_RIGHT);

    headerTable.addCell(cell);
    headerTable.addCell(ObjectUtils.toString(sentDate));

    cell = new PdfPCell(new Paragraph("Attachments:", headerFont));
    cell.setBorder(Rectangle.NO_BORDER);
    cell.setHorizontalAlignment(Element.ALIGN_RIGHT);

    headerTable.addCell(cell);
    headerTable
            .addCell(headerFontSelector.process(StringUtils.defaultString(getAttachmentHeader(attachments))));

    document.add(headerTable);

    if (replyURL != null) {
        addReplyLink(document, replyURL);
    }

    /*
     * Body table will contain the body of the message
     */
    PdfPTable bodyTable = new PdfPTable(1);
    bodyTable.setWidthPercentage(100f);

    bodyTable.setSplitLate(false);

    bodyTable.setSpacingBefore(15f);
    bodyTable.setHorizontalAlignment(Element.ALIGN_LEFT);

    addBodyAndAttachments(pdfWriter, document, bodyTable, body, attachments);

    Phrase footer = new Phrase(FOOTER_TEXT);

    PdfContentByte cb = pdfWriter.getDirectContent();

    ColumnText.showTextAligned(cb, Element.ALIGN_RIGHT, footer, document.right(), document.bottom(), 0);

    document.close();
}

From source file:net.algem.contact.TeacherCtrl.java

License:Open Source License

private File getFollowUpAsPDF(String userId, String from, String to)
        throws IOException, BadElementException, DocumentException {
    String path = "/tmp/" + "suivi-" + userId + ".pdf";
    File f = new File(path);
    LOGGER.log(Level.INFO, f.getName());
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    Document document = new Document(PageSize.A4.rotate());
    PdfWriter.getInstance(document, byteArrayOutputStream); // Do this BEFORE document.open()
    document.open();//ww w .  j av a  2 s  .  co  m

    PdfPTable table = new PdfPTable(10);
    table.setWidthPercentage(100);
    table.setWidths(new float[] { 1.1f, 1.2f, 0.6f, 1.5f, 1.5f, 2f, 0.5f, 0.5f, 1.9f, 1.9f });

    BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.WINANSI, false);
    BaseFont bfb = BaseFont.createFont(BaseFont.HELVETICA_BOLD, BaseFont.WINANSI, false);
    Font normalFont = new Font(bf, 10);
    Font boldFont = new Font(bfb, 10);

    String fromLabel = messageSource.getMessage("from.label", null, CTX_LOCALE);
    String toLabel = messageSource.getMessage("to.label", null, CTX_LOCALE);
    String prefix = messageSource.getMessage("follow-up.label", null, CTX_LOCALE) + " "
            + organization.get("name.label");
    String period = fromLabel.toLowerCase() + " " + from + " " + toLabel.toLowerCase() + " " + to;
    PdfPCell headerCell = new PdfPCell(new Phrase(prefix + " " + period, boldFont));

    headerCell.setBackgroundColor(Color.LIGHT_GRAY);
    headerCell.setColspan(10);
    table.addCell(headerCell);

    table.addCell(new PdfPCell(new Phrase(messageSource.getMessage("date.label", null, CTX_LOCALE), boldFont)));
    table.addCell(new PdfPCell(new Phrase(messageSource.getMessage("time.label", null, CTX_LOCALE), boldFont)));
    table.addCell(new PdfPCell(
            new Phrase(messageSource.getMessage("time.length.label", null, CTX_LOCALE), boldFont)));
    table.addCell(new PdfPCell(new Phrase(messageSource.getMessage("room.label", null, CTX_LOCALE), boldFont)));
    table.addCell(
            new PdfPCell(new Phrase(messageSource.getMessage("course.label", null, CTX_LOCALE), boldFont)));
    table.addCell(
            new PdfPCell(new Phrase(messageSource.getMessage("student.label", null, CTX_LOCALE), boldFont)));
    String abs = messageSource.getMessage("absence.label", null, CTX_LOCALE);
    table.addCell(new PdfPCell(new Phrase(abs != null ? abs.substring(0, 3) + "." : "", boldFont)));
    table.addCell(
            new PdfPCell(new Phrase(messageSource.getMessage("score.label", null, CTX_LOCALE), boldFont)));
    table.addCell(new PdfPCell(
            new Phrase(messageSource.getMessage("individual.logbook.label", null, CTX_LOCALE), boldFont)));
    table.addCell(new PdfPCell(
            new Phrase(messageSource.getMessage("collective.comment.label", null, CTX_LOCALE), boldFont)));

    List<ScheduleElement> items = getFollowUpSchedules(userId, from, to);
    //LOGGER.log(Level.INFO, items.toString());
    for (ScheduleElement e : items) {
        List<ScheduleRangeElement> ranges = new ArrayList<ScheduleRangeElement>(
                (Collection<? extends ScheduleRangeElement>) e.getRanges());

        for (ScheduleRangeElement r : ranges) {
            String status = CommonDao.getAbsenceFromNumberStatus(r.getFollowUp().getStatus());
            String note = r.getFollowUp().getNote();
            String content1 = r.getFollowUp().getContent();
            String content2 = e.getFollowUp().getContent();
            table.addCell(new Phrase(e.getDateFr().toString(), normalFont));
            table.addCell(new Phrase(r.getStart() + "-" + r.getEnd(), normalFont));
            table.addCell(new Phrase(new Hour(r.getLength()).toString(), normalFont));
            table.addCell(new Phrase(e.getDetail().get("room").getName(), normalFont));
            table.addCell(new Phrase(e.getDetail().get("course").getName(), normalFont));
            table.addCell(new Phrase(r.getPerson().getFirstName() + " " + r.getPerson().getName(), normalFont));
            table.addCell(new Phrase(status, normalFont));
            table.addCell(new Phrase(note == null ? "" : note, normalFont));
            table.addCell(new Phrase(content1 == null ? "" : content1.replaceAll("[\r\n]", " "), normalFont));
            table.addCell(new Phrase(content2 == null ? "" : content2.replaceAll("[\r\n]", " "), normalFont));
        }
    }

    document.add(table);
    document.close();
    byte[] pdfBytes = byteArrayOutputStream.toByteArray();
    Files.write(Paths.get(path), pdfBytes);
    return f;
}

From source file:net.algem.security.UserCtrl.java

License:Open Source License

private File getFollowUpAsPDF(String userId, String from, String to)
        throws IOException, BadElementException, DocumentException {
    String path = "/tmp/" + "suivi-" + userId + ".pdf";
    File f = new File(path);
    LOGGER.log(Level.INFO, f.getName());
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    Document document = new Document(PageSize.A4.rotate());
    PdfWriter.getInstance(document, byteArrayOutputStream); // Do this BEFORE document.open()
    document.open();//  w w w.j a va  2  s . c o m

    PdfPTable table = new PdfPTable(10);
    table.setWidthPercentage(100);
    table.setWidths(new float[] { 1.1f, 1.2f, 0.6f, 1.5f, 1.5f, 2f, 0.5f, 0.5f, 1.9f, 1.9f });

    BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.WINANSI, false);
    BaseFont bfb = BaseFont.createFont(BaseFont.HELVETICA_BOLD, BaseFont.WINANSI, false);
    Font normalFont = new Font(bf, 10);
    Font boldFont = new Font(bfb, 10);

    String fromLabel = messageSource.getMessage("from.label", null, CTX_LOCALE);
    String toLabel = messageSource.getMessage("to.label", null, CTX_LOCALE);
    String prefix = messageSource.getMessage("follow-up.label", null, CTX_LOCALE) + " "
            + organization.get("name.label");
    String period = fromLabel.toLowerCase() + " " + from + " " + toLabel.toLowerCase() + " " + to;
    PdfPCell headerCell = new PdfPCell(new Phrase(prefix + " " + period, boldFont));

    headerCell.setBackgroundColor(Color.LIGHT_GRAY);
    headerCell.setColspan(10);
    table.addCell(headerCell);

    table.addCell(new PdfPCell(new Phrase(messageSource.getMessage("date.label", null, CTX_LOCALE), boldFont)));
    table.addCell(new PdfPCell(new Phrase(messageSource.getMessage("time.label", null, CTX_LOCALE), boldFont)));
    table.addCell(new PdfPCell(
            new Phrase(messageSource.getMessage("time.length.label", null, CTX_LOCALE), boldFont)));
    table.addCell(new PdfPCell(new Phrase(messageSource.getMessage("room.label", null, CTX_LOCALE), boldFont)));
    table.addCell(
            new PdfPCell(new Phrase(messageSource.getMessage("course.label", null, CTX_LOCALE), boldFont)));
    table.addCell(
            new PdfPCell(new Phrase(messageSource.getMessage("teacher.label", null, CTX_LOCALE), boldFont)));
    String abs = messageSource.getMessage("absence.label", null, CTX_LOCALE);
    table.addCell(new PdfPCell(new Phrase(abs != null ? abs.substring(0, 3) + "." : "", boldFont)));
    table.addCell(
            new PdfPCell(new Phrase(messageSource.getMessage("score.label", null, CTX_LOCALE), boldFont)));
    table.addCell(new PdfPCell(
            new Phrase(messageSource.getMessage("individual.logbook.label", null, CTX_LOCALE), boldFont)));
    table.addCell(new PdfPCell(
            new Phrase(messageSource.getMessage("collective.comment.label", null, CTX_LOCALE), boldFont)));

    fillPdfTable(table, getFollowUpSchedules(userId, from, to), normalFont);

    document.add(table);
    document.close();
    byte[] pdfBytes = byteArrayOutputStream.toByteArray();
    Files.write(Paths.get(path), pdfBytes);
    return f;
}

From source file:net.bull.javamelody.internal.web.pdf.PdfAbstractTableReport.java

License:Apache License

void initTable(List<String> headers, int[] relativeWidths) throws DocumentException {
    assert headers.size() == relativeWidths.length;
    final PdfPTable mytable = new PdfPTable(headers.size());
    mytable.setWidthPercentage(100);
    mytable.setWidths(relativeWidths);/*  w  w w.  j  ava 2s  .  co m*/
    mytable.setHeaderRows(1);
    final PdfPCell defaultCell = mytable.getDefaultCell();
    defaultCell.setGrayFill(0.9f);
    defaultCell.setHorizontalAlignment(Element.ALIGN_CENTER);
    defaultCell.setPaddingLeft(0);
    defaultCell.setPaddingRight(0);
    final Font tableHeaderFont = PdfFonts.TABLE_HEADER.getFont();
    for (final String header : headers) {
        mytable.addCell(new Phrase(header, tableHeaderFont));
    }
    defaultCell.setPaddingLeft(2);
    defaultCell.setPaddingRight(2);
    this.table = mytable;
}

From source file:net.bull.javamelody.internal.web.pdf.PdfCoreReport.java

License:Apache License

private void writeGraphDetails() throws IOException, DocumentException {
    if (collector.isStopped()) {
        return;// w  w w .j  av  a 2  s  .c  o  m
    }
    final PdfPTable jrobinTable = new PdfPTable(1);
    jrobinTable.setHorizontalAlignment(Element.ALIGN_CENTER);
    jrobinTable.setWidthPercentage(100);
    jrobinTable.getDefaultCell().setBorder(0);
    if (largeGraphs != null) {
        // si les graphiques ont t prinitialiss (en Swing) alors on les utilise
        for (final byte[] imageData : largeGraphs.values()) {
            final Image image = Image.getInstance(imageData);
            jrobinTable.addCell(image);
        }
    } else {
        final Collection<JRobin> counterJRobins = collector.getDisplayedCounterJRobins();
        if (counterJRobins.isEmpty()) {
            return;
        }
        for (final JRobin jrobin : counterJRobins) {
            // la hauteur de l'image est prvue pour qu'il n'y ait pas de graph seul sur une page
            final Image image = Image.getInstance(jrobin.graph(range, LARGE_GRAPH_WIDTH, LARGE_GRAPH_HEIGHT));
            jrobinTable.addCell(image);
        }
    }
    newPage();
    addToDocument(jrobinTable);
    newPage();
}

From source file:net.bull.javamelody.internal.web.pdf.PdfJavaInformationsReport.java

License:Apache License

private static PdfPTable createJavaInformationsTable() throws DocumentException {
    final PdfPTable table = new PdfPTable(2);
    table.setHorizontalAlignment(Element.ALIGN_LEFT);
    table.setWidthPercentage(100);
    table.setWidths(new int[] { 2, 8 });
    table.getDefaultCell().setBorder(0);
    return table;
}

From source file:net.bull.javamelody.internal.web.pdf.PdfMBeansReport.java

License:Apache License

private static PdfPTable createAttributesTable() {
    final PdfPTable table = new PdfPTable(3);
    table.setWidthPercentage(100);
    final PdfPCell defaultCell = table.getDefaultCell();
    defaultCell.setPaddingLeft(2);//from  w ww  .  j av  a  2 s .  c o  m
    defaultCell.setPaddingRight(2);
    defaultCell.setVerticalAlignment(Element.ALIGN_TOP);
    defaultCell.setBorder(0);
    return table;
}

From source file:net.bull.javamelody.internal.web.pdf.PdfRequestAndGraphDetailReport.java

License:Apache License

private void writeRequestRumData() throws DocumentException {
    final CounterRequestRumData rumData = request.getRumData();
    final DecimalFormat percentFormat = I18N.createPercentFormat();
    final int networkTimeMean = rumData.getNetworkTimeMean();
    final int serverMean = request.getMean();
    final int domProcessingMean = rumData.getDomProcessingMean();
    final int pageRenderingMean = rumData.getPageRenderingMean();
    final int totalTime = networkTimeMean + serverMean + domProcessingMean + pageRenderingMean;
    final double networkPercent = 100d * networkTimeMean / totalTime;
    final double serverPercent = 100d * serverMean / totalTime;
    final double domProcessingPercent = 100d * domProcessingMean / totalTime;
    final double pageRenderingPercent = 100d * pageRenderingMean / totalTime;

    final PdfPTable table = new PdfPTable(2);
    table.setHorizontalAlignment(Element.ALIGN_LEFT);
    table.setWidthPercentage(25);
    table.getDefaultCell().setBorderWidth(0);
    table.addCell(new Phrase(I18N.getString("Network"), cellFont));
    table.addCell(new Phrase(
            integerFormat.format(networkTimeMean) + " ms (" + percentFormat.format(networkPercent) + "%)",
            cellFont));/* w  ww  .  j  a va  2  s  .com*/
    table.addCell(new Phrase(I18N.getString("Server"), cellFont));
    table.addCell(new Phrase(
            integerFormat.format(serverMean) + " ms (" + percentFormat.format(serverPercent) + "%)", cellFont));
    table.addCell(new Phrase(I18N.getString("DOM_processing"), cellFont));
    table.addCell(new Phrase(integerFormat.format(domProcessingMean) + " ms ("
            + percentFormat.format(domProcessingPercent) + "%)", cellFont));
    table.addCell(new Phrase(I18N.getString("Page_rendering"), cellFont));
    table.addCell(new Phrase(integerFormat.format(pageRenderingMean) + " ms ("
            + percentFormat.format(pageRenderingPercent) + "%)", cellFont));
    addToDocument(table);
    addToDocument(new Phrase("\n", cellFont));
}

From source file:net.bull.javamelody.internal.web.pdf.PdfRequestAndGraphDetailReport.java

License:Apache License

private void writeGraph() throws IOException, DocumentException {
    final JRobin jrobin = collector.getJRobin(graphName);
    if (jrobin != null) {
        final byte[] img = jrobin.graph(range, 960, 400);
        final Image image = Image.getInstance(img);
        image.scalePercent(50);/*from  w  w  w. j a va  2 s .  c om*/

        final PdfPTable table = new PdfPTable(1);
        table.setHorizontalAlignment(Element.ALIGN_CENTER);
        table.setWidthPercentage(100);
        table.getDefaultCell().setBorder(0);
        table.addCell("\n");
        table.addCell(image);
        table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_RIGHT);
        table.addCell(new Phrase(getString("graph_units"), cellFont));
        addToDocument(table);
    } else {
        // just in case request is null and collector.getJRobin(graphName) is null, we must write something in the document
        addToDocument(new Phrase("\n", cellFont));
    }
}

From source file:net.bull.javamelody.internal.web.pdf.PdfRuntimeDependenciesReport.java

License:Apache License

private void writeHeader() throws DocumentException {
    final List<String> headers = new ArrayList<String>();
    headers.add("Beans");
    headers.addAll(calledBeans);// w  w  w.  ja va2 s  .  com
    final int[] relativeWidths = new int[headers.size()];
    Arrays.fill(relativeWidths, 0, headers.size(), 1);
    relativeWidths[0] = 4;

    final PdfPTable table = new PdfPTable(headers.size());
    table.setWidthPercentage(100);
    table.setWidths(relativeWidths);
    table.setHeaderRows(1);
    final PdfPCell defaultCell = table.getDefaultCell();
    defaultCell.setGrayFill(0.9f);
    defaultCell.setHorizontalAlignment(Element.ALIGN_CENTER);
    defaultCell.setVerticalAlignment(Element.ALIGN_MIDDLE);
    defaultCell.setPaddingLeft(0);
    defaultCell.setPaddingRight(0);
    for (final String header : headers) {
        table.addCell(new Phrase(header, boldCellFont));
        // pas la premire entte de colonne
        defaultCell.setRotation(90);
    }
    defaultCell.setRotation(0);
    defaultCell.setPaddingLeft(2);
    defaultCell.setPaddingRight(2);
    currentTable = table;
}