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

This sample shows how to use SelectPdf Library for .NET to validate a PDF document against a PDF/A, PDF/UA or PDF/X standard, and to fix it for that standard. Validate checks every rule of the standard and shows the rules the document fails; the file is not changed. Fix rewrites the document where a fix exists and returns it - what needs a person, such as the alternate text of a figure, is not fixed.

The sample uses the following (existing) test PDF, which claims PDF/UA-1, or a PDF you upload:
Test PDF document

PDF document (optional):

Standard:


Language (set by the fix when a PDF/UA document has none):


Password (for a protected PDF):


Sample code · C#
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
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 PdfValidationModel : PageModel
    {
        public void OnGet()
        {
            DdlStandard = "";
            TxtLanguage = "en-US";
        }

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

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

        // Empty: the standard the document claims.
        [BindProperty]
        public string DdlStandard { get; set; } = "";

        // The language set by the fix when a PDF/UA document has none.
        [BindProperty]
        public string TxtLanguage { get; set; }

        public List<SelectListItem> Standards { get; } = new List<SelectListItem>
        {
            new SelectListItem { Value = "", Text = "The standard the document claims" },
            new SelectListItem { Value = "PdfA1A", Text = "PDF/A-1a" },
            new SelectListItem { Value = "PdfA1B", Text = "PDF/A-1b" },
            new SelectListItem { Value = "PdfA2A", Text = "PDF/A-2a" },
            new SelectListItem { Value = "PdfA2B", Text = "PDF/A-2b" },
            new SelectListItem { Value = "PdfA2U", Text = "PDF/A-2u" },
            new SelectListItem { Value = "PdfA3A", Text = "PDF/A-3a" },
            new SelectListItem { Value = "PdfA3B", Text = "PDF/A-3b" },
            new SelectListItem { Value = "PdfA3U", Text = "PDF/A-3u" },
            new SelectListItem { Value = "PdfA4", Text = "PDF/A-4" },
            new SelectListItem { Value = "PdfA4E", Text = "PDF/A-4e" },
            new SelectListItem { Value = "PdfA4F", Text = "PDF/A-4f" },
            new SelectListItem { Value = "PdfUA1", Text = "PDF/UA-1" },
            new SelectListItem { Value = "PdfUA2", Text = "PDF/UA-2" },
            new SelectListItem { Value = "PdfX1a2001", Text = "PDF/X-1a:2001" },
            new SelectListItem { Value = "PdfX1a2003", Text = "PDF/X-1a:2003" },
            new SelectListItem { Value = "PdfX3_2002", Text = "PDF/X-3:2002" },
            new SelectListItem { Value = "PdfX3_2003", Text = "PDF/X-3:2003" },
            new SelectListItem { Value = "PdfX4", Text = "PDF/X-4" },
        };

        // One failed rule, shown on the page.
        public class FailedRule
        {
            public string Rule { get; set; }
            public string Description { get; set; }
            public int Count { get; set; }
            public string Example { get; set; }
        }

        // The validation report, shown on the page.
        public ValidationReport Report { get; private set; }
        public List<FailedRule> FailedRules { get; } = new List<FailedRule>();

        // Validate: check the document against the standard and show the report.
        public IActionResult OnPostValidate()
        {
            try
            {
                byte[] pdf = ReadPdf();
                PdfConformanceStandard? standard = ChooseStandard(pdf);
                if (standard == null)
                    return Page();

                // validate the document - it is only read, never changed
                Report = PdfValidator.Validate(pdf, Password, standard.Value);

                // one line per failed rule, with the first object that fails it
                foreach (var rule in Report.Failures.GroupBy(failure => failure.Rule))
                {
                    RuleFailure first = rule.First();
                    FailedRules.Add(new FailedRule
                    {
                        Rule = rule.Key.ToString(),
                        Description = first.Description,
                        Count = rule.Count(),
                        Example = first.Message + (first.Page != null ? " (page " + first.Page + ")" : "")
                    });
                }

                ViewData["Message"] = "Validated against " + standard.Value + ": "
                    + (Report.IsCompliant ? "compliant." : "not compliant.");
            }
            catch (Exception ex)
            {
                ViewData["Message"] = "An error occurred: " + ex.Message;
            }
            return Page();
        }

        // Fix: rewrite the document so that it conforms where a fix exists, and return it.
        public IActionResult OnPostFix()
        {
            try
            {
                byte[] pdf = ReadPdf();
                PdfConformanceStandard? standard = ChooseStandard(pdf);
                if (standard == null)
                    return Page();

                // the language to set when an accessible (PDF/UA) document has none
                var options = new PreflightOptions(
                    Language: string.IsNullOrWhiteSpace(TxtLanguage) ? null : TxtLanguage.Trim());

                // fix the document; the result is validated again
                PreflightResult result = PdfPreflight.Fix(pdf, Password, standard.Value, options);

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

        private string Password
        {
            get { return string.IsNullOrEmpty(TxtPassword) ? null : TxtPassword; }
        }

        // The standard chosen on the page, else the one the document claims.
        private PdfConformanceStandard? ChooseStandard(byte[] pdf)
        {
            if (!string.IsNullOrEmpty(DdlStandard))
                return SampleForm.ParseEnum(DdlStandard, PdfConformanceStandard.PdfA2B);

            PdfConformanceStandard? claimed = PdfValidator.ClaimedStandard(pdf, Password);
            if (claimed == null)
                ViewData["Message"] = "The document claims no standard. Choose one from the list.";
            return claimed;
        }

        private byte[] ReadPdf()
        {
            if (FilePdf != null && FilePdf.Length > 0)
            {
                using (var uploaded = new MemoryStream())
                {
                    FilePdf.CopyTo(uploaded);
                    return uploaded.ToArray();
                }
            }
            return System.IO.File.ReadAllBytes(Path.Combine(Startup.ServerPath, "wwwroot", "files", "w-9.pdf"));
        }
    }
}