Skip to content

Multi byte character language support with TTF fonts

Gajendra kumar edited this page Jan 29, 2020 · 5 revisions

TrueTypeFont fonts are used to write content in languages having multi-byte characters like Hindi. Content needs to be processed while being written to PDF with typographic rules like ghyph substitution according to TrueTypeFonts. OpenPDF can leverage Apache FOP for processing typographic rules.

Enabling typographic rule processing

Add below dependencies along with OpenPDF for enabling typographic rule processing:

           <dependency>
               <groupId>org.apache.xmlgraphics</groupId>
               <artifactId>fop</artifactId>
                <version>2.3</version>
            </dependency>
            <dependency>
                <groupId>org.apache.xmlgraphics</groupId>
                <artifactId>xmlgraphics-commons</artifactId>
                <version>2.3</version>
           </dependency>

Example:

    import com.lowagie.text.*;
    import com.lowagie.text.pdf.PdfWriter;

    import java.io.FileOutputStream;
    import java.io.IOException;

    public class HelloWorld {

        public static void main(String[] args) {

            // Register TrueTypeFont which supports Hindi
            FontFactory.register("C:\\Windows\\Fonts\\NIRMALA.TTF");
            Document document = new Document();
            try {
                PdfWriter.getInstance(document,
                        new FileOutputStream("D:\\workspace\\TMP\\out\\HelloWorld.pdf"));

                document.open();
                document.add(new Chunk(
                        "नमस्ते",
                        FontFactory.getFont("nirmala ui", "Identity-H",false,10,0,null)));
            } catch (DocumentException de) {
                System.err.println(de.getMessage());
            } catch (IOException ioe) {
                System.err.println(ioe.getMessage());
            }
            document.close();
    
        }
    }