SelectPdf for .NET 10 - Pdf Security Settings - C# / .NET 10 Sample

This sample shows how to create a new PDF document using SelectPdf, how to set a password to be able to view or modify the document (password: 'test1' and 'test2') and also specifies user permissions for the pdf document (if the user can print, copy content, fill forms, modify, etc).

Encryption:


Encrypt the XMP metadata

Inspect or Remove the Security

PdfSecurityManager.GetSecurityInfo reads the security settings of a loaded pdf document: its encryption, its permissions and the signatures it carries. PdfSecurityManager.RemoveSecurity clears both passwords, grants every permission and saves the document without encryption. Upload an encrypted pdf document, or leave the field empty to use the document created by this page (with the encryption chosen above), and enter its password (the owner password 'test1' gives full access).

Encrypted PDF (optional):


Password:

Sample code · C#
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.AspNetCore.Mvc.Rendering;
using SelectPdf.Universal;

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

        }

        [BindProperty]
        public string DdlEncryption { get; set; } = "AES256R6";

        public List<SelectListItem> Encryptions { get; } = new List<SelectListItem>
        {
            new SelectListItem { Value = "RC4_40", Text = "RC4, 40-bit key" },
            new SelectListItem { Value = "RC4_128", Text = "RC4, 128-bit key" },
            new SelectListItem { Value = "AES128", Text = "AES, 128-bit key" },
            new SelectListItem { Value = "AES256", Text = "AES, 256-bit key, revision 5" },
            new SelectListItem { Value = "AES256R6", Text = "AES, 256-bit key, revision 6 (default)" },
            new SelectListItem { Value = "AESGCM", Text = "AES-256-GCM (PDF 2.0)" },
        };

        [BindProperty]
        public bool ChkEncryptMetadata { get; set; } = true;

        // an encrypted pdf document to inspect or unprotect (optional; the document this page
        // creates is used when none is uploaded) and its password
        [BindProperty]
        public IFormFile FileEncrypted { get; set; }

        [BindProperty]
        public string TxtPassword { get; set; } = "test1";

        // the security settings shown on the page
        public PdfSecurityInfo SecurityInfo { get; private set; }

        public string InspectedDocument { get; private set; }

        public IActionResult OnPost()
        {
            // create an encrypted pdf document
            byte[] pdf = CreateEncryptedDocument();

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

        public IActionResult OnPostInfo()
        {
            // load the encrypted document in a security manager
            PdfSecurityManager manager = LoadEncryptedDocument();
            if (manager == null)
                return Page();

            // read the security settings of the document as it was loaded: its encryption,
            // its permissions and the signatures it carries
            SecurityInfo = manager.GetSecurityInfo();
            manager.Close();

            // show the security settings on the page
            return Page();
        }

        public IActionResult OnPostRemove()
        {
            // load the encrypted document in a security manager
            PdfSecurityManager manager = LoadEncryptedDocument();
            if (manager == null)
                return Page();

            // remove the security: both passwords are cleared, every permission is granted
            // and the document is saved without encryption
            manager.RemoveSecurity();
            byte[] pdf = manager.Save();
            manager.Close();

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

        // loads the uploaded document, or the document this page creates, with the password
        // entered on the page (the owner password gives full access); null when it cannot be opened
        private PdfSecurityManager LoadEncryptedDocument()
        {
            byte[] pdf;
            if (FileEncrypted != null && FileEncrypted.Length > 0)
            {
                using (MemoryStream ms = new MemoryStream())
                {
                    FileEncrypted.CopyTo(ms);
                    pdf = ms.ToArray();
                }
                InspectedDocument = Path.GetFileName(FileEncrypted.FileName);
            }
            else
            {
                pdf = CreateEncryptedDocument();
                InspectedDocument = "the document created by this page";
            }

            PdfSecurityManager manager = new PdfSecurityManager();
            try
            {
                manager.Load(pdf, TxtPassword ?? "");
            }
            catch (PdfDocumentException ex)
            {
                // for example: the password is wrong
                manager.Close();
                ViewData["Message"] = "An error occurred: " + ex.Message;
                return null;
            }
            return manager;
        }

        private byte[] CreateEncryptedDocument()
        {
            // create a new pdf document
            PdfDocument doc = new PdfDocument();

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

            // create a new pdf font
            PdfFont font = doc.Fonts.Add(PdfStandardFont.Helvetica);
            font.Size = 20;

            // create a new text element and add it to the page
            PdfTextElement text = new PdfTextElement(50, 50,
                "Pdf Security Settings Sample.", font);
            page.Add(text);

            // set document passwords
            doc.Security.OwnerPassword = "test1";
            doc.Security.UserPassword = "test2";

            // set the encryption strength: the key size and the algorithm
            switch (DdlEncryption)
            {
                case "RC4_40":
                    doc.Security.KeySize = PdfEncryptionKeySize.EncryptKey40Bit;
                    doc.Security.Algorithm = PdfEncryptionAlgorithm.RC4;
                    break;
                case "RC4_128":
                    doc.Security.KeySize = PdfEncryptionKeySize.EncryptKey128Bit;
                    doc.Security.Algorithm = PdfEncryptionAlgorithm.RC4;
                    break;
                case "AES128":
                    doc.Security.KeySize = PdfEncryptionKeySize.EncryptKey128Bit;
                    doc.Security.Algorithm = PdfEncryptionAlgorithm.AES;
                    break;
                case "AES256":
                    doc.Security.KeySize = PdfEncryptionKeySize.EncryptKey256Bit;
                    doc.Security.Algorithm = PdfEncryptionAlgorithm.AES;
                    break;
                case "AESGCM":
                    // AES-256-GCM, defined by PDF 2.0: the document is written as PDF 2.0
                    doc.Security.KeySize = PdfEncryptionKeySize.EncryptKey256Bit;
                    doc.Security.Algorithm = PdfEncryptionAlgorithm.AESGCM;
                    break;
                default:
                    // AES with a 256-bit key, revision 6, is the default: setting a password is enough
                    // (the explicit assignment is shown for completeness)
                    doc.Security.KeySize = PdfEncryptionKeySize.EncryptKey256BitRevision6;
                    doc.Security.Algorithm = PdfEncryptionAlgorithm.AES;
                    break;
            }

            // encrypt the XMP metadata stream too (the default); when false, the metadata stays readable
            // for indexing and archiving tools while the content is encrypted
            doc.Security.EncryptMetadata = ChkEncryptMetadata;

            //set document permissions
            doc.Security.CanAssembleDocument = false;
            doc.Security.CanCopyContent = true;
            doc.Security.CanAccessibilityCopyContent = true;
            doc.Security.CanEditAnnotations = true;
            doc.Security.CanEditContent = true;
            doc.Security.CanFillFormFields = true;
            doc.Security.CanPrint = true;

            // save pdf document
            byte[] pdf = doc.Save();

            // close pdf document
            doc.Close();

            return pdf;
        }
    }
}