How to Create Dynamic PDF with Image and Content in Asp.Net Development?

  ethanmillar        2015-04-27 01:11:40       13,698        2    

Aegissofttech .net developers are specialized in developing real time web applications. While working on one of such real time web app development projects, our asp.net development team discovered an easy way to create PDF template from user inputs. The developers used Java Script and web service to accomplish PDF template development. To learn how to develop these dynamic PDF with content and graphics, you can follow the below tutorial.

In real time web applications, we often require to generate PDFs as per the User inputs dynamically. Specially while adding image and text in PDF is tough job to write in specific format. So to make it easy, we are introducing how to create PDF template from user inputs using Java script and web service. First of all, we will develop an aspx page to get user inputs like this,

  • Click here to Download JQuery.
  • Create an HTML page for default template and User inputs
<script src="../js/jquery-1.6.2.min.js"></script>
<div class="selectedTemplate clearfix">
            <div class="left" style="width: 55%;">
                <div class="templateBG selectedImage">
                    <img class="templateImage" src="" />
                </div>
            </div>
            <div class="left" style="width: 45%;">
                <div class="templateForm" id="forTemplate5">
                    <p>Complete the following fields to complete the template</p>
                    <p id="pName">
                        <label for="Name">Name</label><br />
                        <input type="text" id="txtName" maxlength="16"/><br />
                    </p>
                    <p>
                        <label for="Date">Date</label><br />
                        <input type="text" id="date" maxlength="12"/><br />
                    </p>
                    <p>
                        <label for="time">Time</label><br />
                        <input type="text" id="time" maxlength="8"/><br />
                    </p>
                    <p>
                        <label for="where">Venue</label><br />
                        <input type="text" id="where" maxlength="10" /><br />
                    </p>
 <p class="topLeftContentPaneDesc" id="pageSize">
<label for="pageSize">Choose Template Page Size:</label><br />
<br />
<input type="radio" name="pageSize" value="A3" checked="checked" />A3<br />
<input type="radio" name="pageSize" value="A4" />A4
</p>
                   </div>
		</div>
<div class="right">
            		<input type="button" id=" btnGeneratePDF'" class="btn" />
       </div>

</div>

  • Create a java script to get image library to upload image and generate PDF template from user inputs.
<script type="text/javascript">
    $(document).ready(function () {
   	//Pdf generate call
        $('#btnGeneratePDF').click(function () {
            var dpid = $('.txtEventID').val();
            var name = $('#txtName').val();
            var date = $('#date').val();
            var time = $('#time').val();
            var where = $('#where').val();
	
           
            var pageSize = $('input[name=pageSize]:checked', '#Form').val();
            $.ajax({
                type: 'POST',
                url: '/TestService.asmx/GenerateTemplatePDF',
                data: JSON.stringify({
                    name: name,
                    date: date,
                    time: time,
                    where: where,
                    
                    pageSize: pageSize
                }),
                contentType: 'application/json; charset=utf-8',
                beforeSend: function (xhr) { xhr.setRequestHeader("Content-type", "application/json; charset=utf-8"); },
                dataType: 'html',
                success: function (data) {
                    if (data) {
                        var result = JSON.parse(data);

                        imgCount = 0;
                        imgLibrary = "";
                    }
                },
                error: function (xhr, e, s) {
                    console.log('Error');
                }
            });
        });

});
  • Create a TestService.asmx page to create web method for generate PDF template.
  • Create GenerateTemplatePDF web method to generate PDF template from User Input.
using System.Xml;
using System.IO;
using iTextSharp.text.pdf;
using iTextSharp.text;
using System.Web.UI;
using iTextSharp.text.html.simpleparser;
using System.Text;

