将HTML(MVC Razor页面)转换为非UTF8字符的PDF时遇到两个问题。
1)生成带有中文字符的PDF 2)每当我启用添加CSS文件时,我总是会遇到异常“输入字符串格式不正确”。但是当我评论我自己的CSS并使用GetDefaultCSS时,错误没有出现并且正在生成PDF但是中文字符显示为问号(?)
以下是代码:
public static byte[] BuildPDFContent<T>(T model, string template, ControllerContext context)
{
CoreController controller = (CoreController)context.Controller;
var html = controller.RenderRazorViewToString(template, model);
MemoryStream msInput = new MemoryStream(ASCIIEncoding.Default.GetBytes(html));
MemoryStream msOutput = new MemoryStream();
string fontAwesomeCss = HttpContext.Current.Server.MapPath("/Content/css/font-awesome.min.css");
string bootstrapCss = HttpContext.Current.Server.MapPath("/Content/css/bootstrap.css");
string siteCss = HttpContext.Current.Server.MapPath("/Content/css/site.css");
Document doc = new Document(iTextSharp.text.PageSize.A4);
doc.SetMargins(doc.LeftMargin, doc.RightMargin, 35, 0);
PdfWriter pdfWriter = PdfWriter.GetInstance(doc, msOutput);
doc.Open();
var tagProcessors = (DefaultTagProcessorFactory)Tags.GetHtmlTagProcessorFactory();
tagProcessors.RemoveProcessor(HTML.Tag.IMG); // remove the default processor
tagProcessors.AddProcessor(HTML.Tag.IMG, new CustomImageTagProcessor()); // use our new processor
CssFilesImpl cssFiles = new CssFilesImpl();
cssFiles.Add(XMLWorkerHelper.GetCSS(new FileStream(fontAwesomeCss, FileMode.Open)));
cssFiles.Add(XMLWorkerHelper.GetCSS(new FileStream(bootstrapCss, FileMode.Open)));
cssFiles.Add(XMLWorkerHelper.GetCSS(new FileStream(siteCss, FileMode.Open)));
//cssFiles.Add(XMLWorkerHelper.GetInstance().GetDefaultCSS());
StyleAttrCSSResolver cssResolver = new StyleAttrCSSResolver(cssFiles);
var hpc = new HtmlPipelineContext(new CssAppliersImpl(new UnicodeFontFactory()));
hpc.SetAcceptUnknown(true).AutoBookmark(true).SetTagFactory(tagProcessors); // inject the tagProcessors
HtmlPipeline htmlPipeline = new HtmlPipeline(hpc, new PdfWriterPipeline(doc, pdfWriter));
IPipeline pipeline = new CssResolverPipeline(cssResolver, htmlPipeline);
XMLWorker worker = new XMLWorker(pipeline, true);
XMLParser xmlParse = new XMLParser(true, worker);
xmlParse.Parse(msInput);
doc.Close();
return msOutput.ToArray();
}
private class UnicodeFontFactory : FontFactoryImp
{
private static readonly string FontPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Fonts),
"arialuni.ttf");
private readonly BaseFont _baseFont;
public UnicodeFontFactory()
{
_baseFont = BaseFont.CreateFont(FontPath, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
}
public override Font GetFont(string fontname, string encoding, bool embedded, float size, int style, BaseColor color,
bool cached)
{
return new Font(_baseFont, size, style, color);
}
}