1、首先在项目中安装nuget包DinkToPdf
2、下载libwkhtmltox,可以去github上下载,没有条件的我放百度云盘链接。然后将下载好的三个文件放在项目的根目录中。确保DinkToPdf可以读取的到。
3、编辑代码
using DinkToPdf;
using DinkToPdf.Contracts;
namespace Text.Helper
{
public interface IPDFService
{
byte[] ConvertHtmlToPdfByDinkToPdf(string htmlContent, string fileName = "PDF");
}
public class PDFHelper : IPDFService
{
#region 生成PDF
private IConverter _converter;
public PDFHelper(IConverter converter)
{
_converter = converter;
}
public byte[] ConvertHtmlToPdfByDinkToPdf(string htmlContent, string fileName = "PDF")
{
try
{
var globalSettings = new GlobalSettings
{
ColorMode = ColorMode.Color,
Orientation = Orientation.Portrait,
PaperSize = PaperKind.A4,
DocumentTitle = fileName,
};
var objectSettings = new ObjectSettings
{
PagesCount = true,
HtmlContent = htmlContent,
WebSettings = { DefaultEncoding = "utf-8" },
HeaderSettings = { FontSize = 9, Right = "当前 [page]页 共 [toPage]页", Line = false },
FooterSettings = { FontSize = 9, Right = "当前 [page]页 共 [toPage]页" }
};
var doc = new HtmlToPdfDocument()
{
GlobalSettings = globalSettings,
Objects = { objectSettings }
};
byte[] pdfBytes = _converter.Convert(doc);
return pdfBytes;
}
catch (Exception)
{
throw;
}
}
#endregion
}
}
调用代码如下
private IPDFService _PDFService;
public WebModController(IPDFService pDFService)
{
_PDFService = pDFService;
}
[HttpPost]
public FileResult? ExportPDF(Models.VmInfoPub param)
{
try
{
var html = "";//这里放html字符串
string fileName = DateTime.Now.ToString("yyyyMMddHHmmssffff", DateTimeFormatInfo.InvariantInfo) + ".pdf";
var pdfBytes = _PDFService.ConvertHtmlToPdfByDinkToPdf(html, fileName);
if (pdfBytes != null)
{
return File(pdfBytes, "application/pdf", fileName);
}
return null;
}
catch (Exception)
{
throw;
}
}