PDF Password Protection

This demo shows how to protect a PDF document with a password using the PDF Document API. Specify protection options and user permissions on the Options pane and click Protect and Save to download the resulting document to your computer.

Options
Owner Password
User Password
Algorithm
Printing
Data Extraction
Modification
Interactivity
Protect and Save
@model AspNetCoreDemos.OfficeFileAPI.PdfPreviewModel

<img id="previewImage" src="@Url.Action(Model.PreviewDocumentAction, Model.ControllerName)" class="preview-image-bordered @(Model.IsViewWithoutSidePanel ? "preview-image-without-side-panel" : "preview-image-with-side-panel")" />

<script type="text/javascript">
    PdfPreview = {
        basePath: '@Url.Action(Model.PreviewDocumentAction, Model.ControllerName)',
        Update: function (param) {
            var iframeElement = document.getElementById("previewImage");
            if (!iframeElement)
                return;
            var additionalParams = "&" + new Date().valueOf();
            if (param)
                additionalParams = param;
            iframeElement.src = this.basePath + "?" + additionalParams;
        }
    };
</script>
@model AspNetCoreDemos.OfficeFileAPI.PdfPasswordProtectionModel
@using DevExtreme.AspNet.Mvc

@{ Html.BeginForm("PdfPasswordProtect", "DocumentProtection", FormMethod.Post, new { id = "PdfPasswordProtectForm" }); }

<script type="text/javascript">
    function Validate() {
        if ($("#OwnerPassword").dxTextBox('instance').option('value') == null && $("#UserPassword").dxTextBox('instance').option('value') == null)
            alert('Please specify at least one password to protect the document.');
        else
            $("#PdfPasswordProtectForm").submit();
    }
</script>

<div class="demo-view-container demo-preview-border">
    @(Html.DevExtreme().ScrollView()
                       .ID("scrollview")
                       .ScrollByContent(true)
                       .ScrollByThumb(true)
                       .ShowScrollbar(ShowScrollbarMode.OnHover)
                       .Direction(ScrollDirection.Both)
                       .Height("580px")
                       .Content(@<text>
                            <div id="scrollview-content">
                               @await Html.PartialAsync("PdfFileView", Model.PreviewModel)
                            </div>
                       </text>)
    )
</div>

<div class="options">
    <div class="caption">Options</div>
    <div class="option">
        <div class="label">Owner Password</div>
        @(Html.DevExtreme().TextBoxFor(m => m.OwnerPassword)
                           .ID("OwnerPassword")
                           .Mode(TextBoxMode.Password))
    </div>
    <div class="option">
        <div class="label">User Password</div>
        @(Html.DevExtreme().TextBoxFor(m => m.UserPassword)
                           .ID("UserPassword")
                           .Mode(TextBoxMode.Password))
    </div>
    <div class="option">
        <div class="label">Algorithm</div>
        @(Html.DevExtreme().SelectBoxFor(m => m.EncryptionAlgorithm)
                           .DataSource(Html.GetEnumSelectList<DevExpress.Pdf.PdfEncryptionAlgorithm>()
                           .Select(i => new { Value = int.Parse(i.Value), Text = i.Text }))
                           .ValueExpr("Value")
                           .DisplayExpr("Text")
        )
    </div>
    <div class="option">
        <div class="label">Printing</div>
        @(Html.DevExtreme().SelectBoxFor(m => m.AllowPrinting)
                           .DataSource(Html.GetEnumSelectList<DevExpress.Pdf.PdfDocumentPrintingPermissions>()
                           .Select(i => new { Value = int.Parse(i.Value), Text = i.Text }))
                           .ValueExpr("Value")
                           .DisplayExpr("Text")
        )
    </div>
    <div class="option">
        <div class="label">Data Extraction</div>
        @(Html.DevExtreme().SelectBoxFor(m => m.AllowExtraction)
                           .DataSource(Html.GetEnumSelectList<DevExpress.Pdf.PdfDocumentDataExtractionPermissions>()
                           .Select(i => new { Value = int.Parse(i.Value), Text = i.Text }))
                           .ValueExpr("Value")
                           .DisplayExpr("Text")
        )
    </div>
    <div class="option">
        <div class="label">Modification</div>
        @(Html.DevExtreme().SelectBoxFor(m => m.AllowModification)
                           .DataSource(Html.GetEnumSelectList<DevExpress.Pdf.PdfDocumentModificationPermissions>()
                           .Select(i => new { Value = int.Parse(i.Value), Text = i.Text }))
                           .ValueExpr("Value")
                           .DisplayExpr("Text")
        )
    </div>
    <div class="option">
        <div class="label">Interactivity</div>
        @(Html.DevExtreme().SelectBoxFor(m => m.AllowInteractivity)
                           .DataSource(Html.GetEnumSelectList<DevExpress.Pdf.PdfDocumentInteractivityPermissions>()
                           .Select(i => new { Value = int.Parse(i.Value), Text = i.Text }))
                           .ValueExpr("Value")
                           .DisplayExpr("Text")
        )
    </div>
    <div class="option-buttons">
        @(Html.DevExtreme().Button()
                           .Text("Protect and Save")
                           .Type(ButtonType.Default)
                           .StylingMode(ButtonStylingMode.Contained)
                           .OnClick("Validate")
        )
    </div>
