C# – Using different fonts in PDF using iTextSharp and PDFStamper

citextsharppdf

I'm using iTextSharp to load an existing PDF and adding text using the PdfStamper. I want full control over the text, meaning I want to be able to control the font (only TrueType), font size and coordinates. Right now, I'm using ShowTextAligned to add text to certain coordinaties and setFontAndSize to set the font and font size. This is my code to add text:

    private void AddText(BaseFont font, string text, int x, int y, int size)
    {
        pdf.BeginText();
        pdf.SetFontAndSize(font, size);
        pdf.ShowTextAligned(PdfContentByte.ALIGN_LEFT, text, x, y, 0);
        pdf.EndText();
    }

The following function is used to load the TrueType font:

    public BaseFont GetFont(string font, string encoding)
    {
        if (!(font.EndsWith(".ttf") || font.EndsWith(".TTF")))
            font += ".ttf";

        BaseFont basefont;

        basefont = BaseFont.CreateFont(ConfigurationManager.AppSettings["fontdir"] + font, encoding, BaseFont.NOT_EMBEDDED);

        if (basefont == null)
            throw new Exception("Could not load font '" + font + "' with encoding '" + encoding + "'");

        return basefont;
    }

The following code is used to load the existing PDF:

        Stream outputPdfStream = Response.OutputStream;
        PdfReader pdfReader = new PdfReader(new RandomAccessFileOrArray(HttpContext.Current.Request.MapPath("PdfTemplates/" + ConfigurationManager.AppSettings["pdf_template"])), null);
        PdfStamper pdfStamper = new PdfStamper(pdfReader, outputPdfStream);

        pdf = pdfStamper.GetOverContent(1);

This all works perfectly, except when I try to use different fonts. So when AddText is called multiple times with different fonts, the PDF will display a generic error when openend. I wonder if it is possible to use different fonts using the ShowTextAligned function and if it is, how?

Best Answer

Not really, no. It'll only handle one font at a time. Out of curiosity what are you doing to get bad pdf output? I'd like to see your code.

Have a look at ColumnText instead. There are quite a few examples floating around and its well-covered in "iText in Action 2nd edition". All the samples from the book are available on line.

Related Topic