如何使用和改进wkhtmltopdf性能?

时间:2014-12-10 09:32:21

标签: asp.net wkhtmltopdf

我有我的aspx页面,一些逻辑用后面的代码编写来绑定aspx pages的数据。现在使用wkhtmltopdf我发送这些文件转换成pdf文件。当数据量较小时,它工作得很好但是,当该页面的数据较大时,wkhtmltopdf会停止工作并且不会创建任何pdf文件。

你能否提出任何方法来克服这个问题。我尝试的是限制数据..例如我在我的页面上有转发器控件如果控件绑定350记录我只记录20条记录,但如果这20条记录的大小很大,它也会发生相同的

我尝试的下一个选项是我在

中给出参数

处理myProcess = Process.Start(startInfo);                 myProcess.WaitForExit(几秒钟);

但它仍然无效

请建议

2 个答案:

答案 0 :(得分:0)

Process myProcess = Process.Start(startInfo);
                string error = myProcess.StandardError.ReadToEnd();
                myProcess.WaitForExit();
                myProcess.Close();
                objZip.AddFile(destinationFile, "Files");
                myProcess.Dispose();
                myProcess = null;

这是答案=>会发生什么事情,当你开始进程,并等待exit()都会创建一个死锁时间,这会破坏性能......通过在waitforexit()之前添加readtoend()方法来清除死锁然后继续进一步处理......

这解决了我的问题。

答案 1 :(得分:0)

我展示完整解决方案的原因是,wkhtmltopdf非常适合创建动态pdf文件,但这也是免费工具,因此对此文档非常有限..

