var pdfDest = "myfiles/" + "hello.pdf";var pdfWriter = newPdfWriter (pdfDest);var pdf = newPdfDocument (pdfWriter);var pageSize = PageSize.A4; //设置默认页面大小,css @page规则可覆盖这个
pdf.SetDefaultPageSize (pageSize);var mediaDeviceDescription = new MediaDeviceDescription (MediaType.PRINT); //指当前设备类型,如果是预览使用SCREEN
mediaDeviceDescription.SetWidth (pageSize.GetWidth ());var properties = newConverterProperties ();
properties.SetBaseUri ("htmls"); //设置根目录
properties.SetCharset ("utf-8");var provider = new DefaultFontProvider (true, true, true); //第三个参数为True,以支持系统字体,否则不支持中文
properties.SetFontProvider (provider);
properties.SetMediaDeviceDescription (mediaDeviceDescription);var dic = new Dictionary{
["{{ImageUrl}}"] = "./test_files/5687441010153797724.jpg",
["{{Title}}"] = "Colossal (2016) 中文字体",
["{{Director}}"] = "Directed by Nacho Vigalondo",
["{{Description}}"] = "Gloria is an out-of-work party girl forced to leave her life in New York City,and move back home. When reports surface that a giant creature isdestroying Seoul, she gradually comes to the realization that she issomehow connected to this phenomenon.",
["{{Imdb}}"] = "Read more about this movie on",
["{{Href}}"] = "www.imdb.com/title/tt4680182",
["{{HrefContent}}"] = "IMDB"};var htmlTemplate = File.ReadAllText ("htmls/hello.html");var match = Regex.Match (htmlTemplate, @"(.|\s)+?"); //匹配子模版
if (match == null)return;var template = match.Value.Substring ("".Length, match.Value.Length - "".Length);var names = new List { "张三", "李四", "王五"};var sb = new StringBuilder ("");foreach (var name innames) {
sb.Append (template.Replace ("{{Name}}", name)); //子模版赋值
}
sb.Append ("");
htmlTemplate= htmlTemplate.Replace (match.Value, sb.ToString ()); //完成子模版部分
var regex = new Regex (String.Join ("|", dic.Keys));var html = regex.Replace (htmlTemplate, m => dic[m.Value]); //模板字段赋值
HtmlConverter.ConvertToPdf (html, pdf, properties);