Nime Cloud
Nime Cloud

Reputation: 6395

How to use UTF-8 encoding in iTextSharp PDF Stamper?

I want to use UTF-8 instead of CP1250 to display national characters. I found AddParagraph method which supports UTF-8 but I couldn't find any stamper example.

This is the code snippet with CP1250:

        PdfReader reader = new PdfReader(templatePath);
        byte[] bytes;
        using (MemoryStream ms = new MemoryStream())
        {
            using (PdfStamper stamper = new PdfStamper(reader, ms))
            {
                PdfContentByte cb = stamper.GetOverContent(1);

                BaseFont bf = BaseFont.CreateFont(
                   BaseFont.COURIER_BOLD, 
                   BaseFont.CP1250, 
                   true);

                //Begin text command
                cb.BeginText();
                //Set the font information                        
                cb.SetFontAndSize(bf,12f);

                //Position the cursor for drawing
                cb.MoveText(field.X, field.Y);
                //Write some text
                cb.ShowText(field.Text);
                //End text command
                cb.EndText();

                //Flush the PdfStamper's buffer
                stamper.Close();
                //Get the raw bytes of the PDF
                bytes = ms.ToArray();
            }
        }

How can I use UTF-8?

Upvotes: 3

Views: 13595

Answers (1)

mkl
mkl

Reputation: 95918

If you require a wide range of characters from a single font, you most likely should use IDENTITY_H (or IDENTITY_V in case of vertical text) as encoding.

E.g.:

public const string FONT = "c:/windows/fonts/arialbd.ttf";
BaseFont bf = BaseFont.CreateFont(FONT, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);

Cf. the Webified iTextSharp Example UnicodeExample.cs for the use in context.

Upvotes: 8

Related Questions