3

我想将HTML + CSS页面转换为PDF文件。 我试过wkhtmltopdf,我遇到了问题,因为我想访问的网页需要在网站上进行身份验证。如何使用wkhtmltopdf将安全的HTML(ASP.NET MVC 3)页面转换为PDF?

页,我想转换为PDF格式有如下的URL:http:// [公司网址]/PDFReport/33

如果我尝试不认证来访问它,我重定向到登录页。

所以当我用wkhtmltopdf,它在我的登录页面转换为PDF ...

我在我的ASP.NET MVC应用程序中使用anthentication方法是SimpleMembership:

[Authorize] 
public ActionResult PDFReport(string id) 
{ 
} 

我执行wkhtmltopdf .exe与System.Diagnostics.Process:

FileInfo tempFile = new FileInfo(Request.PhysicalApplicationPath + "\\bin\\test.pdf"); 

StringBuilder argument = new StringBuilder(); 
argument.Append(" --disable-smart-shrinking"); 
argument.Append(" --no-pdf-compression"); 
argument.Append(" " + "http://[WEBSITE]/PDFReport/33"); 
argument.Append(" " + tempFile.FullName); 

// to call the exe to convert 
using (Process p = new System.Diagnostics.Process()) 
{ 
    p.StartInfo.UseShellExecute = false; 
    p.StartInfo.CreateNoWindow = true; 
    p.StartInfo.FileName = Request.PhysicalApplicationPath + "\\bin\\wkhtmltopdf.exe"; 
    p.StartInfo.Arguments = argument.ToString(); 
    p.StartInfo.RedirectStandardOutput = true; 
    p.StartInfo.RedirectStandardError = true; 

    p.Start(); 
    p.WaitForExit(); 
} 

您知道如何在不禁用此页面上的安全性的情况下生成PDF吗?

回答

1

最近我遇到了很多麻烦。简而言之,WKHTMLTOPDF是Webkit(QT,我相信他们称之为)的一个版本,所以当你请求一个受密码保护的页面时,浏览器需要登录和存储/引用一个cookie,就像你通常一样。

原始调用看起来是这样的:

`/路/ wkhtmltopdf --cookie-JAR my.jar --username名为myUsername --password输入mypassword URL

其中:

  • my.jar是一个创建并保存您的cookie值的jar文件
  • username是用户名表单字段的namemyusername是岗位价值
  • password是密码表单字段的namemypassword是岗位价值
  • URL的日志页面的URL

一定要包括成功登录所需的任何其他职务领域在 - 你可能会想监视你的HTTP头,而不只是看表格。再次使用正常参数在您要捕获的页面上调用WKHTMLTOPDF,包括--cookie-jar my.jar以维护会话。这应该做到!

但是,我仍然遇到了问题,但它是一个相当健壮的登录(多个Cookie,安全,许多参数等)。我正在使用PHP,并使用CURL运气更好 - 我不确定这是如何继承到ASP.NET(也许这?http://support.microsoft.com/kb/303436),但这里是我的逻辑,如果有帮助:

登录通过卷曲
  • 抓住HTML页面,并存储在本地临时文件
    • 替换的图片和文件,以绝对引用的所有相对引用(或插入base标签)上的临时文件
    • 运行普通的“醇WKHTMLTOPDF删除临时文件

    总而言之,这样做很容易,而且对我来说感觉更好,因为我知道我靠着WKHTMLTOPDF 0.10版中的试验和真实代码而不是参数。

  • +0

    谢谢,我会尝试这种解决方法。 – Toc

    相关问题