SelectPdf for .NET 10 - Pdf Image Element Properties - C# / .NET 10 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.IO;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using SelectPdf.Universal;

namespace SelectPdf.Samples.Pages
{
    public class PdfImageElementModel : PageModel
    {
        public void OnGet()
        {

        }

        public IActionResult OnPost()
        {
            // 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 = Path.Combine(Startup.ServerPath, "wwwroot", "images", "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 file path with fixed size in pdf
            // (aspect ratio not preserved)
            PdfImageElement img2 = new PdfImageElement(0,
                result.PdfPageLastRectangle.Bottom + 50, 100, 100, imgFile);
            result = page.Add(img2);

            // add text element
            PdfFont font1 = doc.Fonts.Add(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
            byte[] pdf = doc.Save();

            // close pdf document
            doc.Close();

            // return resulted pdf document
            FileResult fileResult = new FileContentResult(pdf, "application/pdf");
            fileResult.FileDownloadName = "Document.pdf";
            return fileResult;

        }
    }
}