Elvin Mammadov
Elvin Mammadov

Reputation: 27397

Html to pdf some characters are missing (itextsharp) in Asp.Net MVC Application

I want to export razor view to pdf by using the itextsharp library. The problem is that some turkish characters such as İ,ı,Ş,ş etc... are missing in the pdf document. The code used to export the pdf is:

  public PdfActionResult(object model)
    {
        Model = model;
    }
 public override void ExecuteResult(ControllerContext context)
    {
        IView viewEngineResult;
        ViewContext viewContext;

        if (ViewName == null)
        {
            ViewName = context.RouteData.GetRequiredString("action");
        }

        context.Controller.ViewData.Model = Model;


        var workStream = new MemoryStream();
        var document = new Document();

        PdfWriter writer = PdfWriter.GetInstance(document, workStream);
        writer.CloseStream = false;

        document.Open();

        viewEngineResult = ViewEngines.Engines.FindView(context, ViewName, null).View;
        var sb = new StringBuilder();
        TextWriter tr = new StringWriter(sb);

        viewContext = new ViewContext(context, viewEngineResult, context.Controller.ViewData,
        context.Controller.TempData, tr);
        viewEngineResult.Render(viewContext, tr);

        CultureInfo ci = new CultureInfo("az-Latn-AZ");
        Encoding enc = Encoding.GetEncoding(ci.TextInfo.ANSICodePage);

        Stream stream = new MemoryStream(enc.GetBytes(sb.ToString()));

        XMLWorkerHelper.GetInstance().ParseXHtml(writer, document, stream, null);

        document.Close();

        new FileContentResult(workStream.ToArray(), "application/pdf").ExecuteResult(context);
    }
}

Then I access it as:

 public ActionResult StudentPdf(Guid studentId)
    {
        var model = _studentRepository.GetByIdGuid(studentId);

        return new PdfActionResult(model);
    }

Thanks for reply

Upvotes: 1

Views: 1523

Answers (1)

Vinit Patel
Vinit Patel

Reputation: 2474

by this way you can print all turkish character.

String htmlText = html.ToString();

        Document document = new Document();

        string filePath = HostingEnvironment.MapPath("~/Content/Pdf/");
        PdfWriter.GetInstance(document, new FileStream(filePath + "\\pdf-"+Name+".pdf", FileMode.Create));
        document.Open();

        iTextSharp.text.html.simpleparser.HTMLWorker hw = new iTextSharp.text.html.simpleparser.HTMLWorker(document);
        FontFactory.Register(Path.Combine(_webHelper.MapPath("~/App_Data/Pdf/arial.ttf")),  "Garamond");   // just give a path of arial.ttf 
        StyleSheet css = new StyleSheet();
        css.LoadTagStyle("body", "face", "Garamond");
        css.LoadTagStyle("body", "encoding", "Identity-H");
        css.LoadTagStyle("body", "size", "12pt");

        hw.SetStyleSheet(css);

         hw.Parse(new StringReader(htmlText));

Hope this helps Regards, Vinit Patel

Upvotes: 2

Related Questions