Converting an HTML to PDF in C#/ASP.NET Tutorial

Language

This is a C#/ASP.NET tutorial for converting an HTML to a PDF. This tutorial can be useful for those students or newbies in the said programming language that are planning to develop web application projects that can generate reports into a PDF File. I have also provided a tutorial demo video about the said tutorial.

Here's the following script that I used to develop the simple C#/ASP.NET Project that has the feature of converting the HTML to a PDF. The simple application provides a simple page that shows a simple button that executes the conversion process and opens up a new tab in the browser to Display/downloads the Converted PDF File.

Creating the Interface

The script below is the code for the page interface where user will browse to find the button to convert HTML to PDF. The button function is being executed using jQuery (JavaScript Library).

SampleReportPage.aspx

  1. <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="SampleReportPage.aspx.cs" Inherits="PDFReportSample.SampleReportPage" %>
  2. <!DOCTYPE html>
  3. <html xmlns="http://www.w3.org/1999/xhtml">
  4. <head runat="server">
  5. <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js" integrity="sha512-894YE6QWD5I59HgZOGReFYm4dnWc1Qt5NtvYSaNcOP+u1T9qYdvdihz0PPSiiqn/+/3e7Jo4EaG7TubfWGUrMQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
  6. <title>Sample PDF Report Page</title>
  7. </head>
  8. <form id="form1" runat="server">
  9. <div>
  10. <button type="button" class="pdf-report">PDF Report</button>
  11. </div>
  12. </form>
  13. </body>
  14.  
  15. <script type="text/javascript">
  16. $(document).on("click", ".pdf-report", function () {
  17. $.ajax({
  18. url: "WebService/ReportService.asmx/PDFReportGenerate",
  19. data: '{}',
  20. contentType: "application/json; charset=utf-8",
  21. dataType: "json",
  22. type: "POST",
  23. success: function (response) {
  24. if (response.d.length > 0) {
  25. window.open(response.d[0].pdfReportPath);
  26. }
  27. },
  28. error: function (response) {
  29. alert(response.responseText);
  30. }
  31. });
  32. });
  33.  
  34.  
  35. </html>

Report Service

The following script is the code converting the HTML into a PDF. This codes being executed using Ajax Request in the Sample Report Page.