[WebMethod()]  
public string GenerateTemplatePDF(string name, string date, string time, string where, tring pageSize)
    {
        string path = "~/PDFTemplates/";
        Random rnd = new Random();
        string fileName = DateTime.Now.Day.ToString() + DateTime.Now.Month.ToString() + DateTime.Now.Year.ToString() + DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString() + DateTime.Now.Second.ToString() + DateTime.Now.Millisecond.ToString() + rnd.Next().ToString() + ".pdf";
        string sPathToWritePdfTo = string.Concat(Server.MapPath(path), fileName);
        HttpContext.Current.Response.ContentType = "application/pdf";
        HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);
        string backImagePath = string.Empty;
        string backPDFPath = "PDFTemplates /" + fileName;
        try
        {
        if (pageSize.ToString() == "A4")
                {
                    backImagePath = Server.MapPath("~/images/A4Template.jpg");
                    iTextSharp.text.Image jpg = iTextSharp.text.Image.GetInstance(backImagePath);
                    Document pdfDoc = new Document(PageSize.A4.Rotate(), 0f, 0f, 0f, 0f);
                    jpg.Alignment = iTextSharp.text.Image.UNDERLYING;
                    PdfWriter writer = PdfWriter.GetInstance(pdfDoc, new FileStream(sPathToWritePdfTo, FileMode.OpenOrCreate));
                    pdfDoc.Open();
                    pdfDoc.NewPage();

                    PdfContentByte cb = writer.DirectContent;
                    ColumnText ct = new ColumnText(cb);
                    ct.SetSimpleColumn(new Phrase(new Chunk(date, FontFactory.GetFont(FontFactory.HELVETICA, 15, Font.BOLD, BaseColor.WHITE))), 505, 325, 755, 20, 45, Element.ALIGN_CENTER);
                    ct.Go();
                    ct.SetSimpleColumn(new Phrase(new Chunk(time, FontFactory.GetFont(FontFactory.HELVETICA, 15, Font.BOLD, BaseColor.WHITE))), 505, 285, 755, 50, 45, Element.ALIGN_CENTER);
                    ct.Go();

                    ct.SetSimpleColumn(new Phrase(new Chunk(where, FontFactory.GetFont(FontFactory.HELVETICA, 15, Font.BOLD, BaseColor.WHITE))), 505, 240, 755, 50, 45, Element.ALIGN_CENTER);
                    ct.Go();

                    pdfDoc.Add(jpg);
                    pdfDoc.Close();
                }
                else
                {
                    backImagePath = Server.MapPath("~/images/A3Template.jpg");
                    iTextSharp.text.Image jpg = iTextSharp.text.Image.GetInstance(backImagePath);
                    Document pdfDoc = new Document(PageSize.A3.Rotate(), 0f, 0f, 0f, 0f);
                    jpg.Alignment = iTextSharp.text.Image.UNDERLYING;
                    PdfWriter writer = PdfWriter.GetInstance(pdfDoc, new FileStream(sPathToWritePdfTo, FileMode.OpenOrCreate));
                    pdfDoc.Open();
                    pdfDoc.NewPage();
                   
 PdfContentByte cb = writer.DirectContent;
                    ColumnText ct = new ColumnText(cb);

                    ct.SetSimpleColumn(new Phrase(new Chunk(date, FontFactory.GetFont(FontFactory.HELVETICA, 15, Font.BOLD, BaseColor.WHITE))), 1030, 445, 755, 50, 45, Element.ALIGN_CENTER);
                    ct.Go();

                    ct.SetSimpleColumn(new Phrase(new Chunk(time, FontFactory.GetFont(FontFactory.HELVETICA, 15, Font.BOLD, BaseColor.WHITE))), 1030, 385, 755, 50, 45, Element.ALIGN_CENTER);
                    ct.Go();

                    ct.SetSimpleColumn(new Phrase(new Chunk(where, FontFactory.GetFont(FontFactory.HELVETICA, 15, Font.BOLD, BaseColor.WHITE))), 1030, 325, 755, 50, 45, Element.ALIGN_CENTER);
                    ct.Go();
                    pdfDoc.Add(jpg);
                    pdfDoc.Close();
                    
                }
clearFolder(Server.MapPath("~/TempImage"));
return backPDFPath;
}
catch (Exception ex)
{
            return ex.Message;
}
}



Above is the image template and text entered by user which should be correctly formatted in the PDF. And after going through the process above, the output will be as below :

That works like a charm! You can set the text at specific place on Image to look like a complete image template. Such PDFs will helpful to create gift cards, invitations, Thank you messages and lot many.

Hope it helps you too.

Aegissofttech .net developers have shared this tutorial in order to help global asp.net web application development community in developing dynamic PDFs in real time web applications. For queries and doubts, you can comment below and share your experience with us.


Author Bio

 

Ethan Millar - A Technical Writer at Aegis Softtech, where he leads team to covers a wide range of topics like. He has been working on technical content for 7+ years, acquiring and developing content in areas such as Software, IoT, IT News and Technology Trends.

 

ASP.NET DEVELOPMENT 

       

  RELATED


  2 COMMENTS


Anonymous [Reply]@ 2016-10-18 03:48:17

Super...This solution saved me loads of time..Thank u again..

Anonymous [Reply]@ 2020-11-20 08:28:12

Can't seem to get this working in ASP.NET with VB.NET, button click is never calling the Javascript. Can you show the complete code of the HTML page? Where must the Javascript be located?



  RANDOM FUN

First law of software quality