从HTML生成PDF文件
从HTML生成PDF文件
public static void WriterPDF(string tempFileName, bool isLowerWindows = true, bool withMarkwater = true)
{
string wkhtmltopdfPath = ResourceUtilities.WkhtmltopdfPathLower;
if (!isLowerWindows)
{
wkhtmltopdfPath = ResourceUtilities.WkhtmltopdfPathHigher;
}
var pi = new ProcessStartInfo(wkhtmltopdfPath);
pi.CreateNoWindow = true;
pi.UseShellExecute = false;
if (!Directory.Exists(ResourceUtilities.WkhtmltoxFolder))
{
Directory.CreateDirectory(ResourceUtilities.WkhtmltoxFolder);
}
if (!Directory.Exists(ResourceUtilities.PDFTempFolder))
{
Directory.CreateDirectory(ResourceUtilities.PDFTempFolder);
}
pi.WorkingDirectory = ResourceUtilities.WkhtmltoxFolder;
string[] result = CreateWkhtmltopdfArguments(tempFileName, withMarkwater);
pi.Arguments = result[0];
using (var process = Process.Start(pi))
{
process.WaitForExit(99999);
Debug.WriteLine(process.ExitCode);
}
if (withMarkwater)
{
string pdfExportFile = ExportFilePathHelper.GetExportFilePath() + tempFileName + ".pdf";
AddWatermark(result[1], pdfExportFile);
//IoHelper.DeleteFile(ResourceUtilities.PDFTempFolder + tempFileName + ".pdf");
string htmlTempFolder = ResourceUtilities.HtmlTempFolder.Replace("\\", "/");
string htmlTempFile = htmlTempFolder + tempFileName + ".html";
//IoHelper.DeleteFile(htmlTempFile);
}
}
public static string[] CreateWkhtmltopdfArguments(string fileName, bool withMarkwater = false)
{
string arguments = "file:///";
string htmlTempFolder = ResourceUtilities.HtmlTempFolder.Replace("\\", "/");
string htmlTempFile = htmlTempFolder + fileName + ".html";
string pdfExportFolder = ExportFilePathHelper.GetExportFilePath();
if (!Directory.Exists(pdfExportFolder))
{
Directory.CreateDirectory(pdfExportFolder);
}
string pdfExportFile = pdfExportFolder + fileName + ".pdf";
if (withMarkwater)
{
string tempExportFolder = ResourceUtilities.PDFTempFolder;
pdfExportFile = tempExportFolder + fileName + ".pdf";
}
arguments = arguments + htmlTempFile + " " + pdfExportFile;
string[] result = new string[] { arguments, pdfExportFile };
return result;
}
有几个地方要注意
- 使用的是wkhtmltopdf这个C++编写的工具
- 这个工具有两个主要的版本,一个是依赖VS2013 C++ Runtime编译的,一个是依赖早期的类库编译的,要根据自己的操作系统判断使用哪一个。官网地址http://wkhtmltopdf.org/downloads.html