How to use and improve wakhtmltopdf performance?

旧时模样 提交于 2019-12-13 03:03:23

问题


I have my aspx pages , and some logic is written in code behind to bind the data of aspx pages.Now using wkhtmltopdf i am sending these files to convert into pdf files.Its work very well when the data is smaller in size however when the data comes in larger side for that page the wkhtmltopdf stops working and doesnt create any pdf file.

Can you suggest any way to overcome this problem. What i tried was limiting the data.. for example i have repeater control on my page if that controls binds 350 record i am only taking 20 records , but also if size of those 20 records are large it happens the same

the also next option i tried is my giving the parameter inside

Process myProcess = Process.Start(startInfo); myProcess.WaitForExit(few seconds);

but it still doesnt work

Please suggest


回答1:


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

This is the answer => what happen is when u start process , and wait for exit () both creates a deadlock somtimes which hammers the performance .. by adding readtoend() method before waitforexit() clears the deadlock and then continues further processing ...

this solves my problem.




回答2:


The reason i am showing complete solution is that , wkhtmltopdf is very good for creating dynamic pdf files , but this is free tool as well and hence very limited documentation for this ..

private void ProcessHtmlToPdf(List lstExportToPdfCategories) { try { 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);
        }
    }


来源:https://stackoverflow.com/questions/27397477/how-to-use-and-improve-wakhtmltopdf-performance

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!