Example usage for com.lowagie.text.pdf FontSelector process

List of usage examples for com.lowagie.text.pdf FontSelector process

Introduction

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

Prototype

public Phrase process(String text) 

Source Link

Document

Process the text so that it will render with a combination of fonts if needed.

Usage

From source file:ilarkesto.integration.itext.Paragraph.java

License:Open Source License

@Override
public Element getITextElement() {
    com.lowagie.text.Paragraph p = new com.lowagie.text.Paragraph();
    float maxSize = 0;
    for (AParagraphElement element : getElements()) {
        if (element instanceof TextChunk) {
            TextChunk textChunk = (TextChunk) element;
            FontStyle fontStyle = textChunk.getFontStyle();

            FontSelector fontSelector = createFontSelector(fontStyle.getFont(), fontStyle);

            String text = textChunk.getText();
            Phrase phrase = fontSelector.process(text);
            p.add(phrase);/*from  w w w. ja  va 2s  .co m*/

            float size = (fontStyle.getSize() * 1.1f) + 1f;
            if (size > maxSize)
                maxSize = PdfBuilder.mmToPoints(size);
        } else if (element instanceof Image) {
            Image image = (Image) element;
            com.lowagie.text.Image itextImage;
            try {
                itextImage = image.getITextElement();
            } catch (Exception ex) {
                log.warn("Including image failed:", image, ex);
                continue;
            }

            if (image.getAlign() != null) {
                itextImage.setAlignment(Image.convertAlign(image.getAlign()) | com.lowagie.text.Image.TEXTWRAP);
                p.add(itextImage);
            } else {
                Chunk chunk = new Chunk(itextImage, 0, 0);
                p.add(chunk);
                float size = image.getHeight() + 3;
                if (size > maxSize)
                    maxSize = size;
            }

        } else {
            throw new RuntimeException("Unsupported paragraph element: " + element.getClass().getName());
        }
    }
    p.setLeading(maxSize);
    p.setSpacingBefore(PdfBuilder.mmToPoints(spacingTop));
    p.setSpacingAfter(PdfBuilder.mmToPoints(spacingBottom));
    if (align != null)
        p.setAlignment(convertAlign(align));
    if (height <= 0)
        return p;

    // wrap in table
    PdfPCell cell = new PdfPCell();
    cell.setBorder(0);
    cell.setFixedHeight(PdfBuilder.mmToPoints(height));
    cell.addElement(p);
    PdfPTable table = new PdfPTable(1);
    table.setWidthPercentage(100);
    table.addCell(cell);
    return table;
}

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

License:Open Source License