WebService/ReportService.asmx

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Web;
  5. using System.Web.Services;
  6. using PDFReportSample.Models;
  7. using iText.Html2pdf;
  8. using System.IO;
  9.  
  10. namespace PDFReportSample.WebService
  11. {
  12. /// <summary>
  13. /// Summary description for ReportService
  14. /// </summary>
  15. [WebService(Namespace = "http://tempuri.org/")]
  16. [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
  17. [System.ComponentModel.ToolboxItem(false)]
  18. // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
  19. [System.Web.Script.Services.ScriptService]
  20. public class ReportService : System.Web.Services.WebService
  21. {
  22.  
  23. public int PDFReport(string baseuri,string html,string destination)
  24. {
  25. try
  26. {
  27. ConverterProperties prop = new ConverterProperties();
  28. prop.SetBaseUri(baseuri);
  29. HtmlConverter.ConvertToPdf(html, new FileStream(destination, FileMode.Create), prop);
  30. return 1;
  31. }
  32. catch
  33. {
  34. return 0;
  35. }
  36. }
  37.  
  38. [WebMethod]
  39. public List<ReportModel> PDFReportGenerate()
  40. {
  41. List<ReportModel> _li = new List<ReportModel>();
  42. ReportModel rd = new ReportModel();
  43.  
  44. try
  45. {
  46. string html = "";
  47. html = @"<!DOCTYPE html><html><head><meta charset='utf-8'><link href='css/style.css' rel='stylesheet'><title></title></head><body><table class='tbl'><thead><tr><th class='style0' colspan='2'><img src='img/logo.png' style='width:180px'></th><th class='style1' colspan='4'><p style='font-size:24px;padding-bottom:2px;padding-top:2px;font-weight:700;margin-bottom:1px'>INVOICE</p>ID-2021-0024<br>Issue Date:21/09/2021<br>Delivery Date: 22/09/2021<br>Due Date:30/09/2021<br><br><p style='font-size:24px;padding-bottom:2px;padding-top:2px;font-weight:700;margin-bottom:1px'>CLIENT DETAILS</p>Client 1<br>GST Number:XXXXXXXXXX</th></tr></thead><tbody><tr><td class='headstyle0' colspan='5' style='padding-top:60px'></td></tr><tr><td class='style3a'>ITEM</td><td class='style3a'>DESCRIPTION</td><td class='style3a'>QUANTITY</td><td class='style3a'>UNIT PRICE</td><td class='style3a'>TOTAL</td></tr><tr><td class='style3'>Item-1</td><td class='style3'>Description -1</td><td class='style3'>2 Pkt</td><td class='style3'>90.00</td><td class='style3b'>180.00</td></tr><tr><td class='style3'>Item-2</td><td class='style3'>Description-2</td><td class='style3'>5 Pkt</td><td class='style3'>35.00</td><td class='style3b'>175.00</td></tr><tr><td class='style3'>Item-3</td><td class='style3'>Description-3</td><td class='style3'>5 Kg</td><td class='style3'>50.00</td><td class='style3b'>250.00</td></tr><tr><td class='style3'>Item-4</td><td class='style3'>Description-4</td><td class='style3'>5 Kg</td><td class='style3'>150.00</td><td class='style3b'>750.00</td></tr><tr><td class='style3'>Item-5</td><td class='style3'>Description-5</td><td class='style3'>5 Kg</td><td class='style3'>100.00</td><td class='style3b'>500.00</td></tr><tr><td class='style0' colspan='2' rowspan='3'></td><td class='style3' colspan='2'>Total</td><td class='style3b'>1855.00</td></tr><tr><td class='style3' colspan='2'>GST@18%</td><td class='style3b'>333.90</td></tr><tr><td class='style3' colspan='2'>Net Payable Amount</td><td class='style3b'>2188.90</td></tr><tr><td class='style0' colspan='5' style='padding-top:100px'></td></tr><tr><td class='style0' colspan='5' style='background-color:#f0f8ff;border-radius:2px'><i>Note:Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</i></td></tr><tr><td class='style1' colspan='5' style='padding-top:200px'>Thank You<br><b>CodeSample</b></td></tr></tbody></table></body></html>";
  48.  
  49. string fpath = Server.MapPath("~\\Report\\");
  50. string _filename = System.Guid.NewGuid().ToString();
  51. string file = fpath + _filename + ".pdf";
  52.  
  53. int pdf = PDFReport("https://localhost:44359", html, file);
  54. if (pdf > 0)
  55. {
  56. rd.pdfReportPath = "\\Report\\" + _filename + ".pdf";
  57. }
  58. else
  59. {
  60. rd.pdfReportPath = "";
  61. }
  62. _li.Add(rd);
  63. return _li;
  64. }
  65. catch
  66. {
  67. return null;
  68. }
  69. }
  70. }
  71. }

Tutorial Video

Tutorial Video Link: https://www.youtube.com/watch?v=-WBoON2vyEk

That's it! I hope this will help you with what you are looking for and you'll find this tutorial useful for your future projects.

Enjoy Coding :)

Note: Due to the size or complexity of this submission, the author has submitted it as a .zip file to shorten your download time. After downloading it, you will need a program like Winzip to decompress it.

Virus note: All files are scanned once-a-day by SourceCodester.com for viruses, but new viruses come out every day, so no prevention program can catch 100% of them.

FOR YOUR OWN SAFETY, PLEASE:

1. Re-scan downloaded files using your personal virus checker before using it.
2. NEVER, EVER run compiled files (.exe's, .ocx's, .dll's etc.)--only run source code.

Add new comment