Convert HTML String To PDF Using Aspose.PDF API

In today's modern application reporting part is very important to fulfill the clients complicated requirements . However in today's client based technologies applications like pure HTML or ASP.NET MVC application using Reporting server such as SSRS or other is very risky in terms of performance and maintenance so the best way to deal with this problems is to make Invoice or reporting template in HTML format and convert it into the PDF or other format as per requirements with the help of Aspose.Pdf etc.
In MVC application there is often need to convert HTML to PDF format So in this article we will learn how to convert HTML to PDF using Aspose.PDF for .NET . So lets learn step by step how to achieve this task in easy way.
We will cover following points about Aspose.PDF for .NET with sample ASP.NET MVC application including
  • What is Aspose.PDF ?
  • Aspose.Pdf features.
  • Creating ASP.NET MVC application to use Aspose.PDF. 
  • Add reference of Aspose.Pdf for .NET APIs from NuGet package manager using visual studio 2015.
  • Purchase or get the temporary license of  Aspose.Pdf for .NET product.
  • Applying and how to Aspose.Pdf license in .NET project.
  • Ensuring Aspose.Pdf license is applied or not .
  • How to convert HTML to PDF using Aspose.Pdf for .NET APIs .
What is Aspose.PDF?
Aspose.Pdf for .NET is a set of PDF APIs for document creation and manipulation that enables your .NET applications to read, write and manipulate existing PDF documents without using Adobe Acrobat. It also allows you to create forms and manage form fields embedded in a PDF document.
This APIs are written in managed C# and it allows developers to add PDF Creation and manipulation functionality to their Microsoft .NET application.
Following are the some key and incredible features of Aspose.Pdf APIs.
  • PDF compression options.
  • Table creation and manipulation.
  • Support for graph objects.
  • Extensive hyperlink functionality.
  • Extended security controls.
  • custom font handling.
  • Integration with data sources.
  • Add or remove bookmarks.
  • Create table of contents.
  • Add , update , delete extract or insert pages.
  • Transform pages to image.
  • Print Pdf documents.
So lets demonstrate preceding explanation with practically by creating one simple ASP.NET MVC application
Step 1: Create an MVC Application. Now let us start with a step by step approach from the creation of a simple MVC application as in the following:
  1. "Start", then "All Programs" and select "Microsoft Visual Studio 2015".
  2. "File", then "New" and click "Project", then select "ASP.NET Web Application Template", then provide the Project a name as you wish and click OK. After clicking, the following window will appear:
 Step 2 : Add The Reference of Aspose.PDF into project
Now the next step is to add the reference of Aspose.PDF APIs into our created MVC Project. Here are the steps:
  1. Right click on Solution ,find Manage NuGet Package manager and click on it.
  2. After as shown into the image and type in search box "Aspose.PDF".
  3. Select Aspose.PDF as shown into the image .
  4. Choose version of Aspose.PDF APIs and click on install button.

After successfully installation of Aspose.PDF APIs into ASP.NET MVC project , The added reference of Aspose.PDF APIs will be look like as follows into our created MVC application solution as

In preceding image you can see that Aspose.Pdf APIs is successfully installed in our project.
Step 3: Create Model Class
Now let us create the model class file named InvoiceModel.cs by right clicking on model folder as in the following screenshot:

Note:
It is not mandatory that Model class should be in Models folder, it is just for better readability; you can create this class anywhere in the solution explorer. This can be done by creating different folder names or without folder name or in a separate class APIs .
InvoiceModel.cs class file code snippet:
using System.ComponentModel.DataAnnotations;

namespace ConvertHTMLToPDFUsingAspose.Models
{
    public class InvoiceModel
    {
        [Display(Name ="Customer Name")]
        public string CustomerName { get; set; }
        [Display(Name = "Transaction Ref.")]
        public string TransactionRef { get; set; }
        [Display(Name = "Transaction Date")]
        public string TransactionDate { get; set; }
        [Display(Name = "Transaction Amount")]
        public string TransactionAmount { get; set; }
        public string Status { get; set; }
       
    }
}
Step 4: Add Controller Class.
Now let us add the MVC 5 controller as in the following screenshot:
 After clicking on Add button it will show the window. Specify the Controller name as Home with suffix Controller.
Note:
  • Controller name must be having suffix as 'Controller' after specifying the name of controller.
Step 5: Create Method into the HomeController.cs file.
Now modify the default code in HomeController.cs class file to convert HTML to PDF using Aspose.PDF , After modifying code will look like as follows,
HomeController.cs
using Aspose.Pdf;
using ConvertHTMLToPDFUsingAspose.Models;
using System;
using System.IO;
using System.Text;
using System.Web.Mvc;

namespace ConvertHTMLToPDFUsingAspose.Controllers
{

    public class HomeController : Controller
    {           // GET: Home
        public ActionResult HTMLToPDF()
        {
            InvoiceModel Invoice = new InvoiceModel();
            Invoice.CustomerName = "Vithal Wadje";
            Invoice.TransactionDate = DateTime.Now.ToString("dd-MM-yyy");
            Invoice.TransactionRef = "CMD0152PAY";
            Invoice.TransactionAmount = "4000.00";
            Invoice.Status = "Success";
            return View(Invoice);
        }

