SelectPdf for .NET - Advanced Pdf Security Settings and Digital Signatures - C# / ASP.NET MVC Sample

This sample shows how to modify security settings of an existing 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).

Here is our initial test pdf document:
Test file

The pdf document encryption can be done using either RC4 or AES algorithm, using 40 bit, 128 bit or 256 bit encryption keys.

The sample also show how to sign an existing PDF document using a PFX certificate.

Sample PFX certificate file:
Certificate

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.


Sample Code C#



using System.Web.Mvc;

namespace SelectPdf.Samples.Controllers
{
    public class AdvancedPdfSecurityController : Controller
    {
        // GET: AdvancedPdfSecurity
        public ActionResult Index()
        {
            return View();
        }
        [HttpPost]
        public ActionResult SubmitAction(FormCollection collection)
        {

            // the initial file
            string file = Server.MapPath("~/files/doc1.pdf");

            // the certificate
            string certFile = Server.MapPath("~/files/selectpdf.pfx");

            // load the pdf document using the advanced security manager
            PdfSecurityManager security = new PdfSecurityManager();
            security.Load(file);

            // encryption algorithm and key length
            security.EncryptionAlgorithm = PdfEncryptionAlgorithm.AES;
            security.EncryptionKeySize = PdfEncryptionKeySize.EncryptKey256Bit;

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

            //set document permissions
            security.CanAssembleDocument = false;
            security.CanCopyContent = true;
            security.CanEditAnnotations = true;
            security.CanEditContent = true;
            security.CanFillFields = true;
            security.CanPrint = true;

            // add the digital signature
            security.Sign(certFile, "selectpdf");

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

            // close pdf document
            security.Close();                                 

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