The Image will be uploaded using FileUpload element and inside the Controller, the Image will be read as Stream and will be added to iTextSharp PDF document and ultimately downloaded as PDF file in ASP.Net MVC Razor.
Create a file upload control, Select the image and click the convert button it will generate the PDF. |
Let's Create a ASP .NET MVC application and using iTextSharp we do our stuff.
Step-1 : Open Visual Studio ( we consider VS 2017) ⇒ File New Project ⇒ ASP .NET MVC as app.
Step-2 : Installing and adding reference of iTextSharp Library
In order to install and add reference of ITextSharp library, Right Click the Project in Solution Explorer and click Manage NuGet Packages from the Context Menu then type iTextSharp as like below;
The above View consists of an HTML FileUpload element and a Submit Button enclosed in a Form element.
The HTML Form has been created using the Html.BeginForm method which accepts the following parameters.
- ActionName – Name of the Action. In this case the name is Index.
- ControllerName – Name of the Controller. In this case the name is Home.
- FormMethod – It specifies the Form Method i.e. GET or POST. In this case it will be set to POST.
- HtmlAttributes – This array allows to specify the additional Form Attributes. Here we need to specify enctype = “multipart/form-data” which is necessary for uploading Files.
Step-4 : Now open HomeController.cs file and add the post method like below to convert Image to PDF. Also add the below namespace as well to use iTextSharp.
using System.IO;
using iTextSharp.text;
using iTextSharp.text.pdf;
The Image File is read from the HttpPostedFileBase parameter and added to the iTextSharp PDF document which will be saved in MemoryStream class object.
Finally the MemoryStream class object is converted to Byte Array and exported and downloaded as PDF file using the File function.
That's it. Run the application and upload a image and click on convert button, it can create a PDF for you and download into your local system as like below;
Summary
Post a Comment