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

Wayan

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.