wkhtmltopdf.exe 在 ASP.Net Web 表单中循环执行大约 100 次或更多次

发布于 2025-01-03 13:05:54 字数 4598 浏览 0 评论 0原文

我正在尝试将 HTML 页面打印为 PDF,我使用 wkhtmltopdf.exe 进行转换,类似的代码即使在单击按钮的测试页上也能工作,但是当我在 Print.aspx 页面上使用以下代码时,它会进入循环并开始 100 或我的 win 7 本地计算机上有更多 wkhtmltopdf.exe 进程。

我在 linkbutton 事件上从 main.aspx 页面导航到 print.aspx 页面,然后它生成页面并应该将页面转换为 PDF,而不是进入循环。我不知道为什么它会这样

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using CMS.SqlHelper;
using CMS.DataAccessLayer;
using System.Text;
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.text.html.simpleparser;
using System.Diagnostics;
using System.IO;

public partial class PrintArticle : System.Web.UI.Page
{
   // string print;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            try
            {
                if (Request["download"] != "yes")
                {
                    int articleID = int.Parse(Request["ArticleID"]);
                    string strSql = "Select ArticleID, ArticleTitle,  ArticleBodyDesc, ArticlePublishDate FROM art_Articles";
                    strSql += " WHERE ArticleID = " + articleID;
                    DataSet ds = DataProvider.Connect_Select(strSql);
                    DateTime dt;
                    if (ds.Tables[0].Rows.Count > 0)
                    {
                        lblArticleTitle.Text = ds.Tables[0].Rows[0]["ArticleTitle"].ToString();
                        //lblPubDate.Text = ds.Tables[0].Rows[0]["ArticlePublishDate"].ToString();
                        lblPubDate.Text = Convert.ToDateTime(ds.Tables[0].Rows[0]["ArticlePublishDate"].ToString()).ToLongDateString();
                        lblArticleDesc.Text = ds.Tables[0].Rows[0]["ArticleBodyDesc"].ToString();
                        //Response.Write ("<script type='text/javascript'>function printpage()  {  window.print();  }</script>");
                        //Page.ClientScript.RegisterStartupScript(GetType(), "MyKey", "printpage()");
                        Page.ClientScript.RegisterStartupScript(this.GetType(), "MyScript", "javascript:printpage();", true);

                    }
                    else
                    {
                        lblArticleDesc.Text = "Article not found";
                    }
                }
                else
                {

                    int articleID = int.Parse(Request["ArticleID"]);
                    Response.Clear();
                    string strSql = "Select ArticleID, ArticleTitle,  ArticleBodyDesc, ArticlePublishDate FROM art_Articles";
                    strSql += " WHERE ArticleID = " + articleID;
                    DataSet ds = DataProvider.Connect_Select(strSql);
                    if (ds.Tables[0].Rows.Count > 0)
                    {
                        lblArticleTitle.Text = ds.Tables[0].Rows[0]["ArticleTitle"].ToString();

                        lblPubDate.Text = Convert.ToDateTime( ds.Tables[0].Rows[0]["ArticlePublishDate"].ToString()).ToLongDateString();
                        lblArticleDesc.Text = ds.Tables[0].Rows[0]["ArticleBodyDesc"].ToString();



                        PrintToPDF();
                    }
                    else
                    {
                        lblArticleDesc.Text = "Article not found";
                    }


                }

            }
            catch (Exception ex)
            {
                Response.Write("Page can't be displayed. Please try later.");
            }
        }
    }

    protected void PrintToPDF()
    {
        try
        {
            string args = string.Format("\"{0}\" - ", Request.Url.AbsoluteUri);
            var startInfo = new ProcessStartInfo(Server.MapPath("bin\\wkhtmltopdf.exe"), args)
            {
                UseShellExecute = false,
                CreateNoWindow = true,
                RedirectStandardOutput = true

            };
            var proc = new Process { StartInfo = startInfo };
            proc.Start();

            string output = proc.StandardOutput.ReadToEnd();
            byte[] buffer = proc.StandardOutput.CurrentEncoding.GetBytes(output);
            proc.WaitForExit();
            proc.Close();
            Response.ContentType = "application/pdf";
            Response.AddHeader("Content-Disposition", "attachment;filename=download.pdf");
            Response.BinaryWrite(buffer);
            Response.End();


        }
        catch (Exception ex)
        {
            string xx = ex.Message.ToString();
            Response.Write("<br>" + xx);
        }
    }
}

I am trying to print an HTML page as PDF, I use wkhtmltopdf.exe for conversion similar code works on test page on button click even but when i use the following code on a Print.aspx page it gets in to loop and starts 100 or more wkhtmltopdf.exe process on my win 7 local machine.