private void ProcessHtmlToPdf(List lstExportToPdfCategories)         {             尝试             {                 string pdfExportPath = string.Empty;                 string PDFdeletePath = string.Empty;                 string deletePath = string.Empty;                 string PdfSavePath = string.Empty;

            if (lstExportToPdfCategories != null)
            {
                foreach (var item in lstExportToPdfCategories)
                {
                    path = "";
                    pdfExportPath = profile + ApConfig.CurrentCompany.CompId + "/" + objExpDetails.AddedForId.ToString() + "/" + item.HeaderCategory;
                    PDFdeletePath = profile + ApConfig.CurrentCompany.CompId + "/" + objExpDetails.AddedForId.ToString();
                    PdfSavePath = profile + ApConfig.CurrentCompany.CompId + "/" + objExpDetails.AddedForId.ToString() + "/" + item.HeaderCategory;
                    htmlpath = profile + ApConfig.CurrentCompany.CompId + "/" + objExpDetails.AddedForId.ToString() + "/" + item.HeaderCategory;

                    deletePath = Server.MapPath(PDFdeletePath);
                    string ClearDirectory = Server.MapPath(PdfSavePath);
                    if (Directory.Exists(deletePath))
                    {
                        //Directory.Delete(ClearDirectory, true);
                        //Directory.Delete(deletePath, true);
                    }


                    if (!Directory.Exists(Server.MapPath(pdfExportPath)))
                    {
                        Directory.CreateDirectory(Server.MapPath(pdfExportPath));
                    }
                    string name =
                        pdfExportPath = pdfExportPath + "/" + objExpDetails.FirstName + "." + objExpDetails.LastName + "-" + item.HeaderCategory + "_" + (drpYear.SelectedValue != "0" ? Convert.ToString(drpYear.SelectedValue) : System.DateTime.Now.Year.ToString()) + ".pdf";
                    objpath = Server.MapPath(pdfExportPath);

                    //this will create html mockup 
                    //item.WebsiteUrl = CreateTemportHtmlFile(item.HeaderCategory, PdfSavePath, item.WebsiteUrl);

                    if (path == "")
                    {
                        path = CreateTemportHtmlFile(PdfSavePath, item.HeaderCategory);
                    }

                    HtmlToPdf(item.WebsiteUrl, objpath, path);
                }
                Response.Clear();
                Response.AddHeader("Content-Disposition", "attachment; filename=" + objExpDetails.FirstName + "." + objExpDetails.LastName + "-actusdocs.zip");
                Response.ContentType = "application/zip";
                objZip.Save(Response.OutputStream);
                Response.End();
            }
        }
        catch (Exception ex)
        {
            //SendEmail.SendErrorMail("ProcessHtmlToPdf method : ", ex.Message + ex.StackTrace, objExpDetails);
        }
    }

    //Method overloading

    //this is for testing html pages(not in used during main running)
    private string CreateTemportHtmlFile(string categoryName, string htmlMockupSavingPath, string websiteURL)
    {
        try
        {
            string sessionId = Session.SessionID;
            int employeeId = Convert.ToInt32(hdnEmployeeId.Value);

            htmlMockupSavingPath = Server.MapPath(htmlMockupSavingPath) + "\\" + categoryName + ".html";
            StreamWriter sw;

            HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(websiteURL);
            myRequest.Method = "GET";
            WebResponse myResponse = myRequest.GetResponse();
            StreamReader sr = new StreamReader(myResponse.GetResponseStream(), System.Text.Encoding.UTF8);
            string result = sr.ReadToEnd();

            sw = File.CreateText(htmlMockupSavingPath);
            sw.WriteLine(result);
            sw.Close();
            Response.WriteFile(htmlMockupSavingPath);
        }

        catch (Exception ex)
        {
            SendEmail.SendErrorMail("CreateTemportHtmlFile method : ", ex.Message + ex.StackTrace, objExpDetails);
        }

        return htmlMockupSavingPath;
    }

    private string CreateTemportHtmlFile(string PdfSavePath, string categoryName)
    {
        try
        {
            string sessionId = Session.SessionID;
            int employeeId = Convert.ToInt32(hdnEmployeeId.Value);

            PdfSavePath = Server.MapPath(PdfSavePath) + "\\BindHeader.html";
            htmlpath = htmlpath.Substring(1);
            htmlpath = ConfigurationManager.AppSettings["pdfUrlPath"].ToString() + htmlpath + "/BindHeader.html";
            string exportedYear = (drpYear.SelectedValue == "0" ? System.DateTime.Now.Year.ToString() : drpYear.SelectedValue);

            StreamWriter sw;
            if (categoryName == "MidYearAppraisal" || categoryName == "EndYearAppraisal")
            {
                myRequest = (HttpWebRequest)WebRequest.Create(ConfigurationManager.AppSettings["pdfUrlPath"] + "/User/UserPdfReports/UserPdfHeaderforAppraisal.aspx?session=" + sessionId + "&empId=" + employeeId + "&catName=" + categoryName + "&expYear=" + exportedYear);
            }
            else
            {
                myRequest = (HttpWebRequest)WebRequest.Create(ConfigurationManager.AppSettings["pdfUrlPath"] + "/User/UserPdfReports/UserPdfHeader.aspx?session=" + sessionId + "&empId=" + employeeId + "&catName=" + categoryName + "&expYear=" + exportedYear);
            }

            myRequest.Method = "GET";
            WebResponse myResponse = myRequest.GetResponse();
            StreamReader sr = new StreamReader(myResponse.GetResponseStream(), System.Text.Encoding.UTF8);
            string result = sr.ReadToEnd();

            sw = File.CreateText(PdfSavePath);
            sw.WriteLine(result);
            sw.Close();
            Response.WriteFile(PdfSavePath);
        }

        catch (Exception ex)
        {
            SendEmail.SendErrorMail("CreateTemportHtmlFile method : ", ex.Message + ex.StackTrace, objExpDetails);
        }

        return htmlpath;
    }

    private void HtmlToPdf(string website, string destinationFile, string path)
    {
        try
        {
            string hrmlPath = ConfigurationManager.AppSettings["pdfUrlPath"].ToString() + "/user/UserPdfReports/FooterPdfReports.html";
            ProcessStartInfo startInfo = new ProcessStartInfo();
            string switches = "";
            switches += "--header-html " + path + " --footer-html " + hrmlPath;

            startInfo.UseShellExecute = false;

            startInfo.RedirectStandardOutput = true;

            startInfo.RedirectStandardInput = true;

            startInfo.RedirectStandardError = true;

            startInfo.CreateNoWindow = true;

            startInfo.FileName = "C:\\Program Files\\wkhtmltopdf\\bin\\wkhtmltopdf.exe";

            startInfo.Arguments = switches + " " + website + " " + destinationFile;

            Process myProcess = Process.Start(startInfo);
            string error = myProcess.StandardError.ReadToEnd();
            myProcess.WaitForExit();
            myProcess.Close();
            objZip.AddFile(destinationFile, "Files");
            myProcess.Dispose();
            myProcess = null;

        }
        catch (Exception ex)
        {
            //SendEmail.SendErrorMail("HtmlToPdf : ", ex.Message + ex.StackTrace, objExpDetails);
        }
    }