        [HttpPost]
        public ActionResult HTMLToPDF(int? id)
        {

       //Consider this data coming from database
            InvoiceModel Obj = new InvoiceModel();
            Obj.CustomerName = "Vithal Wadje";
            Obj.TransactionDate = DateTime.Now.ToString("dd-MM-yyy");
            Obj.TransactionRef = "CMD0152PAY";
            Obj.TransactionAmount = "4000.00";
            Obj.Status = "Success";

            string PdfHtmlTemplate = @"<table border=2 width=100%"+">" +@" 
               <tbody><tr>
  
                  <td>
                      Customer Name
                  </td>
  
                  <td>
                     "+Obj.CustomerName+ @"
                  </td> 
              </tr> 
              <tr> 
                  <td>
                      Transaction Ref.  
                  </td>  
                  <td> " + Obj.TransactionRef + @" </td>
  
              </tr>
  
              <tr>
                  <td>
                      Transaction Date
                  </td>
  
                  <td> " + Obj.TransactionDate + @" </td >
  
              </tr>
  
              <tr>
  
                  <td>
                      Transaction Amount
                  </td >
  
                  <td> " + Obj.TransactionAmount + @" </td>
  
              </tr>
  
              <tr>
  
                  <td>
                      Status
                  </td>
  
                  <td> " + Obj.Status + @" </td>
  
              </tr>
  

          </tbody></table>";

            Aspose.Pdf.License Objpdflicense = new Aspose.Pdf.License();
            Objpdflicense.SetLicense(@"E:\Aspose\Aspose.Pdf.lic");
            Objpdflicense.Embedded = true;
            //Check if licensed applied
            if (Document.IsLicensed)
            {
                //Set the properties for PDF file page format         
                HtmlLoadOptions objLoadOptions = new HtmlLoadOptions();
                objLoadOptions.PageInfo.Margin.Bottom = 10;
                objLoadOptions.PageInfo.Margin.Top = 20;

                //Load HTML string into MemoryStream using Aspose document class
                Document doc = new Document(new MemoryStream(Encoding.UTF8.GetBytes(PdfHtmlTemplate)), objLoadOptions);
                string FileName = "Compilemode_" + DateTime.Now.ToString("dd-MM-yyyy")+".pdf";
                //Save PDF file on local hard drive or database or as you wish          
                doc.Save(@"E:\Saved Files\" + FileName);
            }
       
           return View(Obj);
        }

    }
}
Step 6: Create strongly typed view named HTMLToPDF using InvoiceModel class .
Right click on View folder of created application and choose add view , select InvoiceModel class and choose 'List' scaffolding template as.
 Click on Add button then it will create the view named HTMLToPDF , Now open the HTMLToPDF.cshtml view, Then some default code you will see which is generated by MVC scaffolding template, Now modify default code to make as per our requirements, After modifying the code it will look like as in the following,
HTMLToPDF.cshtml
@model ConvertHTMLToPDFUsingAspose.Models.InvoiceModel

@{
    ViewBag.Title = "www.compilemode.com";
}
@using (Html.BeginForm()) 
{
    @Html.AntiForgeryToken()
    
    <div class="form-horizontal">
        <hr />
        <h4>Using Aspose.Pdf for .NET</h4>
        <hr />
        <table class="table-bordered table"> 
            <tr>
                <td>
                    @Html.DisplayNameFor(model => model.CustomerName)
                </td>
                <td>
                    @Html.DisplayFor(model => model.CustomerName)
                </td>
            </tr>
            <tr>
                <td>
                    @Html.DisplayNameFor(model => model.TransactionRef)
                </td>
                <td>@Html.DisplayFor(model => model.TransactionRef)</td>
            </tr>
            <tr>
                <td>
                    @Html.DisplayNameFor(model => model.TransactionDate)
                </td>
                <td>@Html.DisplayFor(model => model.TransactionDate)</td>
            </tr>
            <tr>
                <td>
                    @Html.DisplayNameFor(model => model.TransactionAmount)
                </td>
                <td>@Html.DisplayFor(model => model.TransactionAmount)</td>
            </tr>
            <tr>
                <td>
                    @Html.DisplayNameFor(model => model.Status)
                </td>
                <td>@Html.DisplayFor(model => model.Status)</td>
            </tr>
            
        </table>
        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Export To PDF" class="btn btn-primary" />
            </div>
        </div>
    </div>
}

<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
Now after adding the Model, View and controller into our project. The solution explorer will look like as follows
 Now we have done all coding to convert HTML to PDF using Aspose.PDF in ASP.NET MVC

Step 7 : Now run the application.
After running the application the UI will be look like as follows, 

In the preceding Images , lets consider the preceding the transaction receipt which we wants to Export into PDF. Now click on Export to PDF button . It will generate the PDF file in our specified location as.

Now open the files , The contents of the file will be look like as follows


I hope from all preceding examples we have learned how to convert HTML to PDF using Aspose.PDF in ASP.NET MVC.
Note:

  • Download the Zip file of the sample application for a better understanding.
  • Since this is a demo, it might not be using proper standards, so improve it depending on your skills.
Summary
I hope this article is useful for all readers. If you have any suggestions please contact me.

Read more articles on ASP.NET MVC and ASPOSE:
Download Aspose : API To Create and Convert Files

Post a Comment

www.CodeNirvana.in

Protected by Copyscape Online Copyright Protection
Copyright © Compile Mode