</div>
@{ Html.EndForm(); }
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Logging;

namespace AspNetCoreDemos.OfficeFileAPI {
    public partial class DocumentProtectionController : OfficeDemoController {
        public DocumentProtectionController(ILogger<DocumentProtectionController> logger, IWebHostEnvironment hostingEnvironment)
            : base(logger, hostingEnvironment) {
        }
        protected const string TsaServerUriInvalidExceptionString = "ERROR: TSA server URI is invalid or server doesn't support SHA-256 hashing algorithm";
    }
}
using DevExpress.Pdf;
using Microsoft.AspNetCore.Mvc;
using System.IO;

namespace AspNetCoreDemos.OfficeFileAPI {
    public partial class DocumentProtectionController {
        const string passwordProtectionSessionKey = "PasswordProtectionKey";
        const string passwordProtectionDefaultFile = "/Documents/Pdf/PasswordProtection.pdf";

        public IActionResult PdfPasswordProtection() {
            PdfPasswordProtectionModel model = new PdfPasswordProtectionModel();
            return View(model);
        }

        public IActionResult PdfPasswordProtectionPartial() {
            return GetPartialView(passwordProtectionSessionKey, passwordProtectionDefaultFile);
        }

        IActionResult GetPartialView(string sessionKey, string defaultFile) {
            byte[] data;
            if(!HttpContext.Session.TryGetValue(sessionKey, out data)) {
                string filePath = HostingEnvironment.ContentRootPath + defaultFile;
                data = LoadDocument(filePath);
            }

            using(PdfDocumentProcessor processor = new PdfDocumentProcessor()) {
                using(MemoryStream stream = new MemoryStream(data)) {
                    processor.LoadDocument(stream);

                    PdfPageModel pageModel = new PdfPageModel(processor, 1);
                    byte[] image = pageModel.GetPageImageBytes();
                    return new FileContentResult(image, "image/jpeg");
                }
            }
        }

        public IActionResult PdfPasswordProtect(PdfPasswordProtectionModel options) {
            string filePath = HostingEnvironment.ContentRootPath + passwordProtectionDefaultFile;
            Stream stream = options.PasswordProtect(filePath);
            return CreateFileStreamResult(stream, "application/pdf", "pdf", "Result");
        }
    }
}
using System;
using System.Collections.Generic;
using System.IO;
using DevExpress.Pdf;

