Example usage for com.lowagie.text Phrase Phrase

List of usage examples for com.lowagie.text Phrase Phrase

Introduction

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

Prototype

public Phrase(float leading, String string) 

Source Link

Document

Constructs a Phrase with a certain leading and a certain String.

Usage

From source file:corner.orm.tapestry.pdf.service.PdfResponseBuilder.java

License:Apache License

public void renderResponse(IRequestCycle cycle) throws IOException {
    // ??/*from   ww  w .  j av  a2 s  .  c  om*/
    IPage pdfPage = cycle.getPage();
    // PDF.
    OutputStream os = response.getOutputStream(IPdfPage.CONTENT_TYPE);
    // PDF
    _doc = new Document();

    // PDF Writer
    PdfWriter pdfWriter = null;
    try {

        // PDF writer.
        pdfWriter = PdfWriter.getInstance(_doc, os);

        if (pdfPage instanceof IPdfPage) { // PDF Page?.
            // ?
            PdfOutputPageEvent event = new PdfOutputPageEvent((IPdfPage) pdfPage);
            pdfWriter.setPageEvent(event);
            // Pdf writer?.
            _writer = new PdfWriterDelegate(pdfWriter);
            // pdf
            _doc.open();

            // PDF Writer??.
            cycle.setAttribute(PDF_DOCUMENT_ATTRIBUTE_NAME, _doc);

            // PDF?
            cycle.renderPage(this);

            // PDF??.
            cycle.removeAttribute(PDF_DOCUMENT_ATTRIBUTE_NAME);

            // PDF.
            _doc.close();

        } else if (pdfPage instanceof org.apache.tapestry.pages.Exception) { // ??.

            ExceptionDescription[] exceptions = (ExceptionDescription[]) PropertyUtils.read(pdfPage,
                    "exceptions");
            if (exceptions == null) {
                throw new ApplicationRuntimeException("UNKOWN Exception!");

            } else { // ???.
                StringBuffer sb = new StringBuffer();
                for (int i = 0; i < exceptions.length; i++) {
                    sb.append(exceptions[i].getMessage()).append("\n");
                    ExceptionProperty[] pros = exceptions[i].getProperties();
                    for (ExceptionProperty pro : pros) {
                        sb.append(pro.getName()).append(" ").append(pro.getValue()).append("\n");
                    }
                    String[] traces = exceptions[i].getStackTrace();
                    if (traces == null) {
                        continue;
                    }
                    for (int j = 0; j < traces.length; j++) {
                        sb.append(traces[j]).append("\n");
                    }
                }
                throw new Exception(sb.toString());
            }
        }
    } catch (Throwable e) { // ?.
        if (pdfWriter == null) {
            e.printStackTrace();
            return;
        }
        if (!_doc.isOpen()) {
            _doc.open();
        }
        pdfWriter.setPageEvent(null);

        _doc.newPage();

        // PDF???SO COOL! :)
        try {
            _doc.add(new Phrase("pdf?:", PdfUtils.createSongLightFont(12)));
            _doc.add(new Paragraph(e.getMessage()));
            _doc.add(new Paragraph(fetchStackTrace(e)));
            _doc.close();
        } catch (DocumentException e1) {
            throw new ApplicationRuntimeException(e1);
        }

    }
}

From source file:CPS.Core.TODOLists.PDFExporter.java

License:Open Source License

