Search code examples
c#pdfitext7

How can I set my font on calibri via iText7?


I try to set my text on Calibri on my Pdf document but that doesn't work. How can I set my font on calibri via iText7? Fontconstant class only has limited fonts.


Solution

  • As mentioned, there is a whole chapter on fonts with more information on what you can do, what are the differences, etc.

    In a nutshell, you use CreateFont to load your font file.

    Something like this will allow you to set the font per Paragraph element:

        FontProgram fontProgram =
            FontProgramFactory.CreateFont(@"C:\temp\calibri.ttf");
        PdfFont calibri = PdfFontFactory.CreateFont(fontProgram, PdfEncodings.WINANSI);
        using (PdfDocument pdfDocument = new PdfDocument(new PdfWriter(DEST)))
        {
            Document document = new Document(pdfDocument);
            document.Add(new Paragraph("Hello World!").SetFont(calibri));
        }
    

    but you can also do it for the whole Document:

        FontProgram fontProgram =
            FontProgramFactory.CreateFont(@"C:\temp\calibri.ttf");
        PdfFont calibri = PdfFontFactory.CreateFont(fontProgram, PdfEncodings.WINANSI);
        using (PdfDocument pdfDocument = new PdfDocument(new PdfWriter(DEST)))
        {
            Document document = new Document(pdfDocument);
            document.SetFont(calibri);
            document.Add(new Paragraph("Hello World!"));
        }