> For the complete documentation index, see [llms.txt](https://docs.apryse.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.apryse.com/core/get-started/samples/pdfsanitizetest.md).

# Sanitize PDFs

Sample code for using Apryse SDK to remove hidden, non-visual content within PDF documents. Sample code provided in Python, C++, C#, Java, Node.js (JavaScript), PHP, Ruby and VB.

This is sample code for using Apryse SDK to remove hidden, non-visual content within PDF documents. Using `pdftron.PDF.Sanitizer` ensures that if metadata, form data, bookmarks, hidden layers, markup annotations, JavaScript, or file attachments are present in a document, that content is permanently destroyed and is not simply disabled or obscured. Sample code is provided in Python, C++, C#, Java, Node.js (JavaScript), PHP, Ruby, and VB.

### **Implementation steps**

To sanitize files with Apryse Server SDK:

Step 1: Follow [get started with Server SDK in your preferred language or framework](/core/get-started/get-started.md). Step 2: Add the sample code provided in this guide.

Learn more about Apryse [Server SDK](/core/get-started/get-started.md).

{% tabs %}
{% tab title="C#" %}
{% code lineNumbers="true" %}

```csharp
//---------------------------------------------------------------------------------------
// Copyright (c) 2001-2026 by Apryse Software Inc. All Rights Reserved.
// Consult legal.txt regarding legal and license information.
//---------------------------------------------------------------------------------------

using System;
using System.IO;
using System.Collections;

using pdftron;
using pdftron.Common;
using pdftron.Filters;
using pdftron.SDF;
using pdftron.PDF;

using NUnit.Framework;

//------------------------------------------------------------------------------
// PDFNet's Sanitizer is a security-focused feature that permanently removes
// hidden, sensitive, or potentially unsafe content from a PDF document.
// While redaction targets visible page content such as text or graphics,
// sanitization focuses on non-visual elements and embedded structures.
//
// PDFNet Sanitizer ensures hidden or inactive content is destroyed,
// not merely obscured or disabled. This prevents leakage of sensitive
// data such as authoring details, editing history, private identifiers,
// and residual form entries, and neutralizes scripts or attachments.
//
// Sanitization is recommended prior to external sharing with clients,
// partners, or regulatory bodies. It helps align with privacy policies
// and compliance requirements by permanently removing non-visual data.
//------------------------------------------------------------------------------

namespace MiscellaneousSamples
{

	[TestFixture]
	public class PDFSanitizeTest
	{

		[Test]
		public static void Sample()
		{
			const string input_path =  "TestFiles/";


            // The following example illustrates how to retrieve the existing
            // sanitizable content categories within a document.
			try
			{
         	    using (PDFDoc doc = new PDFDoc(Utils.GetAssetTempFile(input_path + "numbered.pdf")))
    		    {
		            doc.InitSecurityHandler();

			        SanitizeOptions opts = Sanitizer.GetSanitizableContent(doc);
			        if (opts.GetMetadata())
    			    {
	    			    Console.WriteLine("Document has metadata.");
	    		    }
			        if (opts.GetMarkups())
			        {
				        Console.WriteLine("Document has markups.");
			        }
			        if (opts.GetHiddenLayers())
			        {
				        Console.WriteLine("Document has hidden layers.");
			        }
                    Console.WriteLine("Done...");
			    }
			}
			catch (PDFNetException e)
			{
				Console.WriteLine(e.Message);
				Assert.True(false);
			}


    	    // The following example illustrates how to sanitize a document with default options,
    	    // which will remove all sanitizable content present within a document.
    		try
    		{
         	    using (PDFDoc doc = new PDFDoc(Utils.GetAssetTempFile(input_path + "financial.pdf")))
        	    {
    		        doc.InitSecurityHandler();

			        Sanitizer.SanitizeDocument(doc);
    				doc.Save(Utils.CreateExternalFile("financial_sanitized.pdf"), SDFDoc.SaveOptions.e_linearized);
                    Console.WriteLine("Done...");
    			}
    		}
    		catch (PDFNetException e)
    		{
    			Console.WriteLine(e.Message);
    			Assert.True(false);
    		}


	        // The following example illustrates how to sanitize a document with custom set options,
	        // which will only remove the content categories specified by the options object.
    		try
    		{
         	    using (PDFDoc doc = new PDFDoc(Utils.GetAssetTempFile(input_path + "form1.pdf")))
        	    {
    		        doc.InitSecurityHandler();

    		        SanitizeOptions opts = new SanitizeOptions();
		            opts.SetMetadata(true);
        		    opts.SetFormData(true);
        		    opts.SetBookmarks(true);

			        Sanitizer.SanitizeDocument(doc, opts);
    				doc.Save(Utils.CreateExternalFile("form1_sanitized.pdf"), SDFDoc.SaveOptions.e_linearized);
                    Console.WriteLine("Done...");
    			}
    		}
    		catch (PDFNetException e)
    		{
    			Console.WriteLine(e.Message);
    			Assert.True(false);
    		}

		}
	}
}

```

{% endcode %}
{% endtab %}

{% tab title="Go" %}
{% code lineNumbers="true" %}

```go
//---------------------------------------------------------------------------------------
// Copyright (c) 2001-2026 by Apryse Software Inc. All Rights Reserved.
// Consult legal.txt regarding legal and license information.
//---------------------------------------------------------------------------------------

package main
import (
    "fmt"
    "testing"
    "flag"
    . "github.com/pdftron/pdftron-go/v2"
)

var licenseKey string
var modulePath string

func init() {
    flag.StringVar(&licenseKey, "license", "", "License key for Apryse SDK")
    flag.StringVar(&modulePath, "modulePath", "", "Module path for Apryse SDK")
}

//------------------------------------------------------------------------------
// PDFNet's Sanitizer is a security-focused feature that permanently removes
// hidden, sensitive, or potentially unsafe content from a PDF document.
// While redaction targets visible page content such as text or graphics,
// sanitization focuses on non-visual elements and embedded structures.
//
// PDFNet Sanitizer ensures hidden or inactive content is destroyed,
// not merely obscured or disabled. This prevents leakage of sensitive
// data such as authoring details, editing history, private identifiers,
// and residual form entries, and neutralizes scripts or attachments.
//
// Sanitization is recommended prior to external sharing with clients,
// partners, or regulatory bodies. It helps align with privacy policies
// and compliance requirements by permanently removing non-visual data.
//------------------------------------------------------------------------------

func TestPDFSanitize(t *testing.T){

    // Relative path to the folder containing the test files.
    inputPath := "../TestFiles/"
    outputPath := "../TestFiles/Output/"

    PDFNetInitialize(licenseKey)

	// The following example illustrates how to retrieve the existing
	// sanitizable content categories within a document.
	{
		doc := NewPDFDoc(inputPath + "numbered.pdf")
		doc.InitSecurityHandler()
		opts := SanitizerGetSanitizableContent(doc)
		if opts.GetMetadata() {
			fmt.Println("Document has metadata.")
		}
		if opts.GetMarkups() {
			fmt.Println("Document has markups.")
		}
		if opts.GetHiddenLayers() {
			fmt.Println("Document has hidden layers.")
		}
		fmt.Println("Done...")
	}

	// The following example illustrates how to sanitize a document with default options,
	// which will remove all sanitizable content present within a document.
	{
		doc := NewPDFDoc(inputPath + "financial.pdf")
		doc.InitSecurityHandler()
		SanitizerSanitizeDocument(doc, NewSanitizeOptions())
		doc.Save(outputPath+"financial_sanitized.pdf", uint(SDFDocE_linearized))
		fmt.Println("Done...")
	}

	// The following example illustrates how to sanitize a document with custom set options,
	// which will only remove the content categories specified by the options object.
	{
		options := NewSanitizeOptions()
		options.SetMetadata(true)
		options.SetFormData(true)
		options.SetBookmarks(true)

		doc := NewPDFDoc(inputPath + "form1.pdf")
		doc.InitSecurityHandler()
		SanitizerSanitizeDocument(doc, options)
		doc.Save(outputPath+"form1_sanitized.pdf", uint(SDFDocE_linearized))
		fmt.Println("Done...")
	}

    PDFNetTerminate()
}


```

{% endcode %}
{% endtab %}

{% tab title="Java" %}
{% code lineNumbers="true" %}

```java
//---------------------------------------------------------------------------------------
// Copyright (c) 2001-2026 by Apryse Software Inc. All Rights Reserved.
// Consult legal.txt regarding legal and license information.
//---------------------------------------------------------------------------------------

import java.lang.*;
import java.awt.*;

import com.pdftron.pdf.*;
import com.pdftron.sdf.SDFDoc;

//------------------------------------------------------------------------------
// PDFNet's Sanitizer is a security-focused feature that permanently removes
// hidden, sensitive, or potentially unsafe content from a PDF document.
// While redaction targets visible page content such as text or graphics,
// sanitization focuses on non-visual elements and embedded structures.
//
// PDFNet Sanitizer ensures hidden or inactive content is destroyed,
// not merely obscured or disabled. This prevents leakage of sensitive
// data such as authoring details, editing history, private identifiers,
// and residual form entries, and neutralizes scripts or attachments.
//
// Sanitization is recommended prior to external sharing with clients,
// partners, or regulatory bodies. It helps align with privacy policies
// and compliance requirements by permanently removing non-visual data.
//------------------------------------------------------------------------------
public class PDFSanitizeTest {

    public static void main(String[] args) {
        // Relative paths to folders containing test files.
        String input_path = "../../TestFiles/";
        String output_path = "../../TestFiles/Output/";

        PDFNet.initialize(PDFTronLicense.Key());


        // The following example illustrates how to retrieve the existing
        // sanitizable content categories within a document.
        try (PDFDoc doc = new PDFDoc(input_path + "numbered.pdf")) {
            doc.initSecurityHandler();

            SanitizeOptions opts = Sanitizer.getSanitizableContent(doc);
            if (opts.getMetadata())
            {
                System.out.println("Document has metadata.");
            }
            if (opts.getMarkups())
            {
                System.out.println("Document has markups.");
            }
            if (opts.getHiddenLayers())
            {
                System.out.println("Document has hidden layers.");
            }
            System.out.println("Done...");
        } catch (Exception e) {
            e.printStackTrace();
        }


	    // The following example illustrates how to sanitize a document with default options,
	    // which will remove all sanitizable content present within a document.
        try (PDFDoc doc = new PDFDoc(input_path + "financial.pdf")) {
            doc.initSecurityHandler();

            Sanitizer.sanitizeDocument(doc);
            doc.save(output_path + "financial_sanitized.pdf", SDFDoc.SaveMode.LINEARIZED, null);
            System.out.println("Done...");
        } catch (Exception e) {
            e.printStackTrace();
        }


	    // The following example illustrates how to sanitize a document with custom set options,
	    // which will only remove the content categories specified by the options object.
        try (PDFDoc doc = new PDFDoc(input_path + "form1.pdf")) {
            doc.initSecurityHandler();

            SanitizeOptions options = new SanitizeOptions();
            options.setMetadata(true);
            options.setFormData(true);
            options.setBookmarks(true);

            Sanitizer.sanitizeDocument(doc, options);
            doc.save(output_path + "form1_sanitized.pdf", SDFDoc.SaveMode.LINEARIZED, null);
            System.out.println("Done...");
        } catch (Exception e) {
            e.printStackTrace();
        }

        PDFNet.terminate();
    }
}
```

{% endcode %}
{% endtab %}

{% tab title="C++" %}
{% code lineNumbers="true" %}

```cpp
//---------------------------------------------------------------------------------------
// Copyright (c) 2001-2026 by Apryse Software Inc. All Rights Reserved.
// Consult legal.txt regarding legal and license information.
//---------------------------------------------------------------------------------------

#include <PDF/PDFNet.h>
#include <PDF/PDFDoc.h>
#include <PDF/Sanitizer.h>
#include <PDF/SanitizeOptions.h>
#include <iostream>

#include "../../LicenseKey/CPP/LicenseKey.h"


using namespace std;

using namespace pdftron;
using namespace Common;
using namespace SDF;
using namespace PDF;


//------------------------------------------------------------------------------
// PDFNet's Sanitizer is a security-focused feature that permanently removes
// hidden, sensitive, or potentially unsafe content from a PDF document.
// While redaction targets visible page content such as text or graphics,
// sanitization focuses on non-visual elements and embedded structures.
//
// PDFNet Sanitizer ensures hidden or inactive content is destroyed,
// not merely obscured or disabled. This prevents leakage of sensitive
// data such as authoring details, editing history, private identifiers,
// and residual form entries, and neutralizes scripts or attachments.
//
// Sanitization is recommended prior to external sharing with clients,
// partners, or regulatory bodies. It helps align with privacy policies
// and compliance requirements by permanently removing non-visual data.
//------------------------------------------------------------------------------

int main(int argc, char *argv[])
{
	int ret = 0;
	PDFNet::Initialize(LicenseKey);

	// Relative paths to folders containing test files.
	string input_path =  "../../TestFiles/";
	string output_path = "../../TestFiles/Output/";

	// The following example illustrates how to retrieve the existing
	// sanitizable content categories within a document.
	try
	{
		PDFDoc doc(input_path + "numbered.pdf");
		doc.InitSecurityHandler();

		SanitizeOptions opts = Sanitizer::GetSanitizableContent(doc);
		if (opts.GetMetadata())
		{
			cout << "Document has metadata." << endl;
		}
		if (opts.GetMarkups())
		{
			cout << "Document has markups." << endl;
		}
		if (opts.GetHiddenLayers())
		{
			cout << "Document has hidden layers." << endl;
		}
		cout << "Done..." << endl;
	}
	catch(Common::Exception& e)
	{
		cout << e << endl;
		ret = 1;
	}
	catch(...)
	{
		cout << "Unknown Exception" << endl;
		ret = 1;
	}


	// The following example illustrates how to sanitize a document with default options,
	// which will remove all sanitizable content present within a document.
	try
	{
		PDFDoc doc(input_path + "financial.pdf");
		doc.InitSecurityHandler();

		Sanitizer::SanitizeDocument(doc, 0);
		doc.Save(output_path + "financial_sanitized.pdf", SDFDoc::e_linearized, 0);
		cout << "Done..." << endl;
	}
	catch(Common::Exception& e)
	{
		cout << e << endl;
		ret = 1;
	}
	catch(...)
	{
		cout << "Unknown Exception" << endl;
		ret = 1;
	}


	// The following example illustrates how to sanitize a document with custom set options,
	// which will only remove the content categories specified by the options object.
	try
	{
		SanitizeOptions options;
		options.SetMetadata(true);
		options.SetFormData(true);
		options.SetBookmarks(true);

		PDFDoc doc(input_path + "form1.pdf");
		doc.InitSecurityHandler();

		Sanitizer::SanitizeDocument(doc, &options);
		doc.Save(output_path  + "form1_sanitized.pdf", SDFDoc::e_linearized, 0);
		cout << "Done..." << endl;
	}
	catch(Common::Exception& e)
	{
		cout << e << endl;
		ret = 1;
	}
	catch(...)
	{
		cout << "Unknown Exception" << endl;
		ret = 1;
	}

	PDFNet::Terminate();
	return ret;
}

```

{% endcode %}
{% endtab %}

{% tab title="JavaScript" %}
{% code lineNumbers="true" %}

```js
//---------------------------------------------------------------------------------------
// Copyright (c) 2001-2026 by Apryse Software Inc. All Rights Reserved.
// Consult legal.txt regarding legal and license information.
//---------------------------------------------------------------------------------------

//------------------------------------------------------------------------------
// PDFNet's Sanitizer is a security-focused feature that permanently removes
// hidden, sensitive, or potentially unsafe content from a PDF document.
// While redaction targets visible page content such as text or graphics,
// sanitization focuses on non-visual elements and embedded structures.
//
// PDFNet Sanitizer ensures hidden or inactive content is destroyed,
// not merely obscured or disabled. This prevents leakage of sensitive
// data such as authoring details, editing history, private identifiers,
// and residual form entries, and neutralizes scripts or attachments.
//
// Sanitization is recommended prior to external sharing with clients,
// partners, or regulatory bodies. It helps align with privacy policies
// and compliance requirements by permanently removing non-visual data.
//------------------------------------------------------------------------------

const { PDFNet } = require('../../lib/pdfnet.js');
const PDFTronLicense = require('../../LicenseKey/NODEJS/LicenseKey');

((exports) => {

    exports.runPDFSanitizeTest = () => {

        const main = async() => {
            // Relative path to the folder containing test files.
            const inputPath = '../TestFiles/';
            const outputPath = '../TestFiles/Output/';

            // The following example illustrates how to retrieve the existing
            // sanitizable content categories within a document.
            try {
                const doc = await PDFNet.PDFDoc.createFromFilePath(inputPath + 'numbered.pdf');
                if (await doc.initSecurityHandler()) {
                    const opts = await PDFNet.Sanitizer.getSanitizableContent(doc);
                    if (opts.getMetadata()) {
                        console.log('Document has metadata.');
                    }
                    if (opts.getMarkups()) {
                        console.log('Document has markups.');
                    }
                    if (opts.getHiddenLayers()) {
                        console.log('Document has hidden layers.');
                    }
                }
                console.log('Done...');
            } catch (err) {
                console.log(err.stack);
            }

            // The following example illustrates how to sanitize a document with default options,
            // which will remove all sanitizable content present within a document.
            try {
                const doc = await PDFNet.PDFDoc.createFromFilePath(inputPath + 'financial.pdf');
                if (await doc.initSecurityHandler()) {
                    await PDFNet.Sanitizer.sanitizeDocument(doc);
                    await doc.save(outputPath + 'financial_sanitized.pdf', PDFNet.SDFDoc.SaveOptions.e_linearized);
                }
                console.log('Done...');
            } catch (err) {
                console.log(err.stack);
            }

            // The following example illustrates how to sanitize a document with custom set options,
            // which will only remove the content categories specified by the options object.
            try {
                const options = new PDFNet.Sanitizer.SanitizeOptions();
                options.setMetadata(true);
                options.setFormData(true);
                options.setBookmarks(true);

                const doc = await PDFNet.PDFDoc.createFromFilePath(inputPath + 'form1.pdf');
                if (await doc.initSecurityHandler()) {
                    await PDFNet.Sanitizer.sanitizeDocument(doc, options);
                    await doc.save(outputPath + 'form1_sanitized.pdf', PDFNet.SDFDoc.SaveOptions.e_linearized);
                }
                console.log('Done...');
            } catch (err) {
                console.log(err.stack);
            }
        };
        PDFNet.runWithCleanup(main, PDFTronLicense.Key).catch(function(error){console.log('Error: ' + JSON.stringify(error));}).then(function(){return PDFNet.shutdown();});
    };
    exports.runPDFSanitizeTest();
})(exports);
// eslint-disable-next-line spaced-comment
//# sourceURL=PDFSanitizeTest.js
```

{% endcode %}
{% endtab %}

{% tab title="Python" %}
{% code lineNumbers="true" %}

```python
#---------------------------------------------------------------------------------------
# Copyright (c) 2001-2026 by Apryse Software Inc. All Rights Reserved.
# Consult legal.txt regarding legal and license information.
#---------------------------------------------------------------------------------------

import site
site.addsitedir("../../../PDFNetC/Lib")
import sys
from PDFNetPython import *

sys.path.append("../../LicenseKey/PYTHON")
from LicenseKey import *

#------------------------------------------------------------------------------
# PDFNet's Sanitizer is a security-focused feature that permanently removes
# hidden, sensitive, or potentially unsafe content from a PDF document.
# While redaction targets visible page content such as text or graphics,
# sanitization focuses on non-visual elements and embedded structures.
#
# PDFNet Sanitizer ensures hidden or inactive content is destroyed,
# not merely obscured or disabled. This prevents leakage of sensitive
# data such as authoring details, editing history, private identifiers,
# and residual form entries, and neutralizes scripts or attachments.
#
# Sanitization is recommended prior to external sharing with clients,
# partners, or regulatory bodies. It helps align with privacy policies
# and compliance requirements by permanently removing non-visual data.
#------------------------------------------------------------------------------

def main():
    # Relative paths to folders containing test files.
    input_path = "../../TestFiles/"
    output_path = "../../TestFiles/Output/"

    PDFNet.Initialize(LicenseKey)

    # The following example illustrates how to retrieve the existing
    # sanitizable content categories within a document.
    try:
        doc = PDFDoc(input_path + "numbered.pdf")
        doc.InitSecurityHandler()

        opts = Sanitizer.GetSanitizableContent(doc)
        if opts.GetMetadata():
            print("Document has metadata.")
        if opts.GetMarkups():
            print("Document has markups.")
        if opts.GetHiddenLayers():
            print("Document has hidden layers.")
        print("Done...")
    except Exception as e:
        print(e)

    # The following example illustrates how to sanitize a document with default options,
    # which will remove all sanitizable content present within a document.
    try:
        doc = PDFDoc(input_path + "financial.pdf")
        doc.InitSecurityHandler()

        Sanitizer.SanitizeDocument(doc, None)
        doc.Save(output_path + "financial_sanitized.pdf", SDFDoc.e_linearized)
        print("Done...")
    except Exception as e:
        print(e)

    # The following example illustrates how to sanitize a document with custom set options,
    # which will only remove the content categories specified by the options object.
    try:
        options = SanitizeOptions()
        options.SetMetadata(True)
        options.SetFormData(True)
        options.SetBookmarks(True)

        doc = PDFDoc(input_path + "form1.pdf")
        doc.InitSecurityHandler()

        Sanitizer.SanitizeDocument(doc, options)
        doc.Save(output_path + "form1_sanitized.pdf", SDFDoc.e_linearized)
        print("Done...")
    except Exception as e:
        print(e)

    PDFNet.Terminate()

if __name__ == '__main__':
    main()


```

{% endcode %}
{% endtab %}

{% tab title="PHP" %}
{% code lineNumbers="true" %}

```php
<?php
//---------------------------------------------------------------------------------------
// Copyright (c) 2001-2026 by Apryse Software Inc. All Rights Reserved.
// Consult legal.txt regarding legal and license information.
//---------------------------------------------------------------------------------------
if(file_exists("../../../PDFNetC/Lib/PDFNetPHP.php"))
include("../../../PDFNetC/Lib/PDFNetPHP.php");
include("../../LicenseKey/PHP/LicenseKey.php");

//------------------------------------------------------------------------------
// PDFNet's Sanitizer is a security-focused feature that permanently removes
// hidden, sensitive, or potentially unsafe content from a PDF document.
// While redaction targets visible page content such as text or graphics,
// sanitization focuses on non-visual elements and embedded structures.
//
// PDFNet Sanitizer ensures hidden or inactive content is destroyed,
// not merely obscured or disabled. This prevents leakage of sensitive
// data such as authoring details, editing history, private identifiers,
// and residual form entries, and neutralizes scripts or attachments.
//
// Sanitization is recommended prior to external sharing with clients,
// partners, or regulatory bodies. It helps align with privacy policies
// and compliance requirements by permanently removing non-visual data.
//------------------------------------------------------------------------------

	global $LicenseKey;
	PDFNet::Initialize($LicenseKey);
	PDFNet::GetSystemFontList();    // Wait for fonts to be loaded if they haven't already. This is done because PHP can run into errors when shutting down if font loading is still in progress.

	// Relative paths to folders containing test files.
	$input_path = getcwd()."/../../TestFiles/";
	$output_path = $input_path."Output/";

	// The following example illustrates how to retrieve the existing
	// sanitizable content categories within a document.
	try
	{
		$doc = new PDFDoc($input_path."numbered.pdf");
		$doc->InitSecurityHandler();

		$opts = Sanitizer::GetSanitizableContent($doc);
		if ($opts->GetMetadata())
		{
			echo(nl2br("Document has metadata.\n"));
		}
		if ($opts->GetMarkups())
		{
			echo(nl2br("Document has markups.\n"));
		}
		if ($opts->GetHiddenLayers())
		{
			echo(nl2br("Document has hidden layers.\n"));
		}
		echo(nl2br("Done...\n"));
	}
	catch(Exception $e)
	{
		echo(nl2br($e->getMessage()."\n"));
	}

	// The following example illustrates how to sanitize a document with default options,
	// which will remove all sanitizable content present within a document.
	try
	{
		$doc = new PDFDoc($input_path."financial.pdf");
		$doc->InitSecurityHandler();

		Sanitizer::SanitizeDocument($doc, null);
		$doc->Save($output_path."financial_sanitized.pdf", SDFDoc::e_linearized);
		echo(nl2br("Done...\n"));
	}
	catch(Exception $e)
	{
		echo(nl2br($e->getMessage()."\n"));
	}

	// The following example illustrates how to sanitize a document with custom set options,
	// which will only remove the content categories specified by the options object.
	try
	{
		$options = new SanitizeOptions();
		$options->SetMetadata(true);
		$options->SetFormData(true);
		$options->SetBookmarks(true);

		$doc = new PDFDoc($input_path."form1.pdf");
		$doc->InitSecurityHandler();

		Sanitizer::SanitizeDocument($doc, $options);
		$doc->Save($output_path."form1_sanitized.pdf", SDFDoc::e_linearized);
		echo(nl2br("Done...\n"));
	}
	catch(Exception $e)
	{
		echo(nl2br($e->getMessage()."\n"));
	}

	PDFNet::Terminate();
?>


```

{% endcode %}
{% endtab %}

{% tab title="Ruby" %}
{% code lineNumbers="true" %}

```ruby
#---------------------------------------------------------------------------------------
# Copyright (c) 2001-2026 by Apryse Software Inc. All Rights Reserved.
# Consult legal.txt regarding legal and license information.
#---------------------------------------------------------------------------------------

require '../../../PDFNetC/Lib/PDFNetRuby'
include PDFNetRuby
require '../../LicenseKey/RUBY/LicenseKey'

$stdout.sync = true

#------------------------------------------------------------------------------
# PDFNet's Sanitizer is a security-focused feature that permanently removes
# hidden, sensitive, or potentially unsafe content from a PDF document.
# While redaction targets visible page content such as text or graphics,
# sanitization focuses on non-visual elements and embedded structures.
#
# PDFNet Sanitizer ensures hidden or inactive content is destroyed,
# not merely obscured or disabled. This prevents leakage of sensitive
# data such as authoring details, editing history, private identifiers,
# and residual form entries, and neutralizes scripts or attachments.
#
# Sanitization is recommended prior to external sharing with clients,
# partners, or regulatory bodies. It helps align with privacy policies
# and compliance requirements by permanently removing non-visual data.
#------------------------------------------------------------------------------

	# Relative paths to folders containing test files.
	input_path = "../../TestFiles/"
	output_path = "../../TestFiles/Output/"

	PDFNet.Initialize(PDFTronLicense.Key)

	# The following example illustrates how to retrieve the existing
	# sanitizable content categories within a document.
	begin
		doc = PDFDoc.new(input_path + "numbered.pdf")
		doc.InitSecurityHandler

		opts = Sanitizer.GetSanitizableContent(doc)
		if opts.GetMetadata
			puts "Document has metadata."
		end
		if opts.GetMarkups
			puts "Document has markups."
		end
		if opts.GetHiddenLayers
			puts "Document has hidden layers."
		end
		puts "Done..."
	rescue Exception => e
		puts e
	end

	# The following example illustrates how to sanitize a document with default options,
	# which will remove all sanitizable content present within a document.
	begin
		doc = PDFDoc.new(input_path + "financial.pdf")
		doc.InitSecurityHandler

		Sanitizer.SanitizeDocument(doc, nil)
		doc.Save(output_path + "financial_sanitized.pdf", SDFDoc::E_linearized)
		puts "Done..."
	rescue Exception => e
		puts e
	end

	# The following example illustrates how to sanitize a document with custom set options,
	# which will only remove the content categories specified by the options object.
	begin
		options = SanitizeOptions.new
		options.SetMetadata(true)
		options.SetFormData(true)
		options.SetBookmarks(true)

		doc = PDFDoc.new(input_path + "form1.pdf")
		doc.InitSecurityHandler

		Sanitizer.SanitizeDocument(doc, options)
		doc.Save(output_path + "form1_sanitized.pdf", SDFDoc::E_linearized)
		puts "Done..."
	rescue Exception => e
		puts e
	end

	PDFNet.Terminate


```

{% endcode %}
{% endtab %}

{% tab title="VB" %}
{% code lineNumbers="true" %}

```vb
'
' Copyright (c) 2001-2026 by Apryse Software Inc. All Rights Reserved.
'

Imports System
Imports System.Collections

Imports pdftron
Imports pdftron.Common
Imports pdftron.Filters
Imports pdftron.SDF
Imports pdftron.PDF

Module PDFSanitizeTestVB
    Dim pdfNetLoader As PDFNetLoader
    Sub New()
        pdfNetLoader = pdftron.PDFNetLoader.Instance()
    End Sub

    ' PDFNet's Sanitizer is a security-focused feature that permanently removes
    ' hidden, sensitive, or potentially unsafe content from a PDF document.
    ' While redaction targets visible page content such as text or graphics,
    ' sanitization focuses on non-visual elements and embedded structures.
    '
    ' PDFNet Sanitizer ensures hidden or inactive content is destroyed,
    ' not merely obscured or disabled. This prevents leakage of sensitive
    ' data such as authoring details, editing history, private identifiers,
    ' and residual form entries, and neutralizes scripts or attachments.
    '
    ' Sanitization is recommended prior to external sharing with clients,
    ' partners, or regulatory bodies. It helps align with privacy policies
    ' and compliance requirements by permanently removing non-visual data.
    Sub Main()
        PDFNet.Initialize(PDFTronLicense.Key)

        Dim input_path As String = "../../../../TestFiles/"
        Dim output_path As String = "../../../../TestFiles/Output/"

        ' The following example illustrates how to retrieve the existing
        ' sanitizable content categories within a document.
        Try
            Using doc As PDFDoc = New PDFDoc(input_path + "numbered.pdf")
                doc.InitSecurityHandler()
                Dim opts As SanitizeOptions = Sanitizer.GetSanitizableContent(doc)
                If opts.GetMetadata() Then
                    Console.WriteLine("Document has metadata.")
                End If
                If opts.GetMarkups() Then
                    Console.WriteLine("Document has markups.")
                End If
                If opts.GetHiddenLayers() Then
                    Console.WriteLine("Document has hidden layers.")
                End If
            End Using
            Console.WriteLine("Done...")
        Catch ex As PDFNetException
            Console.WriteLine(ex.Message)
        Catch ex As Exception
            MsgBox(ex.Message)
        End Try

        ' The following example illustrates how to sanitize a document with default options,
        ' which will remove all sanitizable content present within a document.
        Try
            Using doc As PDFDoc = New PDFDoc(input_path + "financial.pdf")
                doc.InitSecurityHandler()
                Sanitizer.SanitizeDocument(doc)
                doc.Save(output_path + "financial_sanitized.pdf", SDFDoc.SaveOptions.e_linearized)
            End Using
            Console.WriteLine("Done...")
        Catch ex As PDFNetException
            Console.WriteLine(ex.Message)
        Catch ex As Exception
            MsgBox(ex.Message)
        End Try

        ' The following example illustrates how to sanitize a document with custom set options,
        ' which will only remove the content categories specified by the options object.
        Try
            Dim options As SanitizeOptions = New SanitizeOptions()
            options.SetMetadata(True)
            options.SetFormData(True)
            options.SetBookmarks(True)

            Using doc As PDFDoc = New PDFDoc(input_path + "form1.pdf")
                doc.InitSecurityHandler()
                Sanitizer.SanitizeDocument(doc, options)
                doc.Save(output_path + "form1_sanitized.pdf", SDFDoc.SaveOptions.e_linearized)
            End Using
            Console.WriteLine("Done...")
        Catch ex As PDFNetException
            Console.WriteLine(ex.Message)
        Catch ex As Exception
            MsgBox(ex.Message)
        End Try

        PDFNet.Terminate()
    End Sub

End Module


```

{% endcode %}
{% endtab %}

{% tab title="Obj-C" %}
{% code lineNumbers="true" %}

```objc
//---------------------------------------------------------------------------------------
// Copyright (c) 2001-2026 by Apryse Software Inc. All Rights Reserved.
// Consult legal.txt regarding legal and license information.
//---------------------------------------------------------------------------------------

#import <OBJC/PDFNetOBJC.h>
#import <Foundation/Foundation.h>

//------------------------------------------------------------------------------
// PDFNet's Sanitizer is a security-focused feature that permanently removes
// hidden, sensitive, or potentially unsafe content from a PDF document.
// While redaction targets visible page content such as text or graphics,
// sanitization focuses on non-visual elements and embedded structures.
//
// PDFNet Sanitizer ensures hidden or inactive content is destroyed,
// not merely obscured or disabled. This prevents leakage of sensitive
// data such as authoring details, editing history, private identifiers,
// and residual form entries, and neutralizes scripts or attachments.
//
// Sanitization is recommended prior to external sharing with clients,
// partners, or regulatory bodies. It helps align with privacy policies
// and compliance requirements by permanently removing non-visual data.
//------------------------------------------------------------------------------

int main(int argc, char *argv[])
{
    @autoreleasepool {

        int ret = 0;

        [PTPDFNet Initialize: 0];


        // The following example illustrates how to retrieve the existing
        // sanitizable content categories within a document.
        @try
        {
            PTPDFDoc *doc = [[PTPDFDoc alloc] initWithFilepath: @"../../TestFiles/numbered.pdf"];
            [doc InitSecurityHandler];
            PTSanitizeOptions *opts = [PTSanitizer GetSanitizableContent: doc];

            if ([opts GetMetadata]) {
                NSLog(@"Document has metadata.");
            }
            if ([opts GetMarkups]) {
                NSLog(@"Document has markups.");
            }
            if ([opts GetHiddenLayers]) {
                NSLog(@"Document has hidden layers.");
            }
            NSLog(@"Done...");
        }
        @catch(NSException *e)
        {
            NSLog(@"%@", e.reason);
            ret = 1;
        }


	    // The following example illustrates how to sanitize a document with default options,
	    // which will remove all sanitizable content present within a document.
        @try
        {
            PTPDFDoc *doc = [[PTPDFDoc alloc] initWithFilepath: @"../../TestFiles/financial.pdf"];
            [doc InitSecurityHandler];

            [PTSanitizer SanitizeDocument: doc options: nil];
            [doc SaveToFile: @"../../TestFiles/Output/financial_sanitized.pdf" flags: e_ptlinearized ];
            NSLog(@"Done...");
        }
        @catch(NSException *e)
        {
            NSLog(@"%@", e.reason);
            ret = 1;
        }


	    // The following example illustrates how to sanitize a document with custom set options,
	    // which will only remove the content categories specified by the options object.
        @try
        {
            PTSanitizeOptions *opts = [[PTSanitizeOptions alloc] init];
            [opts SetMetadata: YES];
            [opts SetFormData: YES];
            [opts SetBookmarks: YES];

            PTPDFDoc *doc = [[PTPDFDoc alloc] initWithFilepath: @"../../TestFiles/form1.pdf"];
            [doc InitSecurityHandler];

            [PTSanitizer SanitizeDocument: doc options: opts];
            [doc SaveToFile: @"../../TestFiles/Output/form1_sanitized.pdf" flags: e_ptlinearized ];
            NSLog(@"Done...");
        }
        @catch(NSException *e)
        {
            NSLog(@"%@", e.reason);
            ret = 1;
        }

        [PTPDFNet Terminate: 0];
        return ret;
    }
}


```

{% endcode %}
{% endtab %}
{% endtabs %}


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://docs.apryse.com/core/get-started/samples/pdfsanitizetest.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