private Document prepareDocument(String filename, final String title, final String author, final String creator,
        final Rectangle pageSize) {

    System.out.println("DEBUG(PDFExporter): Creating document: " + filename);

    Document d = new Document();

    d.setPageSize(pageSize);//from   w  w w .j  a  va  2s . c om
    // TODO alter page orientation?  maybe useful for seed order worksheet

    d.addTitle(title);
    d.addAuthor(author);
    //        d.addSubject( );
    //        d.addKeywords( );
    d.addCreator(creator);

    // left, right, top, bottom - scale in points (~72 points/inch)
    d.setMargins(35, 35, 35, 44);

    try {
        PdfWriter writer = PdfWriter.getInstance(d, new FileOutputStream(filename));
        // add header and footer
        writer.setPageEvent(new PdfPageEventHelper() {
            public void onEndPage(PdfWriter writer, Document document) {
                try {
                    Rectangle page = document.getPageSize();

                    PdfPTable head = new PdfPTable(3);
                    head.getDefaultCell().setBorderWidth(0);
                    head.getDefaultCell().setHorizontalAlignment(PdfPCell.ALIGN_LEFT);
                    head.addCell(new Phrase(author, fontHeadFootItal));

                    head.getDefaultCell().setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
                    head.addCell(new Phrase(title, fontHeadFootReg));

                    head.getDefaultCell().setHorizontalAlignment(PdfPCell.ALIGN_RIGHT);
                    head.addCell("");

                    head.setTotalWidth(page.getWidth() - document.leftMargin() - document.rightMargin());
                    head.writeSelectedRows(0, -1, document.leftMargin(),
                            page.getHeight() - document.topMargin() + head.getTotalHeight(),
                            writer.getDirectContent());

                    PdfPTable foot = new PdfPTable(3);

                    foot.getDefaultCell().setBorderWidth(0);
                    foot.getDefaultCell().setHorizontalAlignment(PdfPCell.ALIGN_LEFT);
                    foot.addCell(new Phrase(creator, fontHeadFootItal));

                    foot.getDefaultCell().setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
                    foot.addCell("");

                    foot.getDefaultCell().setHorizontalAlignment(PdfPCell.ALIGN_RIGHT);
                    foot.addCell(new Phrase("Page " + document.getPageNumber(), fontHeadFootReg));

                    foot.setTotalWidth(page.getWidth() - document.leftMargin() - document.rightMargin());
                    foot.writeSelectedRows(0, -1, document.leftMargin(), document.bottomMargin(),
                            writer.getDirectContent());
                } catch (Exception e) {
                    throw new ExceptionConverter(e);
                }
            }
        });
    } catch (Exception e) {
        e.printStackTrace();
    }

    return d;
}

From source file:CPS.Core.TODOLists.PDFExporter.java

License:Open Source License

/**
 * @param args the command line arguments
 *//*from  w w w  .j a  v a 2s.  co m*/
public PdfPTable convertJTable(JTable jtable) {

    boolean tableIncludesNotes = false;
    boolean rowHasNotes = false;
    String notesValue = "";
    int notesIndex = -1;

    // find Notes column (if there is one)
    for (int col = 0; col < jtable.getColumnCount(); col++) {
        String headName;
        if (jtable instanceof CPSTable)
            headName = jtable.getColumnModel().getColumn(col).getHeaderValue().toString();
        else
            headName = jtable.getColumnName(col);
        if (headName.equalsIgnoreCase("Planting Notes")) {
            tableIncludesNotes = true;
            notesIndex = col;
        }
    }

    int colCount = (tableIncludesNotes) ? jtable.getColumnCount() - 1 : jtable.getColumnCount();
    PdfPTable table = new PdfPTable(colCount);

    // create header row
    for (int col = 0; col < jtable.getColumnCount(); col++) {
        String headName;
        if (jtable instanceof CPSTable)
            headName = jtable.getColumnModel().getColumn(col).getHeaderValue().toString();
        else
            headName = jtable.getColumnName(col);
        if (!tableIncludesNotes || col != notesIndex) {
            HeadCell hc = new HeadCell(headName);

            if (jtable.getColumnClass(col).equals(Boolean.TRUE.getClass())
                    || jtable.getColumnClass(col).equals(new Integer(0).getClass())
                    || jtable.getColumnClass(col).equals(new Double(0).getClass())
                    || jtable.getColumnClass(col).equals(new Float(0).getClass())) {
                hc.setRotation(90);
                hc.setFixedHeight(60f);
            }

            table.addCell(hc);
        }
    }
    table.setHeaderRows(1);

    // now fill in the rest of the table
    for (int row = 0; row < jtable.getRowCount(); row++) {
        rowHasNotes = false;

        for (int col = 0; col < jtable.getColumnCount(); col++) {
            Object o = jtable.getValueAt(row, col);

            if (o == null) {
                if (!tableIncludesNotes || col != notesIndex)
                    table.addCell(new RegCell(""));
            }

            else if (o instanceof Date)
                table.addCell(new RegCell(
                        CPSDateValidator.format((Date) o, CPSDateValidator.DATE_FORMAT_SHORT_DAY_OF_WEEK)));

            else if (o instanceof Boolean)
                if (((Boolean) o).booleanValue())
                    table.addCell(new CenterCell("X"));
                else
                    table.addCell(new RegCell(""));

            else if (o instanceof Float)
                table.addCell(new RegCell(CPSRecord.formatFloat(((Float) o).floatValue(), 3)));

            else if (o instanceof Double)
                table.addCell(new RegCell(CPSRecord.formatFloat(((Double) o).floatValue(), 3)));

            else {

                if (tableIncludesNotes && col == notesIndex) {
                    if (o == null || o.equals(""))
                        rowHasNotes = false;
                    else {
                        rowHasNotes = true;
                        notesValue = o.toString();
                    }
                } else
                    table.addCell(new RegCell(o.toString()));
            }
        }

        // now deal w/ the Notes data
        if (tableIncludesNotes && rowHasNotes) {
            table.addCell(new NoteHeadCell());
            NoteCell c = new NoteCell(notesValue);
            // reset the font to be smaller
            c.setPhrase(new Phrase(notesValue, fontHeadFootReg));
            c.setColspan(colCount - 1);
            table.addCell(c);
        }
    }

    // set the widths for the columns
    float[] widths = new float[colCount];
    for (int col = 0; col < colCount; col++) {
        if (tableIncludesNotes && col == notesIndex)
            continue;
        else if (jtable.getColumnClass(col).equals(new Boolean(true).getClass()))
            widths[col] = 2.25f;
        else if (jtable.getColumnClass(col).equals(new Integer(0).getClass())
                || jtable.getColumnClass(col).equals(new Double(0).getClass())
                || jtable.getColumnClass(col).equals(new Float(0).getClass()))
            widths[col] = 5f;
        else // String, Date, etc
            widths[col] = 10f;
    }

    try {
        table.setWidths(widths);
    } catch (Exception e) {
        e.printStackTrace();
    }

    return table;
}

