Search code examples
javapdfitextfont-face

not getting Font effect in PDF when convert HTML To PDF file


Using this below Code i am Abel to convert a HTML text To PDF and my code can generate PDF File on particular location . but problem is...... i give font style in body tags so when PDF is generate i am not getting this font style effect in generate PDF ex.

 // Here On Body Tag I have given a Zurich BT font style
 StyleSheet styles = new StyleSheet();
 //styles.loadTagStyle("body", "font-family", "Zurich BT");
 styles.loadTagStyle("body", "font", "Zurich BT");

so here my font style is Zurich BT but i have just got plane simple text on generate PDF not get any effect on text.

i am using itextpdf-5.1.1 version and my code is....

            ByteArrayOutputStream baos = new ByteArrayOutputStream();   
            Document pdfDocument = new Document();

            Reader htmlreader = new StringReader("<html><head></head><body>"
                    + " <font> HELLO MY NAME IS JIMIT TANK </font> </html></body>");

            PdfWriter.getInstance(pdfDocument, baos);

            pdfDocument.open();

            // Here On Body Tag I am giving a Zurich BT font style
            StyleSheet styles = new StyleSheet();
            //styles.loadTagStyle("body", "font-family", "Zurich BT");
            styles.loadTagStyle("body", "font", "Zurich BT");

            ArrayList arrayElementList =    HTMLWorker.parseToList(htmlreader,styles);

            for (int i = 0; i < arrayElementList.size(); ++i) {
                Element e = (Element) arrayElementList.get(i);
                pdfDocument.add(e);
            }
            pdfDocument.close();
            byte[] bs = baos.toByteArray();
            String pdfBase64 = Base64.encodeBytes(bs); //output
            File pdfFile = new File("c:/pdfExample.pdf");
            FileOutputStream out = new FileOutputStream(pdfFile);
            out.write(bs);
            out.close();

Solution

  • Use iTextSharp Paragraph class and set font and style to it like this

    Document doc = new Document(PageSize.A4);
    Paragraph paraReportTitle = new Paragraph();
                    //paraReportTitle.Font = new Font(Font.FontFamily.HELVETICA, 13f, Font.BOLD);
                    paraReportTitle.Font = new Font(Font.FontFamily.HELVETICA, 8f, Font.NORMAL);
    
    doc.Add(paraReportTitle);
    

    Setting style to html will not work.

    You can also use the BaseFont class in iTextSharp