wkhtmltopdf outputstream & download - diaglog

后端 未结 2 468
小蘑菇
小蘑菇 2021-01-05 14:08

is it possible to get a pdf stream created by wkhtmltopdf from any html file and popup a download dialog in IE/Firefox/Chrome etc.?

At the moment I get my outputstre

2条回答
  •  Happy的楠姐
    2021-01-05 14:17

    Is this still a problem?

    I just created a new ASP.net website to test this on my computer after installing wkhtmltopdf 0.11.0 rc2 and it worked fine creating the PDF. My version was only slightly different;

    In my CSHTML I had:

    MemoryStream PDFStream = new MemoryStream();
    MemoryStream PDF = Derp.GeneratePdf(PDFStream);
    byte[] byteArray1 = PDF.ToArray();
    PDF.Flush();
    PDF.Close();
    Response.BufferOutput = true;
    Response.Clear();
    Response.ClearHeaders();
    Response.AddHeader("Content-Disposition", "attachment; filename=Test.pdf");
    Response.ContentType = "application/octet-stream";
    Response.BinaryWrite(byteArray1);
    Response.End();
    

    My Derp class

    public class Derp
    {
        public static MemoryStream GeneratePdf(MemoryStream pdf)
        {
            using (StreamReader Html = new StreamReader(@"Z:\HTMLPage.htm"))
            {
                Process p;
                StreamWriter stdin;
                ProcessStartInfo psi = new ProcessStartInfo();
                psi.FileName = @"C:\wkhtmltopdf\wkhtmltopdf.exe";
                psi.UseShellExecute = false;
                psi.CreateNoWindow = true;
                psi.RedirectStandardInput = true;
                psi.RedirectStandardOutput = true;
                psi.RedirectStandardError = true;
                psi.Arguments = "-q -n --disable-smart-shrinking " + " - -";
                p = Process.Start(psi);
                try
                {
                    stdin = p.StandardInput;
                    stdin.AutoFlush = true;
                    stdin.Write(Html.ReadToEnd());
                    stdin.Dispose();
                    CopyStream(p.StandardOutput.BaseStream, pdf);
                    p.StandardOutput.Close();
                    pdf.Position = 0;
                    p.WaitForExit(10000);
                    return pdf;
                }
                catch
                {
                    return null;
                }
                finally
                {
                    p.Dispose();
                }
            }
        }
    
        public static void CopyStream(Stream input, Stream output)
        {
            byte[] buffer = new byte[32768];
            int read;
            while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
            {
                output.Write(buffer, 0, read);
            }
        }
    }
    

提交回复
热议问题