From source file:de.dhbw.humbuch.util.PDFHandler.java

/**
 * Use the configuration information to fill the table cells
 * @param tableBuilder Table configuration
 *//*from  ww  w.  ja  va2s.  c o  m*/
private static void fillTableWithContent(TableBuilder tableBuilder) {
    PdfPCell cell = null;
    for (int i = 0; i < tableBuilder.contentArray.length; i++) {
        if (tableBuilder.contentArray[i] == null || tableBuilder.contentArray[i].equals("null")) {
            tableBuilder.contentArray[i] = "";
        }
        if (tableBuilder.font != null) {
            cell = new PdfPCell(new Phrase(tableBuilder.contentArray[i], tableBuilder.font));
        } else {
            cell = new PdfPCell(new Phrase(tableBuilder.contentArray[i]));
        }
        if (tableBuilder.isAlignedCentrally) {
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        }
        if (!tableBuilder.withBorder) {
            cell.setBorder(0);
        }
        if (tableBuilder.padding != 0f) {
            cell.setPadding(tableBuilder.padding);
        }
        if (tableBuilder.leading != 0f) {
            cell.setLeading(tableBuilder.leading, tableBuilder.leading);
        }
        tableBuilder.table.addCell(cell);
    }
}

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

License:Open Source License

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

    CreateSubscriberListForm myForm = (CreateSubscriberListForm) form;
    boolean bSortByName;

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

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

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

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

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

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

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

    }

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

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

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

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

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

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

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

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

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

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

    cols = alWidth.size();

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        document.add(table);

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

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

From source file:domain.reports.menu.PDFReportMenu.java

License:LGPL

/**
 * Return a report section formatted as a table
 * @param data/* w  w  w  .ja va  2  s  .c  o m*/
 * @return
 */
PdfPTable getGroupDetail(Recordset master, Recordset detail) throws Throwable {

    //cols
    PdfPTable datatable = new PdfPTable(2);

    //header
    datatable.getDefaultCell().setPadding(1);
    int headerwidths[] = { 50, 50 }; // percentage
    datatable.setWidths(headerwidths);
    datatable.setWidthPercentage(70); // percentage
    datatable.setHorizontalAlignment(Element.ALIGN_CENTER);
    datatable.getDefaultCell().setBorderWidth(1);
    datatable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);

    PdfPCell c = null;
    String v = "";

    //encabezados de columnas
    c = new PdfPCell(new Phrase("ITEMS DEL MEN", tblHeaderFont));
    c.setGrayFill(0.95f);
    c.setColspan(2);
    c.setHorizontalAlignment(Element.ALIGN_CENTER);
    datatable.addCell(c);

    c = new PdfPCell(new Phrase("Item del men", tblHeaderFont));
    c.setGrayFill(0.95f);
    c.setHorizontalAlignment(Element.ALIGN_CENTER);
    datatable.addCell(c);

    c = new PdfPCell(new Phrase("Servicio", tblHeaderFont));
    c.setGrayFill(0.95f);
    c.setHorizontalAlignment(Element.ALIGN_CENTER);
    datatable.addCell(c);

    while (detail.next()) {
        v = detail.getString("description");
        c = new PdfPCell(new Phrase(v, tblBodyFont));
        c.setHorizontalAlignment(Element.ALIGN_LEFT);
        datatable.addCell(c);

        v = detail.getString("path");
        c = new PdfPCell(new Phrase(v, tblBodyFont));
        c.setHorizontalAlignment(Element.ALIGN_LEFT);
        datatable.addCell(c);
    }

    datatable.setSpacingBefore(20);
    return datatable;

}

