0

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);
        }
    }
}
Learning
  • 19,469
  • 39
  • 180
  • 373

1 Answers1

0

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.

Vishal Suthar
  • 17,013
  • 3
  • 59
  • 105
Özgür Kara
  • 1,333
  • 10
  • 22
  • I already look for Request["download"] != "yes" if it is yes then i want to call this part of code. I am a novice can you please tell me as a code snippet how i should do it exactly. – Learning Feb 07 '12 at 09:45
  • I called the page print function from main page rather than call the print function withing the page. some how it keep on going in the loop, i tried to change few thing but didn't work. So i decided to call it from the main page and pass the page URL of the page – Learning Feb 07 '12 at 11:16