private void addTextPart(String text, Phrase bodyPhrase, FontSelector fontSelector) {
    if (StringUtils.isNotEmpty(text)) {
        bodyPhrase.add(fontSelector.process(StringUtils.defaultString(text)));
    }//  www  .ja  va  2  s  . c o  m
}

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();/*  w w w  .  j a v a 2s .  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.nosleep.superanalyzer.Share.java

License:Open Source License

public static void saveListOfAlbumsAsPdf(JFrame window, Analysis analysis, JProgressBar progressBar) {
    File file = askForFile(window, "pdf");
    if (file == null)
        return;/*from w w  w  . j a va 2  s .c o m*/

    Hashtable albums = analysis.getHash(Analysis.KIND_ALBUM);

    DecimalFormat timeFormat = new DecimalFormat("0.0");

    StringPair list[] = new StringPair[albums.size()];
    Enumeration keys = albums.keys();
    Integer index = 0;
    String regex = Album.SeparatorRegEx;
    while (keys.hasMoreElements()) {
        String albumartist = (String) keys.nextElement();
        String[] parts = albumartist.split(regex);
        StringPair pair = new StringPair(parts[1], parts[0]);
        list[index] = pair;
        index++;
    }

    Arrays.sort(list, new StringPairComparator());

    int done = 0;
    progressBar.setMinimum(0);
    progressBar.setMaximum(list.length);

    String infoString = NumberFormat.getInstance().format(list.length) + " ";
    if (list.length == 1)
        infoString += Misc.getString("ALBUM") + ", ";
    else
        infoString += Misc.getString("ALBUMS") + ", ";
    DateFormat dateFormat = new SimpleDateFormat().getDateInstance(DateFormat.SHORT);
    infoString += "created on " + dateFormat.format(Calendar.getInstance().getTime());

    try {
        String tmpPath = System.getProperty("java.io.tmpdir") + "/image.png";

        // create the pdf document object
        Document document = new Document();

        // create a writer that listens to the document
        // and directs a PDF-stream to a file
        PdfWriter.getInstance(document, new FileOutputStream(file));

        // we open the document
        document.open();

        Font titleFont = FontFactory.getFont(FontFactory.HELVETICA, 18, Font.NORMAL,
                new Color(0x00, 0x00, 0x00));
        Paragraph p = new Paragraph(Misc.getString("MY_ALBUMS"), titleFont);
        p.setSpacingAfter(4);
        document.add(p);

        Font subtitleFont = FontFactory.getFont(FontFactory.HELVETICA, 8, Font.NORMAL,
                new Color(0x88, 0x88, 0x88));
        p = new Paragraph("The Super Analyzer by Nosleep Software", subtitleFont);
        p.setSpacingAfter(-2);
        document.add(p);

        p = new Paragraph(infoString, subtitleFont);
        p.setSpacingAfter(30);
        document.add(p);

        FontSelector albumSelector = new FontSelector();
        Color albumColor = new Color(0x55, 0x55, 0x55);
        albumSelector.addFont(FontFactory.getFont(FontFactory.HELVETICA, 8, Font.NORMAL, albumColor));
        Font albumAsianFont = FontFactory.getFont("MSung-Light", "UniCNS-UCS2-H", BaseFont.NOT_EMBEDDED);
        albumAsianFont.setSize(8);
        albumAsianFont.setColor(albumColor);
        albumSelector.addFont(albumAsianFont);

        FontSelector artistSelector = new FontSelector();
        Color artistColor = new Color(0x77, 0x77, 0x77);
        artistSelector.addFont(FontFactory.getFont(FontFactory.HELVETICA, 8, Font.NORMAL, artistColor));
        Font artistAsianFont = FontFactory.getFont("MSung-Light", "UniCNS-UCS2-H", BaseFont.NOT_EMBEDDED);
        artistAsianFont.setSize(8);
        artistAsianFont.setColor(artistColor);
        artistSelector.addFont(artistAsianFont);

        for (index = 0; index < list.length; index++) {
            p = new Paragraph();
            p.setLeading(9);

            // separate the string into the album and artist parts

            Phrase phrase = albumSelector.process(list[index].Value);
            p.add(phrase);

            phrase = artistSelector.process(" " + Misc.getString("BY") + " " + list[index].Name);
            p.add(phrase);

            document.add(p);

            done++;
            progressBar.setValue(done);
        }

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

    } catch (DocumentException de) {
        System.err.println(de.getMessage());
    } catch (IOException ioe) {
        System.err.println(ioe.getMessage());
    }

}

From source file:optika.sql.java

public PdfPCell getCellWhite(String text, int alignment, int bottom) {
    PdfPCell cell = new PdfPCell();
    FontSelector selector = new FontSelector();
    com.lowagie.text.Font f1 = FontFactory.getFont(FontFactory.TIMES_ROMAN, 12);
    f1.setColor(Color.white);/*from  ww  w  . j av a2s . c om*/
    selector.addFont(f1);
    cell.addElement(selector.process(text));
    cell.setPadding(0);
    cell.setHorizontalAlignment(alignment);
    cell.setBorder(PdfPCell.NO_BORDER);
    cell.setPaddingBottom(bottom);
    return cell;
}

From source file:org.pz.platypus.plugin.pdf.PdfOutfile.java

License:Open Source License

/**
 * Emit a single character in the current font, size, etc. This is used to output
 * a character by its Unicode value and is called by PdfSymbol, which handles the
 * processing of symbols and special characters.
 *
 * @param ch char to be emitted/*from w w  w  . j  a  v  a2s.  c o  m*/
 * @param fontName fontName to use. If null, use current font.
 */
public void emitChar(final String ch, final String fontName) {
    assert (ch != null) : "ch parameter null in PdfOutfile.emitChar()";

    if (iTPara == null) {
        startNewParagraph();
    }

    FontSelector fs = new FontSelector();
    if (fontName == null || fontName.isEmpty()) {
        fs.addFont(pdfData.getFont().getItextFont());
    } else {
        PdfFont newFont = new PdfFont(pdfData, fontName, pdfData.getFont());
        fs.addFont(newFont.getItextFont());
    }

    Phrase phr = fs.process(ch);
    iTPara.add(phr);
}