Sand
Sand

Reputation: 11

How to print the data to pdf format?

In my application, the student will fill all the details and then will click the submit button.

It will show all the details of the students in studentDetails.aspx page.

In studentDetails.aspx page, there is a Print button.

What I want is that when a student clicks this print button it should show the details of the students in a PDF file format, ready to be printed.

i've tried the following, can anybody help me to come out of this...`

protected void Button1_Click(object sender, EventArgs e)
    {
        Uri strurl = Request.Url;
        string url = strurl.ToString();

    string filename = "Test";

    HtmlToPdf(url, filename);
}
public static bool HtmlToPdf(string Url, string outputFilename)
{
    string filename = ConfigurationManager.AppSettings["ExportFilePath"] + "\\" + outputFilename + ".pdf";


    Process p = new System.Diagnostics.Process();
    p.StartInfo.Arguments = Url + " " + filename;
    p.StartInfo.UseShellExecute = false;
    p.StartInfo.CreateNoWindow = true;

    p.StartInfo.FileName = HttpContext.Current.Server.MapPath(@"C:\Users\$$\Documents\Visual Studio 2008\Projects\santhu") + "wkhtmltopdf.exe";

    p.StartInfo.RedirectStandardOutput = true;
    p.StartInfo.RedirectStandardError = true;
    p.StartInfo.RedirectStandardInput = true;
    p.Start();
    string output = p.StandardOutput.ReadToEnd();

    p.WaitForExit(60000);

    int returnCode = p.ExitCode;
    p.Close();
    return (returnCode == 0 || returnCode == 2);
}
}

Upvotes: 1

Views: 142

Answers (1)

Mike Perrenoud
Mike Perrenoud

Reputation: 67898

You're going to want to leverage something like the iTextSharp library for this. It's a straight forward solution. Consider the following code block:

using (Document doc = new Document(PageSize.A4, 0, 0, 0, 0))
{
    using (FileStream stream = new FileStream(targetPath, FileMode.Create))
    {
        PdfWriter.GetInstance(doc, stream);

        doc.Open();

        var font = FontFactory.GetFont("Courier", 10);
        var paragraph = new Paragraph(sb.ToString(), font);
        doc.Add(paragraph);

        doc.Close();
    }
}

That takes a text file and turns it into a PDF. Now obviously you'll need to modify it for your needs, but you see how simple it is. Plus the library has classes for all of the concepts of a PDF, not just a Paragraph.

Upvotes: 2

Related Questions