需要通过NuGet添加Html2Pdf引用
#region 通过Html来生成pdf,测试Html样式 /// <summary> /// 通过Html来生成pdf,测试Html样式 /// </summary> /// <param name="html">要转换成pdf的html</param> /// <returns></returns> [HttpGet] [Route("TestHtmlToPdf")] public HttpResponseMessage TestHtmlToPdf(string html) { //test html="<!DOCTYPE%20html>%20<html>%20<head>%20<meta%20charset="utf-8"%20/>%20<title></title>%20</head>%20<body>%20<div%20style="opacity:0">opacity</div>%20<div%20style="visibility:hidden">发的fads</div>%20<div%20style="display:none">display</div>%20</body>%20</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(); #region 生成pdf后加公章 var outputStream = new MemoryStream(); var reader = new PdfReader(pdfArray); PdfStamper stamp = new PdfStamper(reader, outputStream); Image image = Image.GetInstance("zhang.png"); image.Alignment = Element.ALIGN_LEFT; image.ScaleToFit(120, 120); image.SetAbsolutePosition(400, 700); //页数是从1开始的 for (int i = 1; i <= reader.NumberOfPages; i++) { PdfContentByte under = stamp.GetOverContent(i); under.AddImage(image); } stamp.Close(); outputStream.Close(); pdfArray = outputStream.ToArray(); #endregion 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; } } #endregion