Example usage for com.lowagie.text Font Font

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

Introduction

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

Prototype


public Font(int family, float size, int style) 

Source Link

Document

Constructs a Font.

Usage

From source file:edu.harvard.mcz.imagecapture.encoder.LabelEncoder.java

License:Open Source License

@SuppressWarnings("hiding")
public static boolean printList(List<UnitTrayLabel> taxa) throws PrintFailedException {
    boolean result = false;
    UnitTrayLabel label = new UnitTrayLabel();
    LabelEncoder encoder = new LabelEncoder(label);
    Image image = encoder.getImage();
    int counter = 0;
    try {/*from  w ww .ja v  a 2 s.c  om*/
        Document document = new Document();
        PdfWriter.getInstance(document, new FileOutputStream("labels.pdf"));
        document.setPageSize(PageSize.LETTER);
        document.open();

        PdfPTable table = new PdfPTable(4);
        table.setWidthPercentage(100f);
        //table.setHorizontalAlignment(PdfPTable.ALIGN_LEFT);
        float[] cellWidths = { 30f, 20f, 30f, 20f };
        table.setWidths(cellWidths);

        UnitTrayLabelLifeCycle uls = new UnitTrayLabelLifeCycle();
        if (taxa == null) {
            taxa = uls.findAll();
        }
        Iterator<UnitTrayLabel> i = taxa.iterator();
        PdfPCell cell = null;
        PdfPCell cell_barcode = null;
        // Create two lists of 12 cells, the first 6 of each representing
        // the left hand column of 6 labels, the second 6 of each 
        // representing the right hand column.  
        // cells holds the text for each label, cells_barcode the barcode.
        ArrayList<PdfPCell> cells = new ArrayList<PdfPCell>(12);
        ArrayList<PdfPCell> cells_barcode = new ArrayList<PdfPCell>(12);
        for (int x = 0; x < 12; x++) {
            cells.add(null);
            cells_barcode.add(null);
        }
        int cellCounter = 0;
        while (i.hasNext()) {
            // Loop through all of the taxa (unit tray labels) found to print 
            label = i.next();
            for (int toPrint = 0; toPrint < label.getNumberToPrint(); toPrint++) {
                // For each taxon, loop through the number of requested copies 
                // Generate a text and a barcode cell for each, and add to array for page
                log.debug("Label " + toPrint + " of " + label.getNumberToPrint());
                cell = new PdfPCell();
                cell.setBorderColor(Color.LIGHT_GRAY);
                cell.setVerticalAlignment(PdfPCell.ALIGN_TOP);
                cell.disableBorderSide(PdfPCell.RIGHT);
                cell.setPaddingLeft(3);

                String higherNames = "";
                if (label.getTribe().trim().length() > 0) {
                    higherNames = label.getFamily() + ": " + label.getSubfamily() + ": " + label.getTribe();
                } else {
                    higherNames = label.getFamily() + ": " + label.getSubfamily();
                }
                Paragraph higher = new Paragraph();
                higher.setFont(new Font(Font.TIMES_ROMAN, 11, Font.NORMAL));
                higher.add(new Chunk(higherNames));
                cell.addElement(higher);

                Paragraph name = new Paragraph();
                Chunk genus = new Chunk(label.getGenus().trim() + " ");
                genus.setFont(new Font(Font.TIMES_ROMAN, 11, Font.ITALIC));
                Chunk species = new Chunk(label.getSpecificEpithet().trim());
                Chunk normal = null; // normal font prefix to preceed specific epithet (nr. <i>epithet</i>)
                if (label.getSpecificEpithet().contains(".") || label.getSpecificEpithet().contains("[")) {
                    if (label.getSpecificEpithet().startsWith("nr. ")) {
                        normal = new Chunk("nr. ");
                        normal.setFont(new Font(Font.TIMES_ROMAN, 11, Font.NORMAL));
                        species = new Chunk(label.getSpecificEpithet().trim().substring(4));
                        species.setFont(new Font(Font.TIMES_ROMAN, 11, Font.ITALIC));
                    } else {
                        species.setFont(new Font(Font.TIMES_ROMAN, 11, Font.NORMAL));
                    }
                } else {
                    species.setFont(new Font(Font.TIMES_ROMAN, 11, Font.ITALIC));
                }
                String s = "";
                if (label.getSubspecificEpithet().trim().length() > 0) {
                    s = " ";
                } else {
                    s = "";
                }
                Chunk subspecies = new Chunk(s + label.getSubspecificEpithet().trim());
                if (label.getSubspecificEpithet().contains(".")
                        || label.getSubspecificEpithet().contains("[")) {
                    subspecies.setFont(new Font(Font.TIMES_ROMAN, 11, Font.NORMAL));
                } else {
                    subspecies.setFont(new Font(Font.TIMES_ROMAN, 11, Font.ITALIC));
                }
                if (label.getInfraspecificRank().trim().length() > 0) {
                    s = " ";
                } else {
                    s = "";
                }
                Chunk infraRank = new Chunk(s + label.getInfraspecificRank().trim());
                infraRank.setFont(new Font(Font.TIMES_ROMAN, 11, Font.NORMAL));

                if (label.getInfraspecificEpithet().trim().length() > 0) {
                    s = " ";
                } else {
                    s = "";
                }
                Chunk infra = new Chunk(s + label.getInfraspecificEpithet().trim());
                infra.setFont(new Font(Font.TIMES_ROMAN, 11, Font.ITALIC));
                if (label.getUnNamedForm().trim().length() > 0) {
                    s = " ";
                } else {
                    s = "";
                }
                Chunk unNamed = new Chunk(s + label.getUnNamedForm().trim());
                unNamed.setFont(new Font(Font.TIMES_ROMAN, 11, Font.NORMAL));

                name.add(genus);
                if (normal != null) {
                    name.add(normal);
                }
                name.add(species);
                name.add(subspecies);
                name.add(infraRank);
                name.add(infra);
                name.add(unNamed);
                cell.addElement(name);

                Paragraph authorship = new Paragraph();
                authorship.setFont(new Font(Font.TIMES_ROMAN, 10, Font.NORMAL));
                if (label.getAuthorship() != null && label.getAuthorship().length() > 0) {
                    Chunk c_authorship = new Chunk(label.getAuthorship());
                    authorship.add(c_authorship);
                }
                cell.addElement(authorship);
                //cell.addElement(new Paragraph(" "));
                if (label.getDrawerNumber() != null && label.getDrawerNumber().length() > 0) {
                    Paragraph drawerNumber = new Paragraph();
                    drawerNumber.setFont(new Font(Font.TIMES_ROMAN, 10, Font.NORMAL));
                    Chunk c_drawerNumber = new Chunk(label.getDrawerNumber());
                    drawerNumber.add(c_drawerNumber);
                    cell.addElement(drawerNumber);
                } else {
                    if (label.getCollection() != null && label.getCollection().length() > 0) {
                        Paragraph collection = new Paragraph();
                        collection.setFont(new Font(Font.TIMES_ROMAN, 10, Font.NORMAL));
                        Chunk c_collection = new Chunk(label.getCollection());
                        collection.add(c_collection);
                        cell.addElement(collection);
                    }
                }

                cell_barcode = new PdfPCell();
                cell_barcode.setBorderColor(Color.LIGHT_GRAY);
                cell_barcode.disableBorderSide(PdfPCell.LEFT);
                cell_barcode.setVerticalAlignment(PdfPCell.ALIGN_TOP);

                encoder = new LabelEncoder(label);
                image = encoder.getImage();
                image.setAlignment(Image.ALIGN_TOP);
                cell_barcode.addElement(image);

                cells.add(cellCounter, cell);
                cells_barcode.add(cellCounter, cell_barcode);

                cellCounter++;
                // If we have hit a full set of 12 labels, add them to the document
                // in two columns, filling left column first, then right
                if (cellCounter == 12) {
                    // add a page of 12 cells in columns of two.
                    for (int x = 0; x < 6; x++) {
                        if (cells.get(x) == null) {
                            PdfPCell c = new PdfPCell();
                            c.setBorder(0);
                            table.addCell(c);
                            table.addCell(c);
                        } else {
                            table.addCell(cells.get(x));
                            table.addCell(cells_barcode.get(x));
                        }
                        if (cells.get(x + 6) == null) {
                            PdfPCell c = new PdfPCell();
                            c.setBorder(0);
                            table.addCell(c);
                            table.addCell(c);
                        } else {
                            table.addCell(cells.get(x + 6));
                            table.addCell(cells_barcode.get(x + 6));
                        }
                    }
                    // Reset to begin next page
                    cellCounter = 0;
                    document.add(table);
                    table = new PdfPTable(4);
                    table.setWidthPercentage(100f);
                    table.setWidths(cellWidths);
                    for (int x = 0; x < 12; x++) {
                        cells.set(x, null);
                        cells_barcode.set(x, null);
                    }
                }
            } // end loop through toPrint (for a taxon)
            counter++;
        } // end while results has next (for all taxa requested)
          // get any remaining cells in pairs
        for (int x = 0; x < 6; x++) {
            if (cells.get(x) == null) {
                PdfPCell c = new PdfPCell();
                c.setBorder(0);
                table.addCell(c);
                table.addCell(c);
            } else {
                table.addCell(cells.get(x));
                table.addCell(cells_barcode.get(x));
            }
            if (cells.get(x + 6) == null) {
                PdfPCell c = new PdfPCell();
                c.setBorder(0);
                table.addCell(c);
                table.addCell(c);
            } else {
                table.addCell(cells.get(x + 6));
                table.addCell(cells_barcode.get(x + 6));
            }
        }
        // add any remaining cells
        document.add(table);
        try {
            document.close();
        } catch (Exception e) {
            throw new PrintFailedException("No labels to print." + e.getMessage());
        }
        // Check to see if there was content in the document.
        if (counter == 0) {
            result = false;
        } else {
            // Printed to pdf ok.
            result = true;
            // Increment number printed.
            i = taxa.iterator();
            while (i.hasNext()) {
                label = i.next();
                for (int toPrint = 0; toPrint < label.getNumberToPrint(); toPrint++) {
                    label.setPrinted(label.getPrinted() + 1);
                }
                label.setNumberToPrint(0);
                try {
                    uls.attachDirty(label);
                } catch (SaveFailedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        throw new PrintFailedException("File not found.");
    } catch (DocumentException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        throw new PrintFailedException("Error buiding PDF document.");
    } catch (OutOfMemoryError e) {
        System.out.println("Out of memory error. " + e.getMessage());
        System.out.println("Failed.  Too many labels.");
        throw new PrintFailedException("Ran out of memory, too many labels at once.");
    }
    return result;
}

From source file:fr.aliasource.webmail.server.export.ConversationExporter.java

License:GNU General Public License

@SuppressWarnings("unchecked")
private void exportMessage(Set<ClientMessage> cm, Document d, boolean isForward) throws DocumentException {

    LineSeparator hr = new LineSeparator();
    StyleSheet styles = new StyleSheet();
    Font fnormal = new Font(Font.HELVETICA, 9, Font.NORMAL);
    Font fbold = new Font(Font.HELVETICA, 9, Font.BOLD);

    Iterator<ClientMessage> it = cm.iterator();
    Cell c = null;/*from  w w w . j a v  a2s . co  m*/
    while (it.hasNext()) {
        ClientMessage fwdCm = it.next();
        if (isForward) {
            c = new Cell();
        }

        // Subject (only if isForward)
        if (isForward) {
            String subjectText = fwdCm.getSubject();
            String dateText = formatDate(fwdCm.getDate());
            Chunk subject = new Chunk(subjectText, fbold);
            Chunk date = new Chunk(dateText, fbold);
            Paragraph subjectPar = new Paragraph(subject + ", " + date);
            subjectPar.setIndentationLeft(5.0f);
            c.add(subjectPar);
            c.add(Chunk.NEWLINE);
        } else {
            String dateText = formatDate(fwdCm.getDate());
            Chunk date = new Chunk(dateText, fbold);
            Paragraph datePar = new Paragraph(date);
            datePar.setAlignment(Element.ALIGN_RIGHT);
            d.add(datePar);
        }

        // Sender
        String senderText = formatAddress(fwdCm.getSender());
        Chunk sender = new Chunk(senderText, fbold);
        sender.setTextRise(10.0f);
        Paragraph senderPar = new Paragraph(sender);
        if (isForward) {
            senderPar.setIndentationLeft(5.0f);
            c.add(senderPar);
        } else {
            d.add(senderPar);
        }

        appendRecipients(d, c, isForward, "To:", fwdCm.getTo());
        appendRecipients(d, c, isForward, "Cc:", fwdCm.getCc());
        appendRecipients(d, c, isForward, "Bcc:", fwdCm.getBcc());
        if (isForward) {
            c.add(Chunk.NEWLINE);
        }

        // Body
        String bodyText = fwdCm.getBody().getCleanHtml();
        Paragraph bodyPar = new Paragraph();
        bodyPar.setFont(fnormal);
        if (bodyText != null && !bodyText.isEmpty()) {
            try {
                List<Element> objects = HTMLWorker.parseToList(new StringReader(bodyText), styles);
                for (Iterator<Element> iterator = objects.iterator(); iterator.hasNext();) {
                    Element el = iterator.next();
                    if (!(el instanceof Image)) {
                        // bodyPar.add(el);
                        if (isForward) {
                            c.add(el);
                        } else {
                            bodyPar.add(el);
                        }
                    }
                }
            } catch (Exception e) {
                logger.warn("Cannot generate pdf from html body use plain text instead", e);
                // bodyPar.add(fwdCm.getBody().getPlain());
                if (isForward) {
                    Chunk t = new Chunk(fwdCm.getBody().getPlain());
                    t.setFont(fnormal);
                    c.add(t);
                } else {
                    bodyPar.add(fwdCm.getBody().getPlain());
                }
            }
        } else {
            if (isForward) {
                Chunk t = new Chunk(fwdCm.getBody().getPlain());
                t.setFont(fnormal);
                c.add(t);
            } else {
                bodyPar.add(fwdCm.getBody().getPlain());
            }
        }

        if (isForward) {
            // c.add(bodyPar);
            Table t = new Table(1);
            t.setPadding(5);
            t.setBackgroundColor(new Color(242, 242, 242));
            t.addCell(c);
            d.add(t);
        } else {
            bodyPar.setIndentationLeft(15.0f);
            d.add(bodyPar);
        }

        if (fwdCm.getFwdMessages() != null) {
            this.exportMessage(fwdCm.getFwdMessages(), d, true);
        }
        d.add(hr);
    }

}

From source file:fr.aliasource.webmail.server.export.ConversationExporter.java

License:GNU General Public License

private Chunk getRecipientLabel(String label) {
    Chunk recipientsLabel = new Chunk(label, new Font(Font.HELVETICA, 10, Font.BOLD));
    recipientsLabel.setTextRise(15.0f);/*from w w  w .ja v  a2 s  . c o m*/
    return recipientsLabel;
}

From source file:fr.aliasource.webmail.server.export.ConversationPdfEventHandler.java

License:GNU General Public License

/**
 * @see com.lowagie.text.pdf.PdfPageEventHelper#onOpenDocument(com.lowagie.text.pdf.PdfWriter,
 *      com.lowagie.text.Document)/*from   w w  w .j  a  v a2  s  . co  m*/
 */
public void onOpenDocument(PdfWriter writer, Document document) {
    try {
        headerImage = Image.getInstance(getLogoUrl());
        table = new PdfPTable(new float[] { 1f, 2f });
        Phrase p = new Phrase();
        Chunk ck = new Chunk(cr.getTitle(), new Font(Font.HELVETICA, 16, Font.BOLD));
        p.add(ck);
        p.add(Chunk.NEWLINE);
        ck = new Chunk(ConversationExporter.formatName(account), new Font(Font.HELVETICA, 12, Font.BOLDITALIC));
        p.add(ck);
        p.add(Chunk.NEWLINE);
        ck = new Chunk(cm.length + " messages", new Font(Font.HELVETICA, 10));
        p.add(ck);
        table.getDefaultCell().setBorder(0);
        table.addCell(new Phrase(new Chunk(headerImage, 0, 0)));
        table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_RIGHT);
        table.addCell(p);
        // initialization of the template
        tpl = writer.getDirectContent().createTemplate(100, 100);
        tpl.setBoundingBox(new Rectangle(-20, -20, 100, 100));
        // initialization of the font
        helv = BaseFont.createFont("Helvetica", BaseFont.WINANSI, false);
    } catch (Exception e) {
        throw new ExceptionConverter(e);
    }
}

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

License:Open Source License

/**
 * method to create PDF/*ww w .j  ava2 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//from  w w  w  . j a  v a2 s.  c o 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);
                }
            }
        }
    }
}

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

License:Open Source License

/**
 * This method build the different label and value of directory fields in
 * the document PDF/* w w w . j a v  a2  s.c o  m*/
 * 
 * @param listRecordFields recordfield map
 * @param document document pdf
 * @param entry entry
 * @param locale the locale
 * @param bExtractNotFilledField if true, extract empty fields, false
 * @throws DocumentException DocumentException
 */
private static void builFieldsInPDF(List<RecordField> listRecordFields, Document document, IEntry entry,
        Locale locale, Boolean bExtractNotFilledField) throws DocumentException {
    Phrase phraseEntry = new Phrase();
    Paragraph paragraphEntry = new Paragraph();

    if (StringUtils.isNotBlank(entry.getTitle())) {
        entry.getTitle();

        Font fontEntryTitle = new Font(
                DirectoryUtils.convertStringToInt(AppPropertiesService.getProperty(PROPERTY_POLICE_NAME)),
                DirectoryUtils
                        .convertStringToInt(AppPropertiesService.getProperty(PROPERTY_POLICE_SIZE_ENTRY_TITLE)),
                DirectoryUtils.convertStringToInt(
                        AppPropertiesService.getProperty(PROPERTY_POLICE_STYLE_ENTRY_TITLE)));
        Chunk chunkEntryTitle = new Chunk(entry.getTitle(), fontEntryTitle);
        phraseEntry.add(chunkEntryTitle);
        phraseEntry.add(" : ");
    }

    if ((listRecordFields != null) && (listRecordFields.size() > 0)) {
        // Must separate the behaviour whether the list of record fiels contains 1 or more record fields
        if ((listRecordFields.size() > 1)
                && !(entry instanceof fr.paris.lutece.plugins.directory.business.EntryTypeGeolocation)) {
            builFieldsInParagraph(listRecordFields, entry, locale, phraseEntry, paragraphEntry,
                    bExtractNotFilledField);
        } else {
            builFieldsInSinglePhrase(listRecordFields, entry, locale, phraseEntry, paragraphEntry,
                    bExtractNotFilledField);
        }
    }

    document.add(paragraphEntry);
}

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

License:Open Source License

/**
 * Build the fields in a whole paragraph.
 * @param listRecordFields the list of record fields
 * @param entry the entry//from w w  w  .  j ava  2 s .  c om
 * @param locale the locale
 * @param phraseEntry the phrase entry
 * @param paragraphEntry the paragraph entry
 * @param bExtractNotFilledField if true, extract empty fields, false
 * @throws DocumentException exception if there is an error
 */
private static void builFieldsInParagraph(List<RecordField> listRecordFields, IEntry entry, Locale locale,
        Phrase phraseEntry, Paragraph paragraphEntry, Boolean bExtractNotFilledField) throws DocumentException {
    com.lowagie.text.List listValue = new com.lowagie.text.List(true);
    listValue.setPreSymbol("- ");
    listValue.setNumbered(false);
    listValue.setIndentationLeft(DirectoryUtils
            .convertStringToInt(AppPropertiesService.getProperty(PROPERTY_POLICE_MARGIN_LEFT_ENTRY_VALUE)));

    Font fontEntryValue = new Font(
            DirectoryUtils.convertStringToInt(AppPropertiesService.getProperty(PROPERTY_POLICE_NAME)),
            DirectoryUtils
                    .convertStringToInt(AppPropertiesService.getProperty(PROPERTY_POLICE_SIZE_ENTRY_VALUE)),
            DirectoryUtils
                    .convertStringToInt(AppPropertiesService.getProperty(PROPERTY_POLICE_STYLE_ENTRY_VALUE)));

    for (RecordField recordField : listRecordFields) {
        String strValue = StringUtils.EMPTY;

        if (entry instanceof EntryTypeDownloadUrl && StringUtils.isNotBlank(recordField.getFileName())) {
            strValue = recordField.getFileName();
        } else if ((recordField.getFile() != null)
                && StringUtils.isNotBlank(recordField.getFile().getTitle())) {
            // The thumbnails and big thumbnails should not be displayed
            if (!((StringUtils.isNotBlank(recordField.getValue())
                    && recordField.getValue().startsWith(FIELD_THUMBNAIL))
                    || (StringUtils.isNotBlank(recordField.getValue())
                            && recordField.getValue().startsWith(FIELD_BIG_THUMBNAIL)))) {
                strValue = recordField.getFile().getTitle();
            }
        } else {
            strValue = entry.convertRecordFieldValueToString(recordField, locale, false, false);
        }

        if (bExtractNotFilledField || (!bExtractNotFilledField && StringUtils.isNotBlank(strValue))) {
            listValue.add(new ListItem(strValue, fontEntryValue));
        }
    }

    if (bExtractNotFilledField
            || (!bExtractNotFilledField && CollectionUtils.isNotEmpty(listValue.getItems()))) {
        paragraphEntry.add(phraseEntry);
        paragraphEntry.add(listValue);
    }
}

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

License:Open Source License

/**
 * Build the fields in a single paragraph.
 * @param listRecordFields the list of record fields
 * @param entry the entry/* w ww  .  j  av a 2  s.c om*/
 * @param locale the locale
 * @param phraseEntry the phrase entry
 * @param paragraphEntry the paragraph entry
 * @param bExtractNotFilledField if true, extract empty fields, false
 * @throws DocumentException exception if there is an error
 */
private static void builFieldsInSinglePhrase(List<RecordField> listRecordFields, IEntry entry, Locale locale,
        Phrase phraseEntry, Paragraph paragraphEntry, Boolean bExtractNotFilledField) throws DocumentException {
    RecordField recordField = listRecordFields.get(0);
    Chunk chunkEntryValue = null;
    Font fontEntryValue = new Font(
            DirectoryUtils.convertStringToInt(AppPropertiesService.getProperty(PROPERTY_POLICE_NAME)),
            DirectoryUtils
                    .convertStringToInt(AppPropertiesService.getProperty(PROPERTY_POLICE_SIZE_ENTRY_VALUE)),
            DirectoryUtils
                    .convertStringToInt(AppPropertiesService.getProperty(PROPERTY_POLICE_STYLE_ENTRY_VALUE)));

    if (entry instanceof fr.paris.lutece.plugins.directory.business.EntryTypeDownloadUrl) {
        if (StringUtils.isNotBlank(recordField.getFileName())) {
            chunkEntryValue = new Chunk(recordField.getFileName());
        } else {
            chunkEntryValue = new Chunk(StringUtils.EMPTY);
        }
    } else if (entry instanceof fr.paris.lutece.plugins.directory.business.EntryTypeGeolocation) {
        for (RecordField recordFieldGeo : listRecordFields) {
            if ((recordFieldGeo.getField() != null)
                    && EntryTypeGeolocation.CONSTANT_ADDRESS.equals(recordFieldGeo.getField().getTitle())) {
                chunkEntryValue = new Chunk(
                        entry.convertRecordFieldValueToString(recordFieldGeo, locale, false, false),
                        fontEntryValue);
            }
        }
    } else if (entry instanceof fr.paris.lutece.plugins.directory.business.EntryTypeCheckBox
            || entry instanceof fr.paris.lutece.plugins.directory.business.EntryTypeSelect
            || entry instanceof fr.paris.lutece.plugins.directory.business.EntryTypeRadioButton) {
        chunkEntryValue = new Chunk(entry.convertRecordFieldTitleToString(recordField, locale, false),
                fontEntryValue);
    } else if (entry instanceof fr.paris.lutece.plugins.directory.business.EntryTypeFile
            || entry instanceof fr.paris.lutece.plugins.directory.business.EntryTypeImg) {
        String strFileName = StringUtils.EMPTY;

        if ((recordField.getFile() != null) && StringUtils.isNotBlank(recordField.getFile().getTitle())) {
            // The thumbnails and big thumbnails should not be displayed
            if (!((StringUtils.isNotBlank(recordField.getValue())
                    && recordField.getValue().startsWith(FIELD_THUMBNAIL))
                    || (StringUtils.isNotBlank(recordField.getValue())
                            && recordField.getValue().startsWith(FIELD_BIG_THUMBNAIL)))) {
                strFileName = recordField.getFile().getTitle();
            }
        }

        chunkEntryValue = new Chunk(strFileName, fontEntryValue);
    } else if (entry instanceof fr.paris.lutece.plugins.directory.business.EntryTypeRichText) {
        String strValue = entry.convertRecordFieldValueToString(recordField, locale, false, false);
        strValue = StringUtils.defaultString(HtmlUtils.htmlUnescape(strValue)).replaceAll("<[^>]*>", "");
        chunkEntryValue = new Chunk(strValue, fontEntryValue);
    } else {
        chunkEntryValue = new Chunk(entry.convertRecordFieldValueToString(recordField, locale, false, false),
                fontEntryValue);
    }

    if (chunkEntryValue != null) {
        if (bExtractNotFilledField
                || (!bExtractNotFilledField && StringUtils.isNotBlank(chunkEntryValue.getContent()))) {
            phraseEntry.add(chunkEntryValue);
            paragraphEntry.add(phraseEntry);
        }
    }
}

From source file:is.idega.idegaweb.egov.cases.business.CaseWriter.java

License:Open Source License

protected MemoryFileBuffer writePDF(IWContext iwc) {
    Font titleFont = new Font(Font.HELVETICA, 14, Font.BOLD);
    Font labelFont = new Font(Font.HELVETICA, 11, Font.BOLD);
    Font textFont = new Font(Font.HELVETICA, 11, Font.NORMAL);

    try {// w  w  w. j  ava  2 s  .c  o  m
        MemoryFileBuffer buffer = new MemoryFileBuffer();
        MemoryOutputStream mos = new MemoryOutputStream(buffer);

        Document document = new Document(PageSize.A4, 50, 50, 50, 50);
        PdfWriter.getInstance(document, mos);
        document.addAuthor("Idegaweb eGov");
        document.addSubject("Case");
        document.open();
        document.newPage();

        String title = iwrb.getLocalizedString("case_overview", "Case overview");
        Paragraph cTitle = new Paragraph(title, titleFont);
        cTitle.setSpacingAfter(24);
        document.setPageCount(1);
        document.add(cTitle);

        int[] widths = { 25, 75 };
        PdfPTable table = new PdfPTable(2);
        table.setWidths(widths);
        table.getDefaultCell().setBorder(0);
        table.getDefaultCell().setPaddingBottom(8);

        CaseCategory category = theCase.getCaseCategory();
        CaseCategory parentCategory = category.getParent();
        CaseType type = theCase.getCaseType();
        User user = theCase.getOwner();
        Address address = user != null ? getUserBusiness(iwc).getUsersMainAddress(user) : null;
        PostalCode postal = null;
        if (address != null) {
            postal = address.getPostalCode();
        }
        Phone phone = null;
        if (user != null) {
            try {
                phone = getUserBusiness(iwc).getUsersHomePhone(user);
            } catch (NoPhoneFoundException e) {
                //No phone found...
            }
        }
        Email email = null;
        if (user != null) {
            try {
                email = getUserBusiness(iwc).getUsersMainEmail(user);
            } catch (NoEmailFoundException e) {
                //No email found...
            }
        }

        IWTimestamp created = new IWTimestamp(theCase.getCreated());

        if (user != null) {
            table.addCell(new Phrase(iwrb.getLocalizedString("name", "Name"), labelFont));
            table.addCell(new Phrase(
                    new Name(user.getFirstName(), user.getMiddleName(), user.getLastName()).getName(locale),
                    textFont));

            table.addCell(new Phrase(iwrb.getLocalizedString("personal_id", "Personal ID"), labelFont));
            table.addCell(new Phrase(PersonalIDFormatter.format(user.getPersonalID(), locale), textFont));

            table.addCell(new Phrase(iwrb.getLocalizedString("address", "Address"), labelFont));
            table.addCell(new Phrase(address != null ? address.getStreetAddress() : "-", textFont));

            table.addCell(new Phrase(iwrb.getLocalizedString("zip_code", "Postal code"), labelFont));
            table.addCell(new Phrase(postal != null ? postal.getPostalAddress() : "-", textFont));

            table.addCell(new Phrase(iwrb.getLocalizedString("home_phone", "Home phone"), labelFont));
            table.addCell(new Phrase(phone != null ? phone.getNumber() : "-", textFont));

            table.addCell(new Phrase(iwrb.getLocalizedString("email", "Email"), labelFont));
            table.addCell(new Phrase(email != null ? email.getEmailAddress() : "-", textFont));

            table.addCell(new Phrase(""));
            table.addCell(new Phrase(""));
            table.addCell(new Phrase(""));
            table.addCell(new Phrase(""));
        }

        table.addCell(new Phrase(iwrb.getLocalizedString("case_nr", "Case nr."), labelFont));
        table.addCell(new Phrase(theCase.getPrimaryKey().toString(), textFont));

        if (getCasesBusiness(iwc).useTypes()) {
            table.addCell(new Phrase(iwrb.getLocalizedString("case_type", "Case type"), labelFont));
            table.addCell(new Phrase(type.getName(), textFont));
        }

        if (parentCategory != null) {
            table.addCell(new Phrase(iwrb.getLocalizedString("case_category", "Case category"), labelFont));
            table.addCell(new Phrase(parentCategory.getLocalizedCategoryName(locale), textFont));

            table.addCell(new Phrase(iwrb.getLocalizedString("sub_case_category", "Case category"), labelFont));
            table.addCell(new Phrase(category.getLocalizedCategoryName(locale), textFont));
        } else {
            table.addCell(new Phrase(iwrb.getLocalizedString("case_category", "Case category"), labelFont));
            table.addCell(new Phrase(category.getLocalizedCategoryName(locale), textFont));
        }

        table.addCell(new Phrase(iwrb.getLocalizedString("created_date", "Created date"), labelFont));
        table.addCell(new Phrase(created.getLocaleDateAndTime(locale, IWTimestamp.SHORT, IWTimestamp.SHORT),
                textFont));

        if (theCase.getSubject() != null) {
            table.addCell(new Phrase(iwrb.getLocalizedString("subject", "Subject"), labelFont));
            table.addCell(new Phrase(theCase.getSubject(), textFont));
        }

        table.addCell(new Phrase(iwrb.getLocalizedString("message", "Message"), labelFont));
        table.addCell(new Phrase(theCase.getMessage(), textFont));

        if (theCase.getReference() != null) {
            table.addCell(new Phrase(iwrb.getLocalizedString("reference", "Reference"), labelFont));
            table.addCell(new Phrase(theCase.getReference(), textFont));
        }

        table.setWidthPercentage(100);
        document.add(table);

        document.close();
        try {
            mos.close();
        } catch (Exception ex) {
            ex.printStackTrace();
        }

        buffer.setMimeType("application/pdf");
        return buffer;

    } catch (Exception ex) {
        ex.printStackTrace();
    }

    return null;
}