Search code examples
javacssflying-saucer

Custom font is not working with itextrenderer in java


I have embedded my custom fonts in html with @font-face. This working with all browser but when I am trying to convert it to pdf through itextrender in java custom font is not working anymore its taking default fonts like Arial.

css code:

    @font-face {
        font-family: Subaru-Medium;
        src: url('fonts/Subaru-Medium.eot'); /* IE9 Compat Modes */
        src: url('fonts/Subaru-Medium.eot?#iefix') format('embedded-opentype'), /* IE6-IE8 */
             url('fonts/Subaru-Medium.ttf')  format('truetype'), /* Safari, Android, iOS */
             url('fonts/Subaru-Medium.svg#svgFontName') format('svg'); /* Legacy iOS */
        }

java code:

public static void writePDF(String HTMLfileName, String PDFFileName, String WhereToSave,String fontDirectory)
    {
        try
        {
            String url = new File(HTMLfileName).toURI().toURL().toString();
            String outputFile = WhereToSave+PDFFileName;
            OutputStream os = new FileOutputStream(outputFile);

            ITextRenderer renderer = new ITextRenderer();
            ITextFontResolver fontResolver=renderer.getFontResolver();
                  fontResolver.addFont("C:\\Users\\benay.debnath\\Desktop\\htmltemplate\\fonts\\Subaru-Medium.ttf", true);

                // fontResolver.addFontDirectory(fontDirectory, true);
                SharedContext scontext=renderer.getSharedContext();
                // scontext.setDPI(72);
                scontext.setDotsPerPixel(12);
                renderer.setDocument(url);
                renderer.layout();
                renderer.createPDF(os);
                os.close();
                System.out.println("status:$:true^#^message:$:PDF    Genarated^#^fileName:$:"+outputFile);
        }catch (Exception e) {
            System.out.println("status:$:false^#^message:$:"+e.getMessage());
        }
    }

Any one can help me to find what I am doing wrong? help much appreciated.


Solution

  • This issue has resolved, the problem was in css I mentioned font-family:"Subaru-Medium" in font file(.ttf) font name was "Subaru Medium" so it was not working. Now its working fine :)