简体   繁体   中英

Convert html with Persian characters to pdf using iTextSharp

I have a Html file that contains Persian characters. I eant to convert it to pdf using iTextSharp.

I have written these lines to do it:

string HTML = System.IO.File.ReadAllText(Server.MapPath("~/Misc/Html.txt"));
Document document = new Document();
string fontpath = Server.MapPath("~/Fonts/BNazanin.ttf");
iTextSharp.text.FontFactory.Register(fontpath);
PdfWriter.GetInstance(document, new FileStream(Server.MapPath("~/Files/Pdf/test.pdf"), FileMode.Create));
document.Open();
try
{
    iTextSharp.text.html.simpleparser.StyleSheet styles = new iTextSharp.text.html.simpleparser.StyleSheet();
    styles.LoadTagStyle(HtmlTags.BODY, HtmlTags.FACE, "BNazanin");
    styles.LoadTagStyle(HtmlTags.BODY, HtmlTags.ENCODING, BaseFont.IDENTITY_H);
    List<IElement> list = HTMLWorker.ParseToList(new StringReader(HTML), styles);
    for (int k = 0; k < list.Count; k++)
    {
        document.Add((IElement)list[k]);
    }
    document.Close();
}
catch
{
    document.Close();
}

And the Html.txt is something like this:

<span>گرید</span>

But the output is something like this

دیرگ

instead of

گرید

Long time since I did work with Right-to-Left rendering of text but you should be able to set the RunDirection property to reflect the direction you need.

PdfPTable pdfTable = new PdfPTable(1);
pdfTable.RunDirection = PdfWriter.RUN_DIRECTION_RTL;

Then it will be possible to add text in a cell that you add to the table, the cell will inherit the direction so it should render correctly.

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