Sanitize PDF documents in C#
PDF sanitization removes hidden, private, or non-visible data from a PDF. Use it before sharing documents outside your organization or before archiving documents that shouldn’t retain metadata or embedded objects.
Nutrient .NET SDK sanitizes selected categories, such as metadata, annotations, form fields, attachments, scripts, image metadata, tags, layers, and other hidden data.
This guide shows how to:
- Load a PDF
- Sanitize all supported hidden-data categories
- Save the sanitized PDF
- Read the JSON sanitization report
Prepare the project
Register the SDK license before running PDF operations. For setup details, refer to the getting started with .NET SDK guide.
using System;using System.IO;using GdPicture14;
void CheckStatus(GdPictureStatus status, string operation){ if (status != GdPictureStatus.OK) { throw new InvalidOperationException($"{operation} failed. Status: {status}"); }}
LicenseManager license = new LicenseManager();license.RegisterKEY(""); // Set your license keyLoad the PDF document
Create a GdPicturePDF instance and load the source file:
using GdPicturePDF pdf = new GdPicturePDF();
CheckStatus(pdf.LoadFromFile(@"input.pdf", false), "LoadFromFile");Sanitize the PDF
Run the sanitization pass and request a JSON report:
string reportJson = "";CheckStatus(pdf.Sanitize(SanitizeCategories.All, ref reportJson), "Sanitize");SanitizeCategories.All removes every supported category. To remove specific data types, combine flags. For example, use SanitizeCategories.Metadata | SanitizeCategories.Scripts to remove metadata and scripts only.
Save the sanitized output
Save with a full rewrite so removed objects don’t remain in the file body:
CheckStatus(pdf.SaveToFile(@"sanitized.pdf", true), "SaveToFile");File.WriteAllText(@"sanitize-report.json", reportJson);The second SaveToFile parameter enables a full rewrite of the file. This is important for sanitization because incremental saves preserve older revisions.
Inspect the report
Print the JSON report path for downstream logging or review:
Console.WriteLine("Sanitized PDF written to sanitized.pdf");Console.WriteLine("Sanitization report written to sanitize-report.json");The report contains per-category counts for removed objects and entries.
Error handling and validation
Check the GdPictureStatus returned by LoadFromFile, Sanitize, and SaveToFile. In production, verify that the sanitized output doesn’t expose sensitive data through text extraction, metadata inspection, attachments, annotations, or JavaScript actions.
Conclusion
This workflow removes supported hidden and private data from a PDF, saves the cleaned document, and writes a JSON report for audit or troubleshooting.