通过Url地址或者html内容生成到PDF文件,并部署到IIS,转换内容不支持Webpack构建的前端项目。
这里使用的是TuesPechkin,引用下面2个Nuget包
封装简单工具类
/// <summary>
/// html转pdf帮助类
/// </summary>
public static class HtmlToPdfHelper
{
private static readonly string _fileDir = "htmlToPdf";
private static readonly string _savePath = System.Web.Hosting.HostingEnvironment.MapPath("/" + _fileDir);
private static IConverter _converter = null; //官方要求在程序生命周期内,只能实例化一次
private static string _domainUrl;
/// <summary>
/// 获取当前站点域名
/// </summary>
/// <returns></returns>
public static string DomainUrl
{
get
{
Uri uri = HttpContext.Current.Request.Url;
_domainUrl = uri.Scheme + "://" + uri.Host;
if (!uri.IsDefaultPort)
{
_domainUrl += ":" + uri.Port;
}
return _domainUrl;
}
}
static HtmlToPdfHelper()
{
_converter =
new ThreadSafeConverter(
new RemotingToolset<PdfToolset>(
new WinAnyCPUEmbeddedDeployment(
new TempFolderDeployment())));
//_converter.Begin += ConverterOnBegin;
//_converter.PhaseChange += ConverterOnPhaseChange;
//_converter.ProgressChange += ConverterOnProgressChange;
//_converter.Finish += ConverterOnFinish;
_converter.Warning += new EventHandler<WarningEventArgs>((o, w) =>
{
Console.WriteLine("HtmlToPdfHelper类,html转换PDF,产生警告信息:" + w.WarningMessage);
});
_converter.Error += new EventHandler<TuesPechkin.ErrorEventArgs>((o, e) =>
{
Console.WriteLine("HtmlToPdfHelper类,html转换PDF,产生错误信息:" + e.ErrorMessage);
});
}
/// <summary>
/// 转换为pdf字节
/// </summary>
/// <param name="doc"></param>
/// <returns></returns>
private static byte[] Filing(IDocument doc)
{
byte[] result = _converter.Convert(doc);
return result;
}
/// <summary>
/// 构建PDF服务器访问地址
/// </summary>
/// <param name="pdfName"></param>
/// <returns></returns>
private static string BuildUrl(string pdfName)
{
return $@"{DomainUrl}/{_fileDir}/{pdfName}.pdf";
}
/// <summary>
/// 构建PDF保存路径
/// </summary>
/// <param name="pdfName"></param>
/// <returns></returns>
private static string BuildSaveSrc(string pdfName)
{
return $@"{_savePath}\{pdfName}.pdf";
}
/// <summary>
/// 查找已转换的PDF文件
/// </summary>
/// <param name="pdfName">已保存PDF名称</param>
/// <returns>返回保存Url地址</returns>
private static string FindSaveHtmlPdf(string pdfName)
{
//把文件读进文件流
var fileSrc = BuildSaveSrc(pdfName);
if (!File.Exists(fileSrc))
{
return string.Empty;
}
return BuildUrl(pdfName);
}
/// <summary>
/// 保存已转换的PDF文件
/// </summary>
/// <param name="fileName">PDF文件名</param>
/// <param name="bf">保存字节集</param>
/// <returns>保存成功返回url</returns>
private static string SaveHtmlToPdfFile(string fileName, byte[] bf)
{
var path = _savePath;
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
System.IO.File.WriteAllBytes(BuildSaveSrc(fileName), bf);
return BuildUrl(fileName);
}
/// <summary>
/// 根据类型转换PDF为字节
/// </summary>
/// <param name="document">保存文档</param>
/// <param name="type">保存的类型</param>
/// <returns></returns>
private static byte[] BuildDocumentByType(string document, EHtmlToPdfDocumentType type)
{
byte[] saveBuffer = null;
if (type == EHtmlToPdfDocumentType.HtmlUrl)
{
saveBuffer = ConvertHtmlUrlToPDF(document);
}
else if (type == EHtmlToPdfDocumentType.HtmlText)
{
saveBuffer = ConvertHtmlTextToPDF(document);
}
return saveBuffer;
}
/// <summary>
/// 转换htmltext为PDF
/// </summary>
/// <param name="htmlText">html文档内容</param>
/// <returns></returns>
public static byte[] ConvertHtmlTextToPDF(string htmlText)
{
if (string.IsNullOrWhiteSpace(htmlText))
{
new ArgumentNullException("htmlText", "html的内容不能为空");
}
var document = new HtmlToPdfDocument
{
GlobalSettings = { },
Objects = {
new ObjectSettings {
HtmlText = htmlText,
WebSettings =new WebSettings
{
DefaultEncoding="UTF-8",
LoadImages=true,
}
}
},
};
var result = _converter.Convert(document);
return result;
}
/// <summary>
/// 转换htmlUrl为PDF
/// </summary>
/// <param name="htmlText">html文档内容</param>
/// <returns></returns>
public static byte[] ConvertHtmlUrlToPDF(string htmlUrl)
{
if (string.IsNullOrWhiteSpace(htmlUrl))
{
new ArgumentNullException("htmlUrl", "html的Url地址不能为空");
}
var doc = new HtmlToPdfDocument();
doc.Objects.Add(new ObjectSettings { PageUrl = htmlUrl });
byte[] result = Filing(doc);
return result;
}
/// <summary>
/// 获取Html转换后的PDF文件Url(如果文件不存在,并先执行保存,在返回url地址)
/// </summary>
/// <param name="pdfName">要保存PDF名称</param>
/// <param name="document">要保存的Hmtl文档内容,(例如,htmlTXT,htmlurl)</param>
/// <param name="type">保存的type类型</param>
/// <param name="IsCover">是否覆盖(默认不覆盖)</param>
/// <returns></returns>
public static string GetHtmlToPdfSaveUrl(string pdfName, string document, EHtmlToPdfDocumentType type, bool IsCover = false)
{
string pdfSaveUrl = FindSaveHtmlPdf(pdfName);
if (string.IsNullOrEmpty(pdfSaveUrl) || IsCover)
{
//获取转换成功后PDF字节
byte[] saveBuffer = BuildDocumentByType(document, type);
//返回保存成功后PDF文件url
return SaveHtmlToPdfFile(pdfName, saveBuffer);
}
return pdfSaveUrl;
}
/// <summary>
/// 下载Html转换后的PDF文件字节流(如果文件不存在,并先执行保存,在返回下载字节流)
/// </summary>
/// <param name="pdfName">要保存PDF名称</param>
/// <param name="document">要保存的Hmtl文档内容,(例如,htmlTXT,htmlurl)</param>
/// <param name="type">保存的type类型</param>
/// <param name="IsCover">是否覆盖(默认不覆盖)</param>
/// <returns></returns>
public static byte[] DownloadHtmlToPdf(string pdfName, string document, EHtmlToPdfDocumentType type, bool IsCover = false)
{
byte[] saveBuffer = DownloadSaveHtmlToPdf(pdfName);
if (saveBuffer == null || IsCover)
{
//获取转换成功后PDF字节
saveBuffer = BuildDocumentByType(document, type);
//保存PDF文件
SaveHtmlToPdfFile(pdfName, saveBuffer);
return saveBuffer;
}
return saveBuffer;
}
/// <summary>
/// 获取已存在服务器上的PDF文件字节
/// </summary>
/// <param name="pdfName">文件名称</param>
/// <returns></returns>
public static byte[] DownloadSaveHtmlToPdf(string pdfName)
{
//把文件读进文件流
var fileSrc = BuildSaveSrc(pdfName);
if (!File.Exists(fileSrc))
{
return null;
}
FileStream fs = new FileStream(fileSrc, FileMode.Open);
byte[] file = new byte[fs.Length];
fs.Read(file, 0, file.Length);
fs.Close();
return file;
}
}
/// <summary>
/// 文档转换类型
/// </summary>
public enum EHtmlToPdfDocumentType
{
HtmlUrl = 0,
HtmlText = 1,
}
测试代码
public string GetHtmlToPdf(string pdfName, string url)
{
if (string.IsNullOrWhiteSpace(url))
{
string[] arrs = new string[] { "http://www.baidu.com", "https://news.qq.com/", "https://www.sogou.com/" };
var index = new Random().Next(0, arrs.Length);
url = arrs[index];
}
if (string.IsNullOrWhiteSpace(pdfName))
{
pdfName = DateTime.Now.ToString("yyyyMMdd_HHmmss");
}
var res = HtmlToPdfHelper.GetHtmlToPdfSaveUrl(pdfName, url, EHtmlToPdfDocumentType.HtmlUrl);
return res;
}
测试调用
转换结果