From source file:domain.reports.role.PDFReportRole.java

License:LGPL

/**
 * Return a report section formatted as a table
 * @param data//w  w  w .  j  av  a2  s.c o  m
 * @return
 */
PdfPTable getGroupDetail(Recordset master, Recordset detail) throws Throwable {

    //cols
    PdfPTable datatable = new PdfPTable(4);

    //header
    datatable.getDefaultCell().setPadding(1);
    int headerwidths[] = { 20, 20, 20, 20 }; // percentage
    datatable.setWidths(headerwidths);
    datatable.setWidthPercentage(100); // percentage
    datatable.setHorizontalAlignment(Element.ALIGN_CENTER);
    datatable.getDefaultCell().setBorderWidth(1);
    datatable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);

    PdfPCell c = null;
    String v = "";

    //encabezados de columnas
    c = new PdfPCell(new Phrase("USUARIOS DEL ROL", tblHeaderFont));
    c.setGrayFill(0.95f);
    c.setColspan(4);
    c.setHorizontalAlignment(Element.ALIGN_CENTER);
    datatable.addCell(c);

    c = new PdfPCell(new Phrase("Login de Usuario", tblHeaderFont));
    c.setGrayFill(0.95f);
    c.setHorizontalAlignment(Element.ALIGN_CENTER);
    datatable.addCell(c);

    c = new PdfPCell(new Phrase("Apellido", tblHeaderFont));
    c.setGrayFill(0.95f);
    c.setHorizontalAlignment(Element.ALIGN_CENTER);
    datatable.addCell(c);

    c = new PdfPCell(new Phrase("Nombre", tblHeaderFont));
    c.setGrayFill(0.95f);
    c.setHorizontalAlignment(Element.ALIGN_CENTER);
    datatable.addCell(c);

    c = new PdfPCell(new Phrase("Email", tblHeaderFont));
    c.setGrayFill(0.95f);
    c.setHorizontalAlignment(Element.ALIGN_CENTER);
    datatable.addCell(c);

    while (detail.next()) {
        v = detail.getString("userlogin");
        c = new PdfPCell(new Phrase(v, tblBodyFont));
        c.setHorizontalAlignment(Element.ALIGN_CENTER);
        datatable.addCell(c);

        v = detail.getString("lname");
        c = new PdfPCell(new Phrase(v, tblBodyFont));
        c.setHorizontalAlignment(Element.ALIGN_CENTER);
        datatable.addCell(c);

        v = detail.getString("fname");
        c = new PdfPCell(new Phrase(v, tblBodyFont));
        c.setHorizontalAlignment(Element.ALIGN_CENTER);
        datatable.addCell(c);

        v = detail.getString("email");
        c = new PdfPCell(new Phrase(v, tblBodyFont));
        c.setHorizontalAlignment(Element.ALIGN_CENTER);
        datatable.addCell(c);
    }

    datatable.setSpacingBefore(20);
    return datatable;

}

From source file:eu.europa.ec.markt.dss.report.Tsl2PdfExporter.java

License:Open Source License

/**
 * Produce a human readable export of the given tsl to the given file.
 * //from  ww  w  .  ja  v a 2 s.co  m
 * @param tsl
 *            the TrustServiceList to export
 * @param pdfFile
 *            the file to generate
 * @return
 * @throws IOException
 */
