SelectPdf for .NET 10 - Pdf Sanitizing - C# / .NET 10 Sample

This sample shows how to use SelectPdf Library for .NET to sanitize a PDF document from an untrusted source: JavaScript, actions that leave the document, embedded files, multimedia, XFA forms, hidden layers and private data are removed and the file is written whole, while the pages look the same. Scan reports what the document holds without changing it. Rasterize replaces every page with an image of itself instead.

The sample uses the following (existing) test PDF, or a PDF you upload:
Test PDF document

PDF document (optional):

Also remove:
Web links
Invisible text
Metadata
Form fields (flatten)

Rasterize (an image of every page)

Resolution:
dpi

Password (for a protected PDF):


Sample code · C#
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using SelectPdf.Universal;

namespace SelectPdf.Samples.Pages
{
    public class PdfSanitizeModel : PageModel
    {
        public void OnGet()
        {
            TxtResolution = "150";
        }

        // An uploaded PDF document, or nothing - the shipped files/selectpdf.pdf is used then.
        [BindProperty]
        public IFormFile FilePdf { get; set; }

        [BindProperty]
        public string TxtPassword { get; set; }

        [BindProperty]
        public bool ChkExternalLinks { get; set; }

        [BindProperty]
        public bool ChkInvisibleText { get; set; }

        [BindProperty]
        public bool ChkMetadata { get; set; }

        [BindProperty]
        public bool ChkFlattenFormFields { get; set; }

        [BindProperty]
        public bool ChkRasterize { get; set; }

        [BindProperty]
        public string TxtResolution { get; set; }

        // What the scan found, shown on the page.
        public List<string> Found { get; } = new List<string>();

        // Scan: report what the document holds, change nothing.
        public IActionResult OnPostScan()
        {
            try
            {
                using (PdfSanitizeManager sanitizer = Load())
                {
                    PdfSanitizeReport report = sanitizer.Scan();
                    foreach (PdfSanitizeFinding finding in report.Findings)
                        Found.Add(finding.ToString());
                    foreach (string signature in report.Signatures)
                        Found.Add("Signature (removed when sanitized): " + signature);
                    ViewData["Message"] = report.HasActiveContent
                        ? "The document has active content (scripts, actions, embedded files, multimedia or XFA)."
                        : "The document has no active content.";
                }
            }
            catch (Exception ex)
            {
                ViewData["Message"] = "An error occurred: " + ex.Message;
            }
            return Page();
        }

        // Sanitize: remove what the options say, or rasterize, and return the result.
        public IActionResult OnPostSanitize()
        {
            try
            {
                using (PdfSanitizeManager sanitizer = Load())
                {
                    // what is removed besides the default (scripts, actions, embedded files, multimedia, XFA, hidden layers, private data)
                    PdfSanitizeOptions options = PdfSanitizeOptions.Default;
                    if (ChkExternalLinks) options |= PdfSanitizeOptions.ExternalLinks;
                    if (ChkInvisibleText) options |= PdfSanitizeOptions.InvisibleText;
                    if (ChkMetadata) options |= PdfSanitizeOptions.Metadata;
                    if (ChkFlattenFormFields) options |= PdfSanitizeOptions.FlattenFormFields;
                    sanitizer.Options = options;

                    // or nothing of the original at all: an image of every page
                    sanitizer.Rasterize = ChkRasterize;
                    if (int.TryParse(TxtResolution, NumberStyles.Integer, CultureInfo.InvariantCulture, out int resolution))
                        sanitizer.Resolution = resolution;

                    sanitizer.Sanitize();
                    byte[] pdf = sanitizer.Save();

                    // return resulted pdf document
                    FileResult fileResult = new FileContentResult(pdf, "application/pdf");
                    fileResult.FileDownloadName = "Document.pdf";
                    return fileResult;
                }
            }
            catch (Exception ex)
            {
                ViewData["Message"] = "An error occurred: " + ex.Message;
                return Page();
            }
        }

        private PdfSanitizeManager Load()
        {
            byte[] source;
            if (FilePdf != null && FilePdf.Length > 0)
            {
                using (var uploaded = new MemoryStream())
                {
                    FilePdf.CopyTo(uploaded);
                    source = uploaded.ToArray();
                }
            }
            else
            {
                source = System.IO.File.ReadAllBytes(Path.Combine(Startup.ServerPath, "wwwroot", "files", "selectpdf.pdf"));
            }

            PdfSanitizeManager sanitizer = new PdfSanitizeManager();
            if (string.IsNullOrEmpty(TxtPassword))
                sanitizer.Load(source);
            else
                sanitizer.Load(source, TxtPassword);
            return sanitizer;
        }
    }
}