SelectPdf for .NET - Pdf Image Element Properties - C# / ASP.NET Sample

This sample shows how to create a new PDF document using SelectPdf and add several image elements to it, modifying the properties of these elements.


Sample Code C#



using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using SelectPdf;

namespace SelectPdf.Samples
{
    public partial class pdf_image_element : System.Web.UI.Page
    {
        protected void BtnCreatePdf_Click(object sender, EventArgs e)
        {
            // create a new pdf document
            PdfDocument doc = new PdfDocument();

            // add a new page to the document
            PdfPage page = doc.AddPage();

            // get image path
            string imgFile = Server.MapPath("~/files/logo.png");

            // define a rendering result object
            PdfRenderingResult result;

            // create image element from file path with real image size
            PdfImageElement img1 = new PdfImageElement(0, 0, imgFile);
            result = page.Add(img1);

            // create image element from system Image object with fixed size in pdf 
            // (aspect ratio not preserved)
            System.Drawing.Image img = System.Drawing.Image.FromFile(imgFile);
            PdfImageElement img2 = new PdfImageElement(0, 
                result.PdfPageLastRectangle.Bottom + 50, 100, 100, img);
            result = page.Add(img2);

            // add text element
            PdfFont font1 = doc.AddFont(PdfStandardFont.Helvetica);
            font1.Size = 10;
            PdfTextElement text1 = new PdfTextElement(0, 
                result.PdfPageLastRectangle.Bottom + 50, Helper.SomeText(), font1);
            page.Add(text1);

            // add image over text (no transparency)
            PdfImageElement img3 = new PdfImageElement(0, 
                result.PdfPageLastRectangle.Bottom + 50, imgFile);
            result = page.Add(img3);

            // add image over text (with transparency) next to the previous image
            PdfImageElement img4 = new PdfImageElement(
                result.PdfPageLastRectangle.Right + 30, 
                result.PdfPageLastRectangle.Top, imgFile);
            img4.Transparency = 50;
            result = page.Add(img4);

            // save pdf document
            doc.Save(Response, false, "Sample.pdf");

            // close pdf document
            doc.Close();
        }
    }
}