在使用itextsharp实现 html 2 pdf时,发现display:none无效。如
<div style="display: none">
应该隐藏
</div>
结果转换出来的Pdf竟然显示出来了“应该隐藏”,很奇怪。
在stackoverflow上查找到了类似问题,https://stackoverflow.com/questions/46612643/itextsharp-and-xmlworker-displaynone-is-not-working
原因在于itextsharp和itextsharp对于css解析时存在bug。因此切换成htmlpdf实现方式,也是itext开发的,基本内容和原来的itextsharp差不多,不要顾忌。
通过nuget安装htmlpdf,
/// <summary>
/// 通过Html来生成pdf,测试Html样式
/// </summary>
/// <param name="html">要转换成pdf的html</param>
/// <returns></returns>
[HttpGet]
[Route("TestHtmlToPdf")]
public HttpResponseMessage TestHtmlToPdf(string html)
{
// pdfHTML specific code
using (var memberStream = new MemoryStream())
{
ConverterProperties converterProperties = new ConverterProperties();
converterProperties.SetFontProvider(new DefaultFontProvider(true, true, true));
HtmlConverter.ConvertToPdf(html, memberStream, converterProperties);
byte[] pdfArray = memberStream.ToArray();
var response = new HttpResponseMessage();
response.StatusCode = System.Net.HttpStatusCode.OK;
response.Content = new ByteArrayContent(pdfArray);
response.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/pdf");
return response;
}
}