namespace AspNetCoreDemos.OfficeFileAPI {
    public class PdfModelBase : IDisposable {
        readonly PdfDocumentProcessor processor;
        MemoryStream stream;
        List<PdfPageModel> items = new List<PdfPageModel>();

        public MemoryStream Stream { get { return stream; } }
        protected PdfDocumentProcessor Processor { get { return processor; } }
        protected PdfDocument Document { get { return processor.Document; } }
        public List<PdfPageModel> Items { get { return items; } }

        public string DocumentUrl { get; set; }
        public int PageIndex { get; set; }
        internal virtual string SessionKey { get; }
        public PdfPreviewModel PreviewModel { get; internal set; }

        public PdfModelBase() {
            processor = new PdfDocumentProcessor();
            PreviewModel = new PdfPreviewModel();
        }

        protected void CreateEmptyDocument() {
            stream = new MemoryStream();
            Processor.CreateEmptyDocument(stream);
            Document.Creator = "PDF Document Processor Demo";
            Document.Producer = "Developer Express Inc., " + AssemblyInfo.Version;
            Document.Author = "DevExpress Inc.";
        }

        public virtual void LoadDocument(byte[] data) {
            using(MemoryStream stream = new MemoryStream(data))
                LoadDocument(stream);
        }

        protected void LoadDocument(Stream stream) {
            processor.LoadDocument(stream, true);
            for(int pageNumber = 1; pageNumber <= processor.Document.Pages.Count; pageNumber++)
                Items.Add(new PdfPageModel(processor, pageNumber));
        }

        public void Dispose() {
            if(processor != null)
                processor.Dispose();
            GC.SuppressFinalize(this);
        }
    }
}
using System.ComponentModel;
using System.IO;
using DevExpress.Pdf;

namespace AspNetCoreDemos.OfficeFileAPI {
    public class PdfPasswordProtectionModel : PdfPreviewModelContainer {
        public PdfPasswordProtectionModel() : base("PdfPasswordProtectionPartial", "DocumentProtection") {
            AllowPrinting = PdfDocumentPrintingPermissions.Allowed;
            AllowExtraction = PdfDocumentDataExtractionPermissions.Allowed;
            AllowModification = PdfDocumentModificationPermissions.Allowed;
            AllowInteractivity = PdfDocumentInteractivityPermissions.Allowed;

            EncryptionAlgorithm = PdfEncryptionAlgorithm.AES128;
        }

        [DisplayName("Owner password")]
        public string OwnerPassword { get; set; }

        [DisplayName("User password")]
        public string UserPassword { get; set; }

        [DisplayName("Algorithm")]
        public PdfEncryptionAlgorithm EncryptionAlgorithm { get; set; }

        [DisplayName("Interactivity")]
        public PdfDocumentInteractivityPermissions AllowInteractivity { get; set; }

        [DisplayName("Modification")]
        public PdfDocumentModificationPermissions AllowModification { get; set; }

        [DisplayName("Data extraction")]
        public PdfDocumentDataExtractionPermissions AllowExtraction { get; set; }

        [DisplayName("Printing")]
        public PdfDocumentPrintingPermissions AllowPrinting { get; set; }

        public Stream PasswordProtect(string file) {
            using (PdfDocumentProcessor processor = new PdfDocumentProcessor()) {
                processor.LoadDocument(file);
                PdfEncryptionOptions encryptionOptions = new PdfEncryptionOptions() {
                    OwnerPasswordString = OwnerPassword,
                    UserPasswordString = UserPassword,
                    Algorithm = EncryptionAlgorithm,
                    DataExtractionPermissions = AllowExtraction,
                    PrintingPermissions = AllowPrinting,
                    ModificationPermissions = AllowModification,
                    InteractivityPermissions = AllowInteractivity
                };
                MemoryStream stream = new MemoryStream();
                processor.SaveDocument(stream, new PdfSaveOptions() { EncryptionOptions = encryptionOptions });
                return stream;
            }
        }
    }
}