Apply Different Fonts in PDF in Java

Spire.PDF supports Standard fonts, TrueType fonts and CJK fonts. This tutorial shows you how to apply these fonts when drawing text on a PDF page in Java.

import com.spire.pdf.graphics.*;

public class PdfFonts {

    public static void main(String[] args) {

        //create a pdf document
        PdfDocument doc = new PdfDocument();

        //add a page
        PdfPageBase page = doc.getPages().add();

        //create a brush
        PdfBrush brush = PdfBrushes.getBlack();

        //initialize y coordinate
        float y = 30;

        //draw text using standard fonts
        PdfFont standardFont = new PdfFont(PdfFontFamily.Helvetica, 14f);
        page.getCanvas().drawString("Standard Font - Helvetica", standardFont, brush, 0, y);
        standardFont = new PdfFont(PdfFontFamily.Times_Roman, 14f);
        page.getCanvas().drawString("Standard Font - Times_Roman", standardFont, brush, 0, (y = y + 16));
        standardFont = new PdfFont(PdfFontFamily.Courier, 14f);
        page.getCanvas().drawString("Standard Font - Courier", standardFont, brush, 0, (y = y + 16));

        // draw text using truetype font
        java.awt.Font font = new java.awt.Font("Arial", java.awt.Font.BOLD, 14);
        PdfTrueTypeFont trueTypeFont = new PdfTrueTypeFont(font);
        page.getCanvas().drawString("TrueType Font - Arial", trueTypeFont, brush, 0, (y = y + 30f));

        // draw text using private font
        String fontFileName = "C:\\Users\\Administrator\\Desktop\\Khadija.ttf";
        trueTypeFont = new PdfTrueTypeFont(fontFileName, 14f);
        page.getCanvas().drawString("Private Font - Khadija", trueTypeFont, brush, 0, (y = y + 30f));

        // draw text using cjk fonts
        PdfCjkStandardFont cjkFont = new PdfCjkStandardFont(PdfCjkFontFamily.Monotype_Hei_Medium, 14f);
        page.getCanvas().drawString("How to say 'Font' in Chinese? \u5B57\u4F53", cjkFont, brush, 0, (y = y + 30f));
        cjkFont = new PdfCjkStandardFont(PdfCjkFontFamily.Hanyang_Systems_Gothic_Medium, 14f);
        page.getCanvas().drawString("How to say 'Font' in Japanese? \u30D5\u30A9\u30F3\u30C8", cjkFont, brush, 0, (y = y + 16f));
        cjkFont = new PdfCjkStandardFont(PdfCjkFontFamily.Hanyang_Systems_Shin_Myeong_Jo_Medium, 14f);
        page.getCanvas().drawString("How to say 'Font' in Korean? \uAE00\uAF34", cjkFont, brush, 0, (y = y + 16f));

        //save to file.
        doc.saveToFile("Fonts.pdf");
        doc.close();
    }
}

Apply Different Fonts in PDF in Java