Как использовать и улучшить производительность wakhtmltopdf?

У меня есть страницы aspx, и в коде написана некоторая логика для привязки данных страниц aspx. Теперь, используя wkhtmltopdf, я отправляю эти файлы для преобразования в файлы pdf. Он работает очень хорошо, когда данные меньше по размеру, однако, когда данные поступают в большую сторону для этой страницы, wkhtmltopdf перестает работать и не создает файл PDF.

Можете ли вы предложить какой-либо способ преодолеть эту проблему. То, что я пробовал, ограничивало данные. Например, у меня есть контроль повторителя на моей странице, если он управляет привязкой 350 записей, я беру только 20 записей, но также, если размер этих 20 записей велик, происходит то же самое

также следующий вариант, который я пробовал, - это мой параметр внутри

Процесс myProcess = Process.Start(startInfo); myProcess.WaitForExit(несколько секунд);

но все равно не работает

Пожалуйста, предложите


person Torakami    schedule 10.12.2014    source источник
comment
Попробуйте следующее: визуализируйте точный результат, который вы передаете wkhtmltopdf в браузере. Если там все работает хорошо, сохраните HTML-код вручную в простой HTML-файл и попробуйте преобразовать его из командной строки без дополнительных аргументов командной строки. Это может помочь вам сузить результаты. Было бы полезно увидеть визуализированный HTML, который вызывает проблемы, вставленные куда-нибудь...   -  person Joel Peltonen    schedule 23.12.2014
comment
Я попробовал это, я попытался сначала преобразовать файл в html, а затем попытался отправить этот html-файл в wkhtmltopdf для преобразования ... но происходит то, что рендеринг html в pdf иногда не работает должным образом ...   -  person Torakami    schedule 23.12.2014


Ответы (2)


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

Это ответ => что происходит, когда вы запускаете процесс и ждете выхода (), оба иногда создают тупик, который снижает производительность ... путем добавления метода readtoend () до того, как waitforexit () очищает тупик, а затем продолжает дальнейшую обработку. ..

это решает мою проблему.

person Torakami    schedule 23.12.2014

Причина, по которой я показываю полное решение, заключается в том, что wkhtmltopdf очень хорош для создания динамических файлов PDF, но это также бесплатный инструмент и, следовательно, очень ограниченная документация для этого.

private void ProcessHtmlToPdf (List lstExportToPdfCategories) { try { string pdfExportPath = string.Empty; строка PDFdeletePath = строка.Пустой; строка deletePath = строка.Пустой; строка 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);
        }
    }
person Torakami    schedule 23.12.2014