我正在使用 wkhtmltopdf.exe 将 HTML 转换为 PDF,使用下面的源代码。问题是 - PDF 显示“?” 代替所有非英文字符,如中文、日文、俄文、阿拉伯文。当输出为 HTML 时,字符会正确显示。我尝试为 HTML 设置不同的编码(utf-8、utf-16、gb2312),但 PDF 不会呈现非英语语言。
我在 wkhtmltopdf 论坛上阅读了有关在服务器上安装中文字体的信息,但看起来它们不适用于 Windows 服务器环境。此外,字体似乎在服务器上可用,因为 HTML 正确呈现?
有什么想法让它发挥作用吗?
代码:
private void WritePDF(string html)
{
string inFileName,
outFileName,
tempPath;
Process p;
System.IO.StreamWriter stdin;
ProcessStartInfo psi = new ProcessStartInfo();
tempPath = Request.PhysicalApplicationPath
+ ConfigurationManager.AppSettings[Constants.AppSettings.ExportToPdfTempFolder];
inFileName = Session.SessionID + ".htm";
outFileName = Session.SessionID + ".pdf";
// run the conversion utility
psi.UseShellExecute = false;
psi.FileName = Server.MapPath(ConfigurationManager.AppSettings[Constants.AppSettings.ExportToPdfExecutablePath]);
psi.CreateNoWindow = true;
psi.RedirectStandardInput = true;
psi.RedirectStandardOutput = true;
psi.RedirectStandardError = true;
//psi.StandardOutputEncoding = System.Text.Encoding.gb;
// note that we tell wkhtmltopdf to be quiet and not run scripts
// NOTE: I couldn't figure out a way to get both stdin and stdout redirected so we have to write to a file and then clean up afterwards
psi.Arguments = "-q -n - " + tempPath + outFileName;
p = Process.Start(psi);
try
{
stdin = p.StandardInput;
stdin.AutoFlush = true;
stdin.Write(html);
stdin.Close();
if (p.WaitForExit(15000))
{
// NOTE: the application hangs when we use WriteFile (due to the Delete below?); this works
Response.BinaryWrite(System.IO.File.ReadAllBytes(tempPath + outFileName));
}
}
finally
{
p.Close();
p.Dispose();
}
// delete the pdf
System.IO.File.Delete(tempPath + outFileName);
}