public void humanReadableExport(final TrustServiceList tsl, final File pdfFile) {
    Document document = new Document();
    OutputStream outputStream;
    try {
        outputStream = new FileOutputStream(pdfFile);
    } catch (FileNotFoundException e) {
        throw new RuntimeException("file not found: " + pdfFile.getAbsolutePath(), e);
    }
    try {
        final PdfWriter pdfWriter = PdfWriter.getInstance(document, outputStream);
        pdfWriter.setPDFXConformance(PdfWriter.PDFA1B);

        // title
        final EUCountry country = EUCountry.valueOf(tsl.getSchemeTerritory());
        final String title = country.getShortSrcLangName() + " (" + country.getShortEnglishName()
                + "): Trusted List";

        Phrase footerPhrase = new Phrase("PDF document generated on " + new Date().toString() + ", page ",
                headerFooterFont);
        HeaderFooter footer = new HeaderFooter(footerPhrase, true);
        document.setFooter(footer);

        Phrase headerPhrase = new Phrase(title, headerFooterFont);
        HeaderFooter header = new HeaderFooter(headerPhrase, false);
        document.setHeader(header);

        document.open();
        addTitle(title, title0Font, Paragraph.ALIGN_CENTER, 0, 20, document);

        addLongItem("Scheme name", tsl.getSchemeName(), document);
        addLongItem("Legal Notice", tsl.getLegalNotice(), document);

        // information table
        PdfPTable informationTable = createInfoTable();
        addItemRow("Scheme territory", tsl.getSchemeTerritory(), informationTable);
        addItemRow("Scheme status determination approach",
                substringAfter(tsl.getStatusDeterminationApproach(), "StatusDetn/"), informationTable);

        final List<String> schemeTypes = new ArrayList<String>();
        for (final String schemeType : tsl.getSchemeTypes()) {
            schemeTypes.add(schemeType);
        }
        addItemRow("Scheme type community rules", schemeTypes, informationTable);

        addItemRow("Issue date", tsl.getListIssueDateTime().toString(), informationTable);
        addItemRow("Next update", tsl.getNextUpdate().toString(), informationTable);
        addItemRow("Historical information period", tsl.getHistoricalInformationPeriod().toString() + " days",
                informationTable);
        addItemRow("Sequence number", tsl.getSequenceNumber().toString(), informationTable);
        addItemRow("Scheme information URIs", tsl.getSchemeInformationUris(), informationTable);

        document.add(informationTable);

        addTitle("Scheme Operator", title1Font, Paragraph.ALIGN_CENTER, 0, 10, document);

        informationTable = createInfoTable();
        addItemRow("Scheme operator name", tsl.getSchemeOperatorName(), informationTable);
        PostalAddressType schemeOperatorPostalAddress = tsl.getSchemeOperatorPostalAddress(Locale.ENGLISH);
        addItemRow("Scheme operator street address", schemeOperatorPostalAddress.getStreetAddress(),
                informationTable);
        addItemRow("Scheme operator postal code", schemeOperatorPostalAddress.getPostalCode(),
                informationTable);
        addItemRow("Scheme operator locality", schemeOperatorPostalAddress.getLocality(), informationTable);
        addItemRow("Scheme operator state", schemeOperatorPostalAddress.getStateOrProvince(), informationTable);
        addItemRow("Scheme operator country", schemeOperatorPostalAddress.getCountryName(), informationTable);

        List<String> schemeOperatorElectronicAddressess = tsl.getSchemeOperatorElectronicAddresses();
        addItemRow("Scheme operator contact", schemeOperatorElectronicAddressess, informationTable);
        document.add(informationTable);

        addTitle("Trust Service Providers", title1Font, Paragraph.ALIGN_CENTER, 10, 2, document);

        List<TrustServiceProvider> trustServiceProviders = tsl.getTrustServiceProviders();
        for (TrustServiceProvider trustServiceProvider : trustServiceProviders) {
            addTitle(trustServiceProvider.getName(), title1Font, Paragraph.ALIGN_LEFT, 10, 2, document);

            PdfPTable providerTable = createInfoTable();
            addItemRow("Service provider trade name", trustServiceProvider.getTradeName(), providerTable);
            addItemRow("Information URI", trustServiceProvider.getInformationUris(), providerTable);
            PostalAddressType postalAddress = trustServiceProvider.getPostalAddress();
            addItemRow("Service provider street address", postalAddress.getStreetAddress(), providerTable);
            addItemRow("Service provider postal code", postalAddress.getPostalCode(), providerTable);
            addItemRow("Service provider locality", postalAddress.getLocality(), providerTable);
            addItemRow("Service provider state", postalAddress.getStateOrProvince(), providerTable);
            addItemRow("Service provider country", postalAddress.getCountryName(), providerTable);
            document.add(providerTable);

            List<TrustService> trustServices = trustServiceProvider.getTrustServices();
            for (TrustService trustService : trustServices) {
                addTitle(trustService.getName(), title2Font, Paragraph.ALIGN_LEFT, 10, 2, document);
                PdfPTable serviceTable = createInfoTable();
                addItemRow("Type", substringAfter(trustService.getType(), "Svctype/"), serviceTable);
                addItemRow("Status", substringAfter(trustService.getStatus(), "Svcstatus/"), serviceTable);
                addItemRow("Status starting time", trustService.getStatusStartingTime().toString(),
                        serviceTable);
                document.add(serviceTable);

                addTitle("Service digital identity (X509)", title3Font, Paragraph.ALIGN_LEFT, 2, 0, document);
                final X509Certificate certificate = trustService.getServiceDigitalIdentity();
                final PdfPTable serviceIdentityTable = createInfoTable();
                addItemRow("Version", Integer.toString(certificate.getVersion()), serviceIdentityTable);
                addItemRow("Serial number", certificate.getSerialNumber().toString(), serviceIdentityTable);
                addItemRow("Signature algorithm", certificate.getSigAlgName(), serviceIdentityTable);
                addItemRow("Issuer", certificate.getIssuerX500Principal().toString(), serviceIdentityTable);
                addItemRow("Valid from", certificate.getNotBefore().toString(), serviceIdentityTable);
                addItemRow("Valid to", certificate.getNotAfter().toString(), serviceIdentityTable);
                addItemRow("Subject", certificate.getSubjectX500Principal().toString(), serviceIdentityTable);
                addItemRow("Public key", certificate.getPublicKey().toString(), serviceIdentityTable);
                // TODO certificate policies
                addItemRow("Subject key identifier", toHex(getSKId(certificate)), serviceIdentityTable);
                addItemRow("CRL distribution points", getCrlDistributionPoints(certificate),
                        serviceIdentityTable);
                addItemRow("Authority key identifier", toHex(getAKId(certificate)), serviceIdentityTable);
                addItemRow("Key usage", getKeyUsage(certificate), serviceIdentityTable);
                addItemRow("Basic constraints", getBasicConstraints(certificate), serviceIdentityTable);

                byte[] encodedCertificate;
                try {
                    encodedCertificate = certificate.getEncoded();
                } catch (CertificateEncodingException e) {
                    throw new RuntimeException("cert: " + e.getMessage(), e);
                }
                addItemRow("SHA1 Thumbprint", DigestUtils.shaHex(encodedCertificate), serviceIdentityTable);
                addItemRow("SHA256 Thumbprint", DigestUtils.sha256Hex(encodedCertificate),
                        serviceIdentityTable);
                document.add(serviceIdentityTable);

                List<ExtensionType> extensions = trustService.getExtensions();
                for (ExtensionType extension : extensions) {
                    printExtension(extension, document);
                }

                addLongMonoItem("The decoded certificate:", certificate.toString(), document);
                addLongMonoItem("The certificate in PEM format:", toPem(certificate), document);
            }
        }

        X509Certificate signerCertificate = tsl.verifySignature();
        if (null != signerCertificate) {
            Paragraph tslSignerTitle = new Paragraph("Trusted List Signer", title1Font);
            tslSignerTitle.setAlignment(Paragraph.ALIGN_CENTER);
            document.add(tslSignerTitle);

            final PdfPTable signerTable = createInfoTable();
            addItemRow("Subject", signerCertificate.getSubjectX500Principal().toString(), signerTable);
            addItemRow("Issuer", signerCertificate.getIssuerX500Principal().toString(), signerTable);
            addItemRow("Not before", signerCertificate.getNotBefore().toString(), signerTable);
            addItemRow("Not after", signerCertificate.getNotAfter().toString(), signerTable);
            addItemRow("Serial number", signerCertificate.getSerialNumber().toString(), signerTable);
            addItemRow("Version", Integer.toString(signerCertificate.getVersion()), signerTable);
            byte[] encodedPublicKey = signerCertificate.getPublicKey().getEncoded();
            addItemRow("Public key SHA1 Thumbprint", DigestUtils.shaHex(encodedPublicKey), signerTable);
            addItemRow("Public key SHA256 Thumbprint", DigestUtils.sha256Hex(encodedPublicKey), signerTable);
            document.add(signerTable);

            addLongMonoItem("The decoded certificate:", signerCertificate.toString(), document);
            addLongMonoItem("The certificate in PEM format:", toPem(signerCertificate), document);
            addLongMonoItem("The public key in PEM format:", toPem(signerCertificate.getPublicKey()), document);
        }

        document.close();
    } catch (DocumentException e) {
        throw new RuntimeException("PDF document error: " + e.getMessage(), e);
    } catch (Exception e) {
        throw new RuntimeException("Exception: " + e.getMessage(), e);
    }
}