I navigate to print.aspx page from main.aspx page on a linkbutton event which and then it generate the page and should convert the page into PDF rather it gets into loop. I am not sure why it is behaving like that

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using CMS.SqlHelper;
using CMS.DataAccessLayer;
using System.Text;
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.text.html.simpleparser;
using System.Diagnostics;
using System.IO;

public partial class PrintArticle : System.Web.UI.Page
{
   // string print;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            try
            {
                if (Request["download"] != "yes")
                {
                    int articleID = int.Parse(Request["ArticleID"]);
                    string strSql = "Select ArticleID, ArticleTitle,  ArticleBodyDesc, ArticlePublishDate FROM art_Articles";
                    strSql += " WHERE ArticleID = " + articleID;
                    DataSet ds = DataProvider.Connect_Select(strSql);
                    DateTime dt;
                    if (ds.Tables[0].Rows.Count > 0)
                    {
                        lblArticleTitle.Text = ds.Tables[0].Rows[0]["ArticleTitle"].ToString();
                        //lblPubDate.Text = ds.Tables[0].Rows[0]["ArticlePublishDate"].ToString();
                        lblPubDate.Text = Convert.ToDateTime(ds.Tables[0].Rows[0]["ArticlePublishDate"].ToString()).ToLongDateString();
                        lblArticleDesc.Text = ds.Tables[0].Rows[0]["ArticleBodyDesc"].ToString();
                        //Response.Write ("<script type='text/javascript'>function printpage()  {  window.print();  }</script>");
                        //Page.ClientScript.RegisterStartupScript(GetType(), "MyKey", "printpage()");
                        Page.ClientScript.RegisterStartupScript(this.GetType(), "MyScript", "javascript:printpage();", true);

                    }
                    else
                    {
                        lblArticleDesc.Text = "Article not found";
                    }
                }
                else
                {

                    int articleID = int.Parse(Request["ArticleID"]);
                    Response.Clear();
                    string strSql = "Select ArticleID, ArticleTitle,  ArticleBodyDesc, ArticlePublishDate FROM art_Articles";
                    strSql += " WHERE ArticleID = " + articleID;
                    DataSet ds = DataProvider.Connect_Select(strSql);
                    if (ds.Tables[0].Rows.Count > 0)
                    {
                        lblArticleTitle.Text = ds.Tables[0].Rows[0]["ArticleTitle"].ToString();

                        lblPubDate.Text = Convert.ToDateTime( ds.Tables[0].Rows[0]["ArticlePublishDate"].ToString()).ToLongDateString();
                        lblArticleDesc.Text = ds.Tables[0].Rows[0]["ArticleBodyDesc"].ToString();



                        PrintToPDF();
                    }
                    else
                    {
                        lblArticleDesc.Text = "Article not found";
                    }


                }

            }
            catch (Exception ex)
            {
                Response.Write("Page can't be displayed. Please try later.");
            }
        }
    }

    protected void PrintToPDF()
    {
        try
        {
            string args = string.Format("\"{0}\" - ", Request.Url.AbsoluteUri);
            var startInfo = new ProcessStartInfo(Server.MapPath("bin\\wkhtmltopdf.exe"), args)
            {
                UseShellExecute = false,
                CreateNoWindow = true,
                RedirectStandardOutput = true

            };
            var proc = new Process { StartInfo = startInfo };
            proc.Start();

            string output = proc.StandardOutput.ReadToEnd();
            byte[] buffer = proc.StandardOutput.CurrentEncoding.GetBytes(output);
            proc.WaitForExit();
            proc.Close();
            Response.ContentType = "application/pdf";
            Response.AddHeader("Content-Disposition", "attachment;filename=download.pdf");
            Response.BinaryWrite(buffer);
            Response.End();


        }
        catch (Exception ex)
        {
            string xx = ex.Message.ToString();
            Response.Write("<br>" + xx);
        }
    }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

傻比既视感 2025-01-10 13:05:54

你的问题是符合的。

string args = string.Format("\"{0}\" - ", Request.Url.AbsoluteUri);

当您使用相同的页面 url 和参数调用 wkhtmltopdf.exe 时,wkhtmltopdf.exe 会再次调用您的页面,因此您的页面会再次调用 wkhtmltopdf.exe :)

要解决此问题,您可以使用额外的查询字符串调用 wkhtmltopdf.exe 并在加载时查看这个查询字符串,并没有调用wkhtmltopdf.exe。

your problem is in line.

string args = string.Format("\"{0}\" - ", Request.Url.AbsoluteUri);

when you call wkhtmltopdf.exe with same page url and parameters, wkhtmltopdf.exe calls your page again, so your page calls wkhtmltopdf.exe againg :)

to solve this problem you can call wkhtmltopdf.exe with an extra querystring an on load look at this query string, and not call wkhtmltopdf.exe.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文