首页 > 解决方案 > 使用 iTextSharp 将 HTML 转换为 PDF 不支持阿拉伯语

问题描述

我正在使用 iTextSharp 将 HTML 内容转换为 PDF 文件,但是当阿拉伯语中的 HTML 内容是这样时我遇到了问题: 在此处输入图像描述

这就是我的代码:

Public Shared Function ExportToPDF(lang As String) As String
    Try
        Dim stringWrite As New System.IO.StringWriter
        Dim htmlWrite As New HtmlTextWriter(stringWrite)

        divExport.RenderControl(htmlWrite)

        Dim text As String
        text = String.Format("<html><head><style type='text/css'>{0}</style></head><body>{1}</body></html>", "body{font-color:red;}", stringWrite.ToString)
        Dim sr As New StringReader(text)
        Dim pdfDoc As New Document(PageSize.A4, 10.0F, 10.0F, 10.0F, 0.0F)
        Dim writer As PdfWriter = PdfWriter.GetInstance(pdfDoc, Response.OutputStream)
        pdfDoc.Open()

        XMLWorkerHelper.GetInstance().ParseXHtml(writer, pdfDoc, sr)
        pdfDoc.Close()
        Response.ContentType = "application/pdf"
        Response.AddHeader("content-disposition", "attachment;filename=FileName.pdf")
        Response.Cache.SetCacheability(HttpCacheability.NoCache)
        Response.Write(pdfDoc)
        Response.End()
    Catch ex As Exception

    End Try
    Return Nothing
End Function

div导出:

     <div id="divExport">
        <h1>Header</h1>
        <table>
         <tr>
        <td>Questions</td><td>الاسئلة</td>
        </tr>
        </table>
        <h2>Questions Answers</h2>
        <table>
        <tr>
        <td>Device Type</td><td>جهاز الكمبيوتر</td>
        </tr>
        </table>
        </div>

标签: c#htmlasp.netvb.netitext

解决方案


XMLWorker不是为能够处理阿拉伯文本而设计的,据我所知(前 iText 员工)它无法处理阿拉伯文本。

更好的解决方案是使用pdfHTML(它是 iText 7 产品系列的一部分,并将 HTML5 和 CSS3 转换为 PDF)。

为了正确渲染阿拉伯语(以及其他非西方文字),您还需要pdfCalligraph专门设计用于正确渲染非西方文字的 .

这个链接提供了更多的解释pdfCalligraph


推荐阅读