Matija Grcic
Matija Grcic

Reputation: 13381

iTextSharp cyrillic letters

I used http://www.codeproject.com/Articles/260470/PDF-reporting-using-ASP-NET-MVC3 to generate pdf files from my razor views and it works great but i can't display cyrillic letters like č,ć . I tried everything and i can't get it working.

I must somehow tell the HtmlWorker to use different font:

 using (var htmlViewReader = new StringReader(htmlText))
                    {                       
                        using (var htmlWorker = new HTMLWorker(pdfDocument))
                        {                            

                            htmlWorker.Parse(htmlViewReader);
                        }
                    }

Can you help?

EDIT:

I was missing one line

styleSheet.LoadTagStyle(HtmlTags.BODY, HtmlTags.ENCODING, BaseFont.IDENTITY_H);

The rest was the same as the answer.

Upvotes: 4

Views: 6820

Answers (1)

Daniel
Daniel

Reputation: 990

If you change the Render method of StandardPdfRenderer to the following snippet, it should work:

public byte[] Render(string htmlText, string pageTitle)
{
    byte[] renderedBuffer;

    using (var outputMemoryStream = new MemoryStream())
    {
        using (var pdfDocument = new Document(PageSize.A4, HorizontalMargin, HorizontalMargin, VerticalMargin, VerticalMargin))
        {
            string arialuniTff = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Fonts), "ARIALUNI.TTF");
            iTextSharp.text.FontFactory.Register(arialuniTff);

            PdfWriter pdfWriter = PdfWriter.GetInstance(pdfDocument, outputMemoryStream);

            pdfWriter.CloseStream = false;
            pdfWriter.PageEvent = new PrintHeaderFooter { Title = pageTitle };
            pdfDocument.Open();

            using (var htmlViewReader = new StringReader(htmlText))
            {
                using (var htmlWorker = new HTMLWorker(pdfDocument))
                {
                    var styleSheet = new iTextSharp.text.html.simpleparser.StyleSheet();
                    styleSheet.LoadTagStyle(HtmlTags.BODY, HtmlTags.FACE, "Arial Unicode MS");
                    styleSheet.LoadTagStyle(HtmlTags.BODY, HtmlTags.ENCODING, BaseFont.IDENTITY_H);
                    htmlWorker.SetStyleSheet(styleSheet);

                    htmlWorker.Parse(htmlViewReader);
                }
            }
        }

        renderedBuffer = new byte[outputMemoryStream.Position];
        outputMemoryStream.Position = 0;
        outputMemoryStream.Read(renderedBuffer, 0, renderedBuffer.Length);
    }

    return renderedBuffer;
}

Upvotes: 4

Related Questions