From source file:fr.paris.lutece.plugins.directory.modules.pdfproducer.utils.PDFUtils.java

License:Open Source License

/**
 * method to create PDF/*w w w . ja v  a2  s  .c o m*/
 * @param adminUser The admin user
 * @param locale The locale
 * @param strNameFile PDF name
 * @param out OutputStream
 * @param nIdRecord the id record
 * @param listIdEntryConfig list of config id entry
 * @param bExtractNotFilledField if true, extract empty fields, false
 */
public static void doCreateDocumentPDF(AdminUser adminUser, Locale locale, String strNameFile, OutputStream out,
        int nIdRecord, List<Integer> listIdEntryConfig, Boolean bExtractNotFilledField) {
    Document document = new Document(PageSize.A4);

    Plugin plugin = PluginService.getPlugin(DirectoryPlugin.PLUGIN_NAME);

    EntryFilter filter;

    Record record = RecordHome.findByPrimaryKey(nIdRecord, plugin);

    filter = new EntryFilter();
    filter.setIdDirectory(record.getDirectory().getIdDirectory());
    filter.setIsGroup(EntryFilter.FILTER_TRUE);

    List<IEntry> listEntry = DirectoryUtils.getFormEntries(record.getDirectory().getIdDirectory(), plugin,
            adminUser);
    int nIdDirectory = record.getDirectory().getIdDirectory();
    Directory directory = DirectoryHome.findByPrimaryKey(nIdDirectory, plugin);

    try {
        PdfWriter.getInstance(document, out);
    } catch (DocumentException e) {
        AppLogService.error(e);
    }

    document.open();

    if (record.getDateCreation() != null) {
        SimpleDateFormat monthDayYearformatter = new SimpleDateFormat(
                AppPropertiesService.getProperty(PROPERTY_POLICE_FORMAT_DATE));

        Font fontDate = new Font(
                DirectoryUtils.convertStringToInt(AppPropertiesService.getProperty(PROPERTY_POLICE_NAME)),
                DirectoryUtils.convertStringToInt(AppPropertiesService.getProperty(PROPERTY_POLICE_SIZE_DATE)),
                DirectoryUtils
                        .convertStringToInt(AppPropertiesService.getProperty(PROPERTY_POLICE_STYLE_DATE)));

        Paragraph paragraphDate = new Paragraph(
                new Phrase(monthDayYearformatter.format(record.getDateCreation()).toString(), fontDate));

        paragraphDate.setAlignment(DirectoryUtils
                .convertStringToInt(AppPropertiesService.getProperty(PROPERTY_POLICE_ALIGN_DATE)));

        try {
            document.add(paragraphDate);
        } catch (DocumentException e) {
            AppLogService.error(e);
        }
    }

    Image image;

    try {

        image = Image.getInstance(ImageIO.read(new File(AppPathService
                .getAbsolutePathFromRelativePath(AppPropertiesService.getProperty(PROPERTY_IMAGE_URL)))), null);
        image.setAlignment(
                DirectoryUtils.convertStringToInt(AppPropertiesService.getProperty(PROPERTY_IMAGE_ALIGN)));
        float fitWidth;
        float fitHeight;

        try {
            fitWidth = Float.parseFloat(AppPropertiesService.getProperty(PROPERTY_IMAGE_FITWIDTH));
            fitHeight = Float.parseFloat(AppPropertiesService.getProperty(PROPERTY_IMAGE_FITHEIGHT));
        } catch (NumberFormatException e) {
            fitWidth = 100f;
            fitHeight = 100f;
        }

        image.scaleToFit(fitWidth, fitHeight);

        try {
            document.add(image);
        } catch (DocumentException e) {
            AppLogService.error(e);
        }
    } catch (BadElementException e) {
        AppLogService.error(e);
    } catch (MalformedURLException e) {
        AppLogService.error(e);
    } catch (IOException e) {
        AppLogService.error(e);
    }

    directory.getTitle();

    Font fontTitle = new Font(
            DirectoryUtils.convertStringToInt(AppPropertiesService.getProperty(PROPERTY_POLICE_NAME)),
            DirectoryUtils
                    .convertStringToInt(AppPropertiesService.getProperty(PROPERTY_POLICE_SIZE_TITLE_DIRECTORY)),
            DirectoryUtils.convertStringToInt(
                    AppPropertiesService.getProperty(PROPERTY_POLICE_STYLE_TITLE_DIRECTORY)));
    fontTitle.isUnderlined();

    Paragraph paragraphHeader = new Paragraph(new Phrase(directory.getTitle(), fontTitle));
    paragraphHeader.setAlignment(Element.ALIGN_CENTER);
    paragraphHeader.setSpacingBefore(DirectoryUtils.convertStringToInt(
            AppPropertiesService.getProperty(PROPERTY_POLICE_SPACING_BEFORE_TITLE_DIRECTORY)));
    paragraphHeader.setSpacingAfter(DirectoryUtils.convertStringToInt(
            AppPropertiesService.getProperty(PROPERTY_POLICE_SPACING_AFTER_TITLE_DIRECTORY)));

    try {
        document.add(paragraphHeader);
    } catch (DocumentException e) {
        AppLogService.error(e);
    }

    builderPDFWithEntry(document, plugin, nIdRecord, listEntry, listIdEntryConfig, locale,
            bExtractNotFilledField);
    document.close();
}

