HTML to PDF Converter ASP.NET Core samples · .NET 10 and .NET 11

ExpertPdf Html To Pdf Converter for .NET - Digital Signatures - C# / ASP.NET Sample

Digital signatures can be added to a PDF document using PdfDigitalSignatureElement objects. Adding a digital signature requires a PKCS#12 certificate (provided as a .pfx or a .p12 file).

Sample certificate file:
Certificate

The following sample shows how to add a digital signature to a pdf document using ExpertPdf HtmlToPdf Converter for .NET.

IMPORTANT: Please note that the certificate used is a self signed certificate generated for testing purposes only. The signature will appear as not valid in a pdf viewer. Using a valid certificate will result in a valid digital signature.

C# code of this sample

Pages/DigitalSignatures.cshtml.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using ExpertPdf.HtmlToPdf.PdfDocument;

namespace ExpertPdf.Samples.Pages
{
    public class DigitalSignaturesModel : PageModel
    {
        public void OnGet()
        {
        }

        public IActionResult OnPost()
        {
            // create a new pdf document
            Document doc = new Document();

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

            // get image path 
            // the image will be used to display the digital signature over it
            string imgFile = Startup.ServerPath + @"\wwwroot\images\logo.png";

            // get certificate path
            string certFile = Startup.ServerPath + @"\wwwroot\files\oss.pfx";

            // define a rendering result object
            AddElementResult result;

            // create image element from file path 
            ImageElement img = new ImageElement(0, 0, imgFile);
            result = page.AddElement(img);

            // get the #PKCS12 certificate from file
            DigitalCertificatesCollection certificates =
                DigitalCertificatesStore.GetCertificates(certFile, "osspswd");
            DigitalCertificate certificate = certificates[0];

            // create the digital signature object
            DigitalSignatureElement signature =
                new DigitalSignatureElement(result.EndPageBounds, certificate);
            signature.Reason = "ExpertPdf";
            signature.ContactInfo = "ExpertPdf";
            signature.Location = "ExpertPdf";
            page.AddElement(signature);

            // 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 = "Sample.pdf";
            return fileResult;

        }
    }
}