尝试将html转换为pdf wkhtmltopdf时出现错误502

时间:2019-07-18 15:20:23

标签: c# asp.net wkhtmltopdf

尝试将html转换为pdf时出现错误:502 - Web server received an invalid response while acting as a gateway or proxy server. 我一步一步地记录了代码的哪一部分完全停止了.txt文件中的程序。最糟糕的是,我没有任何错误,尽管try中的这段代码不会在catch中引发错误。在这里:

string html = "html";

            byte[] pdf = null;

            Process p;
            ProcessStartInfo psi = new ProcessStartInfo();

            psi.FileName = "...wkhtmltopdf.exe";
            psi.WorkingDirectory = "...\\TempFolder";

            psi.UseShellExecute = false;
            psi.CreateNoWindow = true;
            psi.RedirectStandardInput = true;
            psi.RedirectStandardOutput = true;
            psi.RedirectStandardError = true;

            psi.Arguments = "--zoom 0.63 --dpi 300 - -";

            p = Process.Start(psi);

            try
            {
                // Get PDF as bytes without temp files
                using(StreamWriter stdin = new StreamWriter(p.StandardInput.BaseStream, Encoding.UTF8))
                {
                    stdin.AutoFlush = true;
                    stdin.Write(html);
                }

                byte[] buffer = new byte[32768];
                using(var ms = new MemoryStream())
                {
                    while(true)
                    {
                        int read = p.StandardOutput.BaseStream.Read(buffer, 0, buffer.Length);

                        if(read <= 0)
                        {
                            break;
                        }

                        ms.Write(buffer, 0, read); //!!! Here its last step !!!
                    }

                    pdf = ms.ToArray();
                }

                p.StandardOutput.Close();
                p.WaitForExit(60 * 10 * 1000);

                int returnCode = p.ExitCode;

                p.Close();

                if(returnCode == 0)
                    ViewData["Content"] = null;
                else
                    ViewData["Content"] = "Couldn't create PDF " + returnCode;

                MemoryStream PDF = new MemoryStream(pdf);

                // Return and save PDF    //application/pdf   multipart/form-data   application/x-msdownload
                return new FileStreamResult(PDF, "application/x-msdownload")
                {
                    FileDownloadName = fileName + "[" + dt + "]" + ".pdf"
                }; 

我花了三天的时间弄清楚为什么我会得到错误之后……事实证明……CSS中字体的错误路径。除502之外没有错误,程序正在无缘无故地停止。我猜是因为我通过StreamWriter / MemoryStream传递了参数,并直接将创建的PDF作为字节发送,没有临时文件。

0 个答案:

没有答案