Archive for tag: PDF Generation with HTML

PDF Generation with HTML tags and background image in C#

Generate PDF in C# including Background Image and HTML Tags, I have been through many blogs but there are very few blogs that they have explained to include background image while generating PDFs, so though it's worth creating C# Program and writing blog.

Step 1:

Once you have created your solution, then you have to download iTextSharp in this zip file you will have DLLs so Add Reference to your solution.

Step 2:

Now add following line of code to to reference the code

using iTextSharp.text;
using iTextSharp.text.pdf;

Step 3:

Following is code for it: 

 

        void PDF_Generation_With_HTML_And_Background_Image()
        {

            //setting ContentType
            Response.ContentType = "application/pdf";

            //setting up PDF header and filename
            Response.AddHeader("content-disposition", "attachment;filename=filename.pdf");

            Response.Cache.SetCacheability(HttpCacheability.NoCache);

            //getting image & it's path from server
            string imageFilePath = Server.MapPath(".") + "/images/imagename.jpg";

            //creating Image object
            Image imageFile = Image.GetInstance(imageFilePath);

            //Page site and margin left, right, top, bottom is defined
            var pdfDocument = new Document(PageSize.A4, 20f, 0f, 20f, 0f);

            //Resize image depend upon your need
            //here I had Landscape Image
            imageFile.ScaleToFit(800, 800);

            //If you want to choose image as background then,
            imageFile.Alignment = Image.UNDERLYING;

            //Scale Percent of image. 
            //Here we have 50% in float is 50f
            imageFile.ScalePercent(50f);

            //pdf writer will get instance of document
            PdfWriter.GetInstance(pdfDocument, Response.OutputStream);

            pdfDocument.Open();

            pdfDocument.NewPage();

            //html p tag or Pragraph tag
            Paragraph paragraph = new Paragraph("Lorem Ipsum is simply dummy text of the printing and typesetting " + 
                "industry.\n\n Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an " + 
                "unknown printer took a galley of type and scrambled it to make a type specimen book.");

            pdfDocument.Add(imageFile);

            pdfDocument.Add(paragraph);

            pdfDocument.Close();

            Response.Write(pdfDocument);

            Response.End();
        }

 

Thank you for going through