Reputation: 61
I'm using wkhtmltopdf.exe on my server to convert some .aspx page based reports into pdf's that are then downloaded to the clients computer. After extensive research I found this blog post with an example that seemed to get at what I want to accomplish. I attempted to adapt it to my own uses however I can't get it to work. The response from the page is a .pdf file but it is 0 bytes in length. I been researching solutions for converting an rendered aspx page to .pdf for close to a day and a half now with no luck - this solution is the closest I've come and I think I'm just missing something simple and it will work.
Please see code below - I would appreciate any guidance you can provide to make this work!
public partial class PDFOut : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string args = string.Format("\"{0}\" - ", Request.Form["url"]);//'http://www.google.com' is what I'm passing for testing
var startInfo = new ProcessStartInfo(Server.MapPath("\\tools\\wkhtmltopdf.exe"), args)
{
UseShellExecute = false,
RedirectStandardOutput = true
};
var proc = new Process { StartInfo = startInfo };
proc.Start();
string output = proc.StandardOutput.ReadToEnd();
byte[] buffer = proc.StandardOutput.CurrentEncoding.GetBytes(output);
proc.WaitForExit();
proc.Close();
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment; filename=test.pdf");
Response.BinaryWrite(buffer);
Response.End();
}
}
Upvotes: 1
Views: 1730
Reputation: 928
Would something like this work for you? Write the PDF to a temp directory, then read the PDF and finally delete the temp file?
protected void Page_Load(object sender, EventArgs e)
{
string outputFile = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName(), ".pdf");
string args = string.Format("\"{0}\" \"{1}\"", Request.Form["url"], outputFile );
var startInfo = new ProcessStartInfo(Server.MapPath("\\tools\\wkhtmltopdf.exe"), args)
{
UseShellExecute = false,
RedirectStandardOutput = true
};
var proc = new Process { StartInfo = startInfo };
proc.Start();
proc.WaitForExit();
proc.Close();
var buffer= File.ReadAllBytes(outputFile);
File.Delete(outputFile);
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment; filename=test.pdf");
Response.BinaryWrite(buffer);
Response.End();
}
Upvotes: 1