从数据库到PDF的HTML
我需要使用asp.net从html动态生成pdf。HTML存储在数据库中。HTML有表格和css,最多10页。我已经尝试了从数据库到PDF的HTML,html,asp.net,export-to-pdf,Html,Asp.net,Export To Pdf,我需要使用asp.net从html动态生成pdf。HTML存储在数据库中。HTML有表格和css,最多10页。我已经尝试了iTextSharp,通过直接传递,它生成了未打开的pdf。Destinationpdf.codeplex.com没有文档,它从父页面生成带有样式的pdf 任何其他解决方案都会有帮助。我已经尝试了许多HTML到PDF的解决方案,包括iTextSharp、wkhtmltopdf和ABCpdf(付费) 我目前选择了一款无头、开源、基于WebKit的浏览器。它可以用一个文档记录良好
iTextSharp
,通过直接传递,它生成了未打开的pdf。Destinationpdf.codeplex.com
没有文档,它从父页面生成带有样式的pdf
任何其他解决方案都会有帮助。我已经尝试了许多HTML到PDF的解决方案,包括iTextSharp、wkhtmltopdf和ABCpdf(付费) 我目前选择了一款无头、开源、基于WebKit的浏览器。它可以用一个文档记录良好的脚本编写 我发现的唯一缺点是,尝试使用stdin将HTML传递到进程中失败,因为进程仍然存在一些bug。我还发现使用
stdout
似乎比简单地允许进程写入磁盘要慢得多
下面的代码通过将javascript输入创建为临时文件、执行PhantomJS、将输出文件复制到MemoryStream
并在最后清理临时文件来避免stdin
和stdout
using System.IO;
using System.Drawing;
using System.Diagnostics;
public Stream HTMLtoPDF (string html, Size pageSize) {
string path = "C:\\dev\\";
string inputFileName = "tmp.js";
string outputFileName = "tmp.pdf";
StringBuilder input = new StringBuilder();
input.Append("var page = require('webpage').create();");
input.Append(String.Format("page.viewportSize = {{ width: {0}, height: {1} }};", pageSize.Width, pageSize.Height));
input.Append("page.paperSize = { format: 'Letter', orientation: 'portrait', margin: '1cm' };");
input.Append("page.onLoadFinished = function() {");
input.Append(String.Format("page.render('{0}');", outputFileName));
input.Append("phantom.exit();");
input.Append("};");
// html is being passed into a string literal so make sure any double quotes are properly escaped
input.Append("page.content = \"" + html.Replace("\"", "\\\"") + "\";");
File.WriteAllText(path + inputFileName, input.ToString());
Process p;
ProcessStartInfo psi = new ProcessStartInfo();
psi.FileName = path + "phantomjs.exe";
psi.Arguments = inputFileName;
psi.WorkingDirectory = Path.GetDirectoryName(psi.FileName);
psi.UseShellExecute = false;
psi.CreateNoWindow = true;
p = Process.Start(psi);
p.WaitForExit(10000);
Stream strOut = new MemoryStream();
Stream fileStream = File.OpenRead(path + outputFileName);
fileStream.CopyTo(strOut);
fileStream.Close();
strOut.Position = 0;
File.Delete(path + inputFileName);
File.Delete(path + outputFileName);
return strOut;
}
是一种无头(无用户itnerface)浏览器,它将获取一个url,“截图”并将结果保存为pdf。将其复制到服务器,并使用Process.Start()
或类似机制运行它