From source file:fr.paris.lutece.plugins.directory.modules.pdfproducer.utils.PDFUtils.java

License:Open Source License

/**
 * method to builder PDF with directory entry
 * @param document document pdf// w  w  w  .j  a v  a2  s.  co m
 * @param plugin plugin
 * @param nIdRecord id record
 * @param listEntry list of entry
 * @param listIdEntryConfig list of config id entry
 * @param locale the locale
 * @param bExtractNotFilledField if true, extract empty fields, false
 */
private static void builderPDFWithEntry(Document document, Plugin plugin, int nIdRecord, List<IEntry> listEntry,
        List<Integer> listIdEntryConfig, Locale locale, Boolean bExtractNotFilledField) {
    Map<String, List<RecordField>> mapIdEntryListRecordField = DirectoryUtils
            .getMapIdEntryListRecordField(listEntry, nIdRecord, plugin);

    for (IEntry entry : listEntry) {
        if (entry.getEntryType().getGroup() && (listIdEntryConfig.isEmpty()
                || listIdEntryConfig.contains(Integer.valueOf(entry.getIdEntry())))) {
            Font fontEntryTitleGroup = new Font(
                    DirectoryUtils.convertStringToInt(AppPropertiesService.getProperty(PROPERTY_POLICE_NAME)),
                    DirectoryUtils.convertStringToInt(
                            AppPropertiesService.getProperty(PROPERTY_POLICE_SIZE_ENTRY_GROUP)),
                    DirectoryUtils.convertStringToInt(
                            AppPropertiesService.getProperty(PROPERTY_POLICE_STYLE_ENTRY_GROUP)));
            Paragraph paragraphTitleGroup = new Paragraph(new Phrase(entry.getTitle(), fontEntryTitleGroup));
            paragraphTitleGroup.setAlignment(Element.ALIGN_LEFT);
            paragraphTitleGroup.setIndentationLeft(DirectoryUtils.convertStringToInt(
                    AppPropertiesService.getProperty(PROPERTY_POLICE_MARGIN_LEFT_ENTRY_GROUP)));
            paragraphTitleGroup.setSpacingBefore(DirectoryUtils.convertStringToInt(
                    AppPropertiesService.getProperty(PROPERTY_POLICE_SPACING_BEFORE_ENTRY_GROUP)));
            paragraphTitleGroup.setSpacingAfter(DirectoryUtils.convertStringToInt(
                    AppPropertiesService.getProperty(PROPERTY_POLICE_SPACING_AFTER_ENTRY_GROUP)));

            try {
                document.add(paragraphTitleGroup);
            } catch (DocumentException e) {
                AppLogService.error(e);
            }

            if (entry.getChildren() != null) {
                for (IEntry child : entry.getChildren()) {
                    if (listIdEntryConfig.isEmpty()
                            || listIdEntryConfig.contains(Integer.valueOf(child.getIdEntry()))) {
                        try {
                            builFieldsInPDF(mapIdEntryListRecordField.get(Integer.toString(child.getIdEntry())),
                                    document, child, locale, bExtractNotFilledField);
                        } catch (DocumentException e) {
                            AppLogService.error(e);
                        }
                    }
                }
            }
        } else {
            if (listIdEntryConfig.isEmpty()
                    || listIdEntryConfig.contains(Integer.valueOf(entry.getIdEntry()))) {
                try {
                    builFieldsInPDF(mapIdEntryListRecordField.get(Integer.toString(entry.getIdEntry())),
                            document, entry, locale, bExtractNotFilledField);
                } catch (DocumentException e) {
                    AppLogService.error(e);
                }
            }
        }
    }
}