简体   繁体   中英

Display Chinese Text in iTextSharp pdf from html c#

I want to display chinese text from html to pdf by using itextsharp in c#

Text in HTML is properly visible but when i tried to make pdf from Xml Parser in iTextSharp it does not show me chinese texts.

UTF8 encoding is not working properly. I also given Encoding.UTF8 but it also not worked.

Below are my code to generate PDF from html.

 public static byte[] HtmlToPDFConvert(string baseHtml, Rectangle pageSize)
 {
        Stream htmlStream = new MemoryStream(Encoding.UTF8.GetBytes(baseHtml ?? ""));

        Document pdfDoc = new Document(pageSize, 18f, 18f, 18f, 18f);
        using (MemoryStream memoryStream = new MemoryStream())
        {
            PdfWriter writer = PdfWriter.GetInstance(pdfDoc, memoryStream);
            pdfDoc.Open();

            XMLWorkerHelper.GetInstance().ParseXHtml(writer, pdfDoc, htmlStream, null, Encoding.UTF8, FontFactory.FontImp);
            pdfDoc.Close();

            byte[] bytes = memoryStream.ToArray();
            memoryStream.Close();

            return bytes;
        }
 }

Since Xmlworker has been deprecated by pdfHTML , I've used it instead.

The only trick is to point to a font that supports the glyphs you want to use.

ConverterProperties props = new ConverterProperties();
FontProvider fontProvider = new DefaultFontProvider(true, true, true);
fontProvider.AddFont("fonts/NotoSansCJKjp-Regular.otf");
props.SetFontProvider(fontProvider);
PdfDocument doc = new PdfDocument(new PdfWriter(DEST));
HtmlConverter.ConvertToPdf(new FileStream(ORIG, FileMode.Open), doc, props);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM