How do I display emojis in a PDF document using iText 8?

Displaying emojis using iText 8 requires you to use a font that supports the unicode characters for emojis. By default, the most common fonts don’t support colorful emojis, but you can use some fonts like Segoe UI Emoji (which comes with Windows 10), Apple Color Emoji, NotoColorEmoji or FreeSerif to display black and white outlined emoji characters.

Here is a simple example of how to add an emojis using Segoe UI Emoji font. You can find the font file in C:\Windows\Fonts\ directory, and the file name is seguiemj.ttf. You need to add the seguiemj.ttf file to your project’s resources, in a Maven project, under the src/main/resources directory. Then, modify your code as follows:

package org.kodejava.itext;

import com.itextpdf.io.font.PdfEncodings;
import com.itextpdf.kernel.colors.DeviceRgb;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.kernel.font.PdfFont;
import com.itextpdf.kernel.font.PdfFontFactory;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.element.Paragraph;

import java.io.IOException;

public class DocumentWithEmoji {
    public static void main(String[] args) throws IOException {
        PdfWriter writer = new PdfWriter("emoji.pdf");
        PdfDocument pdf = new PdfDocument(writer);

        try (Document document = new Document(pdf)) {
            PdfFont fontEmoji = PdfFontFactory.createFont("seguiemj.ttf", PdfEncodings.IDENTITY_H);

            Paragraph paragraph = new Paragraph()
                    .add(new Paragraph("Hello ").setFont(fontEmoji).setFontSize(20))
                    .add(new Paragraph("\uD83D\uDE00").setFont(fontEmoji).setFontSize(20)
                            .setFontColor(new DeviceRgb(243, 58, 106)));

            document.add(paragraph);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Output:

Hello Emoji

In this example, “\uD83D\uDE00” is the Unicode surrogate pair for the grinning face emoji (😀). This code will result in a PDF document containing the text “Hello 😀”.

To depict different emojis, you would need their respective unicode characters. You can get those from various online sources such as the official Unicode website.

Remember, though, for colored emojis, you might need to use specific emoji fonts like Apple Color Emoji or NotoColorEmoji, and even then, support can be limited, since colored font rendering is not a standard PDF feature and the display can depend heavily on the viewer software.

Maven Dependencies

<dependency>
    <groupId>com.itextpdf</groupId>
    <artifactId>itext-core</artifactId>
    <version>8.0.2</version>
    <type>pom</type>
</dependency>

Maven Central

How do I style some texts in the Paragraph object in iText 8?

In iText 8, if you want to style only part of the text inside a Paragraph object, you can use the Text object to encapsulate the text that needs separate styling.

Here’s an example:

package org.kodejava.itext;

import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.kernel.font.PdfFont;
import com.itextpdf.kernel.font.PdfFontFactory;
import com.itextpdf.kernel.colors.DeviceRgb;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.element.Paragraph;
import com.itextpdf.layout.element.Text;
import com.itextpdf.io.font.constants.StandardFonts;

public class ParagraphTextExample {
    public static void main(String[] args) throws Exception {
        PdfWriter writer = new PdfWriter("styled-text.pdf");
        PdfDocument pdf = new PdfDocument(writer);

        try (Document document = new Document(pdf)) {

            PdfFont font = PdfFontFactory.createFont(StandardFonts.HELVETICA);

            // Create a Text object and style it
            Text text1 = new Text("This text is green and super bold. ")
                    .setFont(font)
                    .setFontSize(15)
                    .setFontColor(new DeviceRgb(0, 255, 0))
                    .setBold();

            // Create another Text object and style it differently
            Text text2 = new Text("This text is blue and italic. ")
                    .setFont(font)
                    .setFontSize(12)
                    .setFontColor(new DeviceRgb(0, 0, 255))
                    .setItalic();

            // Create another Text object and style it differently
            final String text = """
                    What's in a name? \
                    That which we call a rose by any other name \
                    would smell just as sweet.
                    """;
            Text text3 = new Text(text)
                    .setFont(font)
                    .setFontSize(20)
                    .setFontColor(new DeviceRgb(243, 58, 106))
                    .setBold()
                    .setItalic();

            // Add Text objects to a single Paragraph
            Paragraph paragraph = new Paragraph().add(text1).add(text2).add(text3);

            document.add(paragraph);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

In this example, three Text objects, text1, text2, and text3, are created with different styles. The Text objects are then added to a Paragraph object. As a result, the paragraph will have mixed styles, depending on the individual text elements.

Notably, you can apply a rich variety of styling on the Text objects, including font, size, color, background color, underlines, strike-through, superscripts, subscripts, and nearly any other style applicable to text.

Maven Dependencies

<dependency>
    <groupId>com.itextpdf</groupId>
    <artifactId>itext-core</artifactId>
    <version>8.0.2</version>
    <type>pom</type>
</dependency>

Maven Central

How do I install Calibri font in Ubuntu?

I need to create a Microsoft Word Mail Merge document in my Java Spring MVC application. But running it in Ubuntu server resulting in a document that missing the default font use in the document, which is the Calibri font. So I need to install the font in Ubuntu to make the document looks as expected.

Here what I need to do to install the font in my Ubuntu box. Starts by updating the repository package list to get latest packages information for upgrades or new package installation.

sudo apt-get update

Then install FontForge in our system. FontForge is a free and open source font editor, but in this case it will help to do the font conversion in the installation script on the upcoming step.

sudo apt-get install fontforge

Install the Microsoft Cabinet file un-packer. This is required for the next script to successfully install the fonts.

sudo apt-get install cabextract

The following script will install Microsoft Vista TrueType Fonts (TTF) in Ubuntu. It includes the following fonts, Calibri, Cambria, Candara, Consolas, Constantia, and Corbel.

wget https://gist.githubusercontent.com/maxwelleite/10774746/raw/ttf-vista-fonts-installer.sh -q -O - | sudo bash

Run the next command to see if the font successfully installed. You will see the Calibri fonts in the result if the fonts successfully installed.

fc-list | grep Calibri

Here are the list of installed Calibri fonts.

/usr/share/fonts/truetype/vista/calibriz.ttf: Calibri:style=Bold Italic
/usr/share/fonts/truetype/vista/calibrii.ttf: Calibri:style=Italic
/usr/share/fonts/truetype/vista/calibrib.ttf: Calibri:style=Bold
/usr/share/fonts/truetype/vista/calibri.ttf: Calibri:style=Regular

How to Install Consolas Font in Mac OS X?

Here are the instructions to install Microsoft Consolas Font on Mac OS X.

  • You need to install brew first.
  • Type-in the following commands.
brew install cabextract
cd ~/Downloads
mkdir Consolas
cd Consolas
curl -LO https://sourceforge.net/projects/mscorefonts2/files/cabs/PowerPointViewer.exe
cabextract PowerPointViewer.exe
cabextract ppviewer.cab
open CONSOLA*.TTF
  • Press Install Font button to install the fonts.

How do I draw a string in Java 2D?

The code snippet below show you how to draw a string using Graphics2D. The drawString() method accept the string to be drawn and their x and y coordinate. Here you can also see how to set the antialiasing mode using the setRenderingHint() method.

package org.kodejava.awt.geom;

import javax.swing.*;
import java.awt.*;

public class DrawString extends JPanel {
    public static void main(String[] args) {
        JFrame frame = new JFrame();
        frame.setTitle("Draw String Demo");
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.add(new DrawString());
        frame.pack();
        frame.setSize(420, 300);
        frame.setVisible(true);
    }

    @Override
    public void paint(Graphics g) {
        Graphics2D g2 = (Graphics2D) g;

        // Define rendering hint, font name, font style and font size
        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        g2.setFont(new Font("Segoe Script", Font.BOLD + Font.ITALIC, 40));
        g2.setPaint(Color.ORANGE);

        // Draw Hello World String
        g2.drawString("Hello World!", 50, 100);
    }
}

Run the snippet, and you’ll see the following screen:

Draw 2D String

Draw 2D String