Sinhala text not properly rendering in PDF output using iText7 in Java

163 Views Asked by At

I'm using the iText7 library in Java to generate a PDF document that contains Sinhala text.
I've followed the code example below to embed a custom Sinhala font and render the text properly.
However, when I run the code, the Sinhala text doesn't render correctly in the output PDF. Instead, it appears as garbled characters or boxes.
I've verified that the font file (NotoSansSinhala-VariableFont_wdth,wght.ttf) is present at the specified path.

Can someone help me identify what I might be doing wrong in my code or suggest a solution to properly render Sinhala text in the generated PDF using iText?
Any insights or corrections to my code would be greatly appreciated. Thank you!

package mlib;

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

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

public class App {

    public static void main(String[] args) throws IOException {
        try (PdfWriter writer = new PdfWriter("output.pdf");
             PdfDocument pdfDocument = new PdfDocument(writer)) {

            // Load font data and create a PdfFont object with the desired Sinhala font
            byte[] fontData = Files.readAllBytes(Paths.get("C:\\Users\\madushankag\\Desktop\\Sinhala_iText\\NotoSansSinhala-VariableFont_wdth,wght.ttf"));
            PdfFont sinhalaFont = PdfFontFactory.createFont(fontData, PdfEncodings.IDENTITY_H, EmbeddingStrategy.FORCE_EMBEDDED, false);
            

            // Open the document
            Document document = new Document(pdfDocument);

            //Add content with the Sinhala font
            String sinhalaText = "කොහොමද සැප සනිප?";
            Paragraph paragraph = new Paragraph(sinhalaText).setFont(sinhalaFont);
            document.add(paragraph);

            //Close the document
            document.close();

            System.out.println("PDF generation completed successfully.");
        }
    }
}

Output pdf file:

Output pdf file

0

There are 0 best solutions below