Skip to main content

Code samples

Here you'll find some samples to get you started with the Pdf Tools SDK.

Sign documents

Add a document time-stamp to a PDF

1static void AddTimestamp(Uri timeStampUrl, string inPath, string outPath)
2{
3    // Create a session to the built-in cryptographic provider
4    using var session = new BuiltIn.Provider();
5    session.TimestampUrl = timeStampUrl;
6
7    // Create time-stamp configuration
8    var timestamp = session.CreateTimestamp();
9
10    // Open input document
11    using var inStr = File.OpenRead(inPath);
12    using var inDoc = Document.Open(inStr);
13
14    // Create stream for output file
15    using var outStr = File.Create(outPath);
16
17    // Add the document time-stamp
18    using var outDoc = new Signer().AddTimestamp(inDoc, timestamp, outStr);
19}
1private static void AddTimestamp(URI timeStampUrl, String inPath, String outPath) throws Exception
2{
3    // Create a session to the built-in cryptographic provider
4    try (Provider session = new Provider())
5    {
6        // Configure URL of the trusted time-stamp authority (TSA)
7        session.setTimestampUrl(timeStampUrl);
8
9        // Create time-stamp configuration
10        TimestampConfiguration timestamp = session.createTimestamp();
11
12        try (
13            // Open input document
14            FileStream inStr = new FileStream(inPath, FileStream.Mode.READ_ONLY);
15            Document inDoc = Document.open(inStr);
16
17            // Create output stream
18            FileStream outStr = new FileStream(outPath, FileStream.Mode.READ_WRITE_NEW);
19
20            // Add the document time-stamp
21            Document outDoc = new Signer().addTimestamp(inDoc, timestamp, outStr))
22        {
23        }
24    }
25}

Certify a PDF

1static void Certify(string certificateFile, string password, string inPath, string outPath)
2{
3    // Create a session to the built-in cryptographic provider
4    using var session = new BuiltIn.Provider();
5
6    // Create signature configuration from PFX (or P12) file
7    using var pfxStr = File.OpenRead(certificateFile);
8    var signature = session.CreateSignatureFromCertificate(pfxStr, password);
9
10    // Embed validation information to enable the long term validation (LTV) of the signature (default)
11    signature.ValidationInformation = PdfTools.Crypto.ValidationInformation.EmbedInDocument;
12
13    // Open input document
14    using var inStr = File.OpenRead(inPath);
15    using var inDoc = Document.Open(inStr);
16
17    // Create stream for output file
18    using var outStr = File.Create(outPath);
19
20    // Add a document certification (MDP) signature
21    // Optionally, the access permissions can be set.
22    using var outDoc = new Signer().Certify(inDoc, signature, outStr);
23}
1private static void Certify(String certificateFile, String password, String inPath, String outPath) throws Exception
2{
3    try (
4        // Create a session to the built-in cryptographic provider
5        Provider session = new Provider();
6
7        // Open certificate file
8        FileStream pfxStr = new FileStream(certificateFile, FileStream.Mode.READ_ONLY))
9    {
10        // Create signature configuration from PFX (or P12) file
11        SignatureConfiguration signature = session.createSignatureFromCertificate(pfxStr, password);
12
13        // Embed validation information to enable the long term validation (LTV) of the signature (default)
14        signature.setValidationInformation(com.pdftools.crypto.ValidationInformation.EMBED_IN_DOCUMENT);
15
16        try (
17            // Open input document
18            FileStream inStr = new FileStream(inPath, FileStream.Mode.READ_ONLY);
19            Document inDoc = Document.open(inStr);
20
21            // Create output stream
22            FileStream outStr = new FileStream(outPath, FileStream.Mode.READ_WRITE_NEW);
23
24            // Add a document certification (MDP) signature
25            // Optionally, the access permissions can be set.
26            Document outDoc = new Signer().certify(inDoc, signature, outStr))
27        {
28        }
29    }
30}

Sign a PDF using a PFX soft certificate

1static void Sign(string certificateFile, string password, string inPath, string outPath)
2{
3    // Create a session to the built-in cryptographic provider
4    using var session = new BuiltIn.Provider();
5
6    // Create signature configuration from PFX (or P12) file
7    using var pfxStr = File.OpenRead(certificateFile);
8    var signature = session.CreateSignatureFromCertificate(pfxStr, password);
9
10    // Embed validation information to enable the long term validation (LTV) of the signature (default)
11    signature.ValidationInformation = PdfTools.Crypto.ValidationInformation.EmbedInDocument;
12
13    // Open input document
14    using var inStr = File.OpenRead(inPath);
15    using var inDoc = Document.Open(inStr);
16
17    // Create stream for output file
18    using var outStr = File.Create(outPath);
19
20    // Sign the input document
21    using var outDoc = new Signer().Sign(inDoc, signature, outStr);
22}
1private static void Sign(String certificateFile, String password, String inPath, String outPath) throws Exception
2{
3    try (
4        // Create a session to the built-in cryptographic provider
5        Provider session = new Provider();
6
7        // Open certificate file
8        FileStream pfxStr = new FileStream(certificateFile, FileStream.Mode.READ_ONLY))
9    {
10        // Create signature configuration from PFX (or P12) file
11        SignatureConfiguration signature = session.createSignatureFromCertificate(pfxStr, password);
12
13        // Embed validation information to enable the long term validation (LTV) of the signature (default)
14        signature.setValidationInformation(com.pdftools.crypto.ValidationInformation.EMBED_IN_DOCUMENT);
15
16        try (
17            // Open input document
18            FileStream inStr = new FileStream(inPath, FileStream.Mode.READ_ONLY);
19            Document inDoc = Document.open(inStr);
20
21            // Create output stream
22            FileStream outStr = new FileStream(outPath, FileStream.Mode.READ_WRITE_NEW);
23
24            // Sign the input document
25            Document outDoc = new Signer().sign(inDoc, signature, outStr))
26        {
27        }
28    }
29}

Add a document time-stamp to a PDF using the GlobalSign Digital Signing Service

1// Configure the SSL client certificate to connect to the service
2var httpClientHandler = new HttpClientHandler();
3using (var sslClientCert = File.OpenRead(@"C:\path\to\clientcert.cer"))
4    using (var sslClientKey = File.OpenRead(@"C:\path\to\privateKey.key"))
5    httpClientHandler.SetClientCertificateAndKey(sslClientCert, sslClientKey, "***insert password***");
6
7// Connect to the GlobalSign Digital Signing Service
8using var session = new GlobalSignDss.Session(new Uri("https://emea.api.dss.globalsign.com:8443"), "***insert api_key***", "***insert api_secret***", httpClientHandler);
9
10// Add a document time-stamp to a PDF
11AddTimestamp(session, inPath, outPath);
1static void AddTimestamp(GlobalSignDss.Session session, string inPath, string outPath)
2{
3    // Create time-stamp configuration
4    var timestamp = session.CreateTimestamp();
5
6    // Open input document
7    using var inStr = File.OpenRead(inPath);
8    using var inDoc = Document.Open(inStr);
9
10    // Create stream for output file
11    using var outStr = File.Create(outPath);
12
13    // Add the document time-stamp
14    using var outDoc = new Signer().AddTimestamp(inDoc, timestamp, outStr);
15}
1// Configure the SSL client certificate to connect to the service
2HttpClientHandler httpClientHandler = new HttpClientHandler();
3try (
4     FileStream sslClientCert = new FileStream("C:/path/to/clientcert.cer", FileStream.Mode.READ_ONLY);
5     FileStream sslClientKey = new FileStream("C:/path/to/privateKey.key", FileStream.Mode.READ_ONLY))
6{
7    httpClientHandler.setClientCertificateAndKey(sslClientCert, sslClientKey, "***insert password***");
8}
9
10// Connect to the GlobalSign Digital Signing Service
11try (Session session = new Session(new URI("https://emea.api.dss.globalsign.com:8443"),
12                                   "***insert api_key***", "***insert api_secret***",
13                                   httpClientHandler))
14{
15    // Add a document time-stamp to a PDF
16    AddTimestamp(session, inPath, outPath);
17}
1private static void AddTimestamp(Session session, String inPath, String outPath) throws Exception
2{
3    // Create time-stamp configuration
4    TimestampConfiguration timestamp = session.createTimestamp();
5
6    try (
7        // Open input document
8        FileStream inStr = new FileStream(inPath, FileStream.Mode.READ_ONLY);
9        Document inDoc = Document.open(inStr);
10
11        // Create output stream
12        FileStream outStr = new FileStream(outPath, FileStream.Mode.READ_WRITE_NEW);
13
14        // Add the document time-stamp
15        Document outDoc = new Signer().addTimestamp(inDoc, timestamp, outStr))
16    {
17    }
18}

Sign a PDF using the GlobalSign Digital Signing Service

1// Configure the SSL client certificate to connect to the service
2var httpClientHandler = new HttpClientHandler();
3using (var sslClientCert = File.OpenRead(@"C:\path\to\clientcert.cer"))
4    using (var sslClientKey = File.OpenRead(@"C:\path\to\privateKey.key"))
5    httpClientHandler.SetClientCertificateAndKey(sslClientCert, sslClientKey, "***insert password***");
6
7// Connect to the GlobalSign Digital Signing Service
8using var session = new GlobalSignDss.Session(new Uri("https://emea.api.dss.globalsign.com:8443"), "***insert api_key***", "***insert api_secret***", httpClientHandler);
9
10// Sign a PDF document
11Sign(session, commonName, inPath, outPath);
1static void Sign(GlobalSignDss.Session session, string commonName, string inPath, string outPath)
2{
3    // Create a signing certificate for an account with a dynamic identity
4    var identity = JsonSerializer.Serialize(new { subject_dn = new { common_name = commonName } });
5    var signature = session.CreateSignatureForDynamicIdentity(identity);
6
7    // Embed validation information to enable the long term validation (LTV) of the signature (default)
8    signature.ValidationInformation = PdfTools.Crypto.ValidationInformation.EmbedInDocument;
9
10    // Open input document
11    using var inStr = File.OpenRead(inPath);
12    using var inDoc = Document.Open(inStr);
13
14    // Create stream for output file
15    using var outStr = File.Create(outPath);
16
17    // Sign the document
18    using var outDoc = new Signer().Sign(inDoc, signature, outStr);
19}
1// Configure the SSL client certificate to connect to the service
2HttpClientHandler httpClientHandler = new HttpClientHandler();
3try (
4     FileStream sslClientCert = new FileStream("C:/path/to/clientcert.cer", FileStream.Mode.READ_ONLY);
5     FileStream sslClientKey = new FileStream("C:/path/to/privateKey.key", FileStream.Mode.READ_ONLY))
6{
7    httpClientHandler.setClientCertificateAndKey(sslClientCert, sslClientKey, "***insert password***");
8}
9
10// Connect to the GlobalSign Digital Signing Service
11try (Session session = new Session(new URI("https://emea.api.dss.globalsign.com:8443"),
12                                   "***insert api_key***", "***insert api_secret***",
13                                   httpClientHandler))
14{
15    // Sign a PDF document
16    Sign(session, commonName, inPath, outPath);
17}
1private static void Sign(Session session, String commonName, String inPath, String outPath) throws Exception
2{
3    // Create a signing certificate for an account with a dynamic identity
4    // This can be re-used to sign multiple documents
5    var signature = session.createSignatureForDynamicIdentity(String.format("{ \"subject_dn\" : { \"common_name\" : \"%s\" } }", commonName));
6
7    // Embed validation information to enable the long term validation (LTV) of the signature (default)
8    signature.setValidationInformation(ValidationInformation.EMBED_IN_DOCUMENT);
9
10    try (
11        // Open input document
12        FileStream inStr = new FileStream(inPath, FileStream.Mode.READ_ONLY);
13        Document inDoc = Document.open(inStr);
14
15        // Create output stream
16        FileStream outStr = new FileStream(outPath, FileStream.Mode.READ_WRITE_NEW);
17
18        // Sign the input document
19        Document outDoc = new Signer().sign(inDoc, signature, outStr))
20    {
21    }
22}

Sign a PDF using a PKCS#11 device

1// Load the PKCS#11 driver module (middleware)
2// The module can only be loaded once in the application.
3using var module = Pkcs11.Module.Load(pkcs11Library);
4
5// Create a session to the cryptographic device and log in
6// with the password (pin)
7using var session = module.Devices.GetSingle().CreateSession(password);
8
9// Sign a PDF document
10Sign(session, certificate, inPath, outPath);
1static void Sign(Pkcs11.Session session, string certificate, string inPath, string outPath)
2{
3    // Create the signature configuration
4    // This can be re-used to sign multiple documents
5    var signature = session.CreateSignatureFromName(certificate);
6
7    // Open input document
8    using var inStr = File.OpenRead(inPath);
9    using var inDoc = Document.Open(inStr);
10
11    // Create stream for output file
12    using var outStr = File.Create(outPath);
13
14    // Sign the input document
15    using var outDoc = new Signer().Sign(inDoc, signature, outStr);
16}
1try (
2    // Load the PKCS#11 driver module (middleware)
3    // The module can only be loaded once in the application.
4    Module module = Module.load(pkcs11Library);
5
6    // Create a session to the cryptographic device and log in
7    // with the password (pin)
8    Session session = module.getDevices().getSingle().createSession(password))
9{
10    // Sign a PDF document
11    Sign(session, certificate, inPath, outPath);
12}
1private static void Sign(Session session, String certificate, String inPath, String outPath) throws Exception
2{
3    // Create the signature configuration
4    // This can be re-used to sign multiple documents
5    var signature = session.createSignatureFromName(certificate);
6
7    try (
8        // Open input document
9        FileStream inStr = new FileStream(inPath, FileStream.Mode.READ_ONLY);
10        Document inDoc = Document.open(inStr);
11
12        // Create output stream
13        FileStream outStr = new FileStream(outPath, FileStream.Mode.READ_WRITE_NEW);
14
15        // Sign the input document
16        Document outDoc = new Signer().sign(inDoc, signature, outStr))
17    {
18    }
19}

Add a signature field to a PDF

1static void AddSignatureField(string inPath, string outPath)
2{
3    // Open input document
4    using var inStr = File.OpenRead(inPath);
5    using var inDoc = Document.Open(inStr);
6
7    // Create empty field appearance that is 6cm by 3cm in size
8    var appearance = Appearance.CreateFieldBoundingBox(Size.cm(6, 3));
9
10    // Add field to last page of document
11    appearance.PageNumber = inDoc.PageCount;
12
13    // Position field
14    appearance.Bottom = Length.cm(3);
15    appearance.Left = Length.cm(6.5);
16
17    // Create a signature field configuration
18    var field = new SignatureFieldOptions(appearance);
19
20    // Create stream for output file
21    using var outStr = File.Create(outPath);
22
23    // Sign the input document
24    using var outDoc = new Signer().AddSignatureField(inDoc, field, outStr);
25}
1private static void AddSignatureField(String inPath, String outPath) throws Exception
2{
3    try (
4        // Open input document
5        FileStream inStr = new FileStream(inPath, FileStream.Mode.READ_ONLY);
6        Document inDoc = Document.open(inStr))
7    {
8        // Create empty field appearance that is 6cm by 3cm in size
9        var appearance = Appearance.createFieldBoundingBox(new Size(6, 3, Units.CENTIMETRE));
10
11        // Add field to last page of document
12        appearance.setPageNumber(inDoc.getPageCount());
13
14        // Position field
15        appearance.setBottom(new Length(3, Units.CENTIMETRE));
16        appearance.setLeft(new Length(6.5, Units.CENTIMETRE));
17
18        // Create a signature field configuration
19        var field = new SignatureFieldOptions(appearance);
20
21        try (
22            // Create output stream
23            FileStream outStr = new FileStream(outPath, FileStream.Mode.READ_WRITE_NEW);
24
25            // Sign the input document
26            Document outDoc = new Signer().addSignatureField(inDoc, field, outStr))
27        {
28        }
29    }
30}

Add a document time-stamp to a PDF using the Swisscom Signing Service

1// Configure the SSL client certificate to connect to the service
2var httpClientHandler = new HttpClientHandler();
3using (var sslClientCert = File.OpenRead(@"C:\path\to\clientcert.p12"))
4    httpClientHandler.SetClientCertificate(sslClientCert, "***insert password***");
5
6// Connect to the Swisscom Signing Service
7using var session = new SwisscomSigSrv.Session(new Uri("https://ais.swisscom.com"), httpClientHandler);
8
9// Add a document time-stamp to a PDF
10AddTimestamp(session, identity, inPath, outPath);
1static void AddTimestamp(SwisscomSigSrv.Session session, string identity, string inPath, string outPath)
2{
3    // Create time-stamp configuration
4    var timestamp = session.CreateTimestamp(identity);
5
6    // Open input document
7    using var inStr = File.OpenRead(inPath);
8    using var inDoc = Document.Open(inStr);
9
10    // Create stream for output file
11    using var outStr = File.Create(outPath);
12
13    // Add the document time-stamp
14    using var outDoc = new Signer().AddTimestamp(inDoc, timestamp, outStr);
15}
1// Configure the SSL client certificate to connect to the service
2HttpClientHandler httpClientHandler = new HttpClientHandler();
3try (FileStream sslClientCert = new FileStream("C:/path/to/clientcert.p12", FileStream.Mode.READ_ONLY))
4{
5    httpClientHandler.setClientCertificate(sslClientCert, "***insert password***");
6}
7
8// Connect to the Swisscom Signing Service
9try (Session session = new Session(new URI("https://ais.swisscom.com"), httpClientHandler))
10{
11    // Add a document time-stamp to a PDF
12    AddTimestamp(session, identity, inPath, outPath);
13}
1private static void AddTimestamp(Session session, String identity, String inPath, String outPath) throws Exception
2{
3    // Create time-stamp configuration
4    TimestampConfiguration timestamp = session.createTimestamp(identity);
5
6    try (
7        // Open input document
8        FileStream inStr = new FileStream(inPath, FileStream.Mode.READ_ONLY);
9        Document inDoc = Document.open(inStr);
10
11        // Create output stream
12        FileStream outStr = new FileStream(outPath, FileStream.Mode.READ_WRITE_NEW);
13
14        // Add the document time-stamp
15        Document outDoc = new Signer().addTimestamp(inDoc, timestamp, outStr))
16    {
17    }
18}

Sign a PDF using the Swisscom Signing Service

1// Configure the SSL client certificate to connect to the service
2var httpClientHandler = new HttpClientHandler();
3using (var sslClientCert = File.OpenRead(@"C:\path\to\clientcert.p12"))
4    httpClientHandler.SetClientCertificate(sslClientCert, "***insert password***");
5
6// Connect to the Swisscom Signing Service
7using var session = new SwisscomSigSrv.Session(new Uri("https://ais.swisscom.com"), httpClientHandler);
8
9// Sign a PDF document
10Sign(session, identity, commonName, inPath, outPath);
1static void Sign(SwisscomSigSrv.Session session, string identity, string commonName, string inPath, string outPath)
2{
3    // Create a signing certificate for a static identity
4    var signature = session.CreateSignatureForStaticIdentity(identity, commonName);
5
6    // Embed validation information to enable the long term validation (LTV) of the signature (default)
7    signature.EmbedValidationInformation = true;
8
9    // Open input document
10    using var inStr = File.OpenRead(inPath);
11    using var inDoc = Document.Open(inStr);
12
13    // Create stream for output file
14    using var outStr = File.Create(outPath);
15
16    // Sign the document
17    using var outDoc = new Signer().Sign(inDoc, signature, outStr);
18}
1// Configure the SSL client certificate to connect to the service
2HttpClientHandler httpClientHandler = new HttpClientHandler();
3try (FileStream sslClientCert = new FileStream("C:/path/to/clientcert.p12", FileStream.Mode.READ_ONLY))
4{
5    httpClientHandler.setClientCertificate(sslClientCert, "***insert password***");
6}
7
8// Connect to the Swisscom Signing Service
9try (Session session = new Session(new URI("https://ais.swisscom.com"), httpClientHandler))
10{
11    // Sign a PDF document
12    Sign(session, identity, commonName, inPath, outPath);
13}
1private static void Sign(Session session, String identity, String commonName, String inPath, String outPath) throws Exception
2{
3    // Create a signing certificate for a static identity
4    // This can be re-used to sign multiple documents
5    var signature = session.createSignatureForStaticIdentity(identity, commonName);
6
7    // Embed validation information to enable the long term validation (LTV) of the signature (default)
8    signature.setEmbedValidationInformation(true);
9
10    try (
11        // Open input document
12        FileStream inStr = new FileStream(inPath, FileStream.Mode.READ_ONLY);
13        Document inDoc = Document.open(inStr);
14
15        // Create output stream
16        FileStream outStr = new FileStream(outPath, FileStream.Mode.READ_WRITE_NEW);
17
18        // Sign the input document
19        Document outDoc = new Signer().sign(inDoc, signature, outStr))
20    {
21    }
22}

Encrypt documents

Decrypt an encrypted PDF

1static void Decrypt(string password, string inPath, string outPath)
2{
3    // Use password to open encrypted input document
4    using var inStr = File.OpenRead(inPath);
5    using var inDoc = Document.Open(inStr, password);
6
7    if (inDoc.Permissions == null)
8        throw new Exception("Input file is not encrypted.");
9
10    // Create stream for output file
11    using var outStr = File.Create(outPath);
12
13    // Set encryption options
14    var outputOptions = new Sign.OutputOptions()
15    {
16        // Set encryption parameters to no encryption
17        Encryption = null,
18        // Allow removal of signatures. Otherwise the Encryption property is ignored for signed input documents
19        // (see warning category Sign.WarningCategory.SignedDocEncryptionUnchanged).
20        RemoveSignatures = Sign.SignatureRemoval.Signed,
21    };
22
23    // Decrypt the document
24    using var outDoc = new Sign.Signer().Process(inDoc, outStr, outputOptions);
25}
1private static void Decrypt(String password, String inPath, String outPath) throws Exception
2{
3    try (
4        // Use password to open encrypted input document
5        FileStream inStr = new FileStream(inPath, FileStream.Mode.READ_ONLY);
6        Document inDoc = Document.open(inStr, password))
7    {
8        if (inDoc.getPermissions() == null)
9            throw new Exception("Input file is not encrypted.");
10
11        // Set encryption options
12        OutputOptions outputOptions = new OutputOptions();
13
14        // Set encryption parameters to no encryption
15        outputOptions.setEncryption(null);
16
17        // Allow removal of signatures. Otherwise the Encryption property is ignored for signed input documents
18        // (see warning category WarningCategory.SIGNED_DOC_ENCRYPTION_UNCHANGED).
19        outputOptions.setRemoveSignatures(SignatureRemoval.SIGNED);
20
21        try(
22            // Create output stream
23            FileStream outStr = new FileStream(outPath, FileStream.Mode.READ_WRITE_NEW);
24
25            // Decrypt the document
26            Document outDoc = new Signer().process(inDoc, outStr, outputOptions))
27        {
28        }
29    }
30}

Encrypted PDF

1static void Encrypt(string password, string inPath, string outPath)
2{
3    // Open input document
4    using var inStr = File.OpenRead(inPath);
5    using var inDoc = Document.Open(inStr);
6
7    // Create stream for output file
8    using var outStr = File.Create(outPath);
9
10    // Set encryption options
11    var outputOptions = new Sign.OutputOptions()
12    {
13        // Set a user password that will be required to open the document.
14        // Note that this will remove PDF/A conformance of input files (see warning category Sign.WarningCategory.PdfARemoved)
15        Encryption = new Encryption(password, null, Permission.All),
16        // Allow removal of signatures. Otherwise the Encryption property is ignored for signed input documents
17        // (see warning category Sign.WarningCategory.SignedDocEncryptionUnchanged).
18        RemoveSignatures = Sign.SignatureRemoval.Signed,
19    };
20
21    // Encrypt the document
22    using var outDoc = new Sign.Signer().Process(inDoc, outStr, outputOptions);
23}
1private static void Encrypt(String password, String inPath, String outPath) throws Exception
2{
3    try (
4        // Open input document
5        FileStream inStr = new FileStream(inPath, FileStream.Mode.READ_ONLY);
6        Document inDoc = Document.open(inStr))
7    {
8        // Set encryption options
9        OutputOptions outputOptions = new OutputOptions();
10
11        // Set a user password that will be required to open the document.
12        // Note that this will remove PDF/A conformance of input files (see warning category WarningCategory.PDF_A_REMOVED)
13        outputOptions.setEncryption(new Encryption(password, null, Permission.ALL));
14
15        // Allow removal of signatures. Otherwise the Encryption property is ignored for signed input documents
16        // (see warning category WarningCategory.SIGNED_DOC_ENCRYPTION_UNCHANGED).
17        outputOptions.setRemoveSignatures(SignatureRemoval.SIGNED);
18
19        try(
20            // Create output stream
21            FileStream outStr = new FileStream(outPath, FileStream.Mode.READ_WRITE_NEW);
22
23            // Encrypt the document
24            Document outDoc = new Signer().process(inDoc, outStr, outputOptions))
25        {
26        }
27    }
28}

Converting images to PDF documents

Convert an image to an accessible PDF/A document

1private static void Image2Pdf(string inPath, string alternateText, string outPath)
2{
3    // Open image document
4    using var inStr = File.OpenRead(inPath);
5    using var inDoc = Document.Open(inStr);
6
7    // Create the profile that defines the conversion parameters.
8    // The Archive profile converts images to PDF/A documents for archiving.
9    var profile = new Profiles.Archive();
10
11    // Set conformance of output document to PDF/A-2a
12    profile.Conformance = new Conformance(2, Conformance.PdfALevel.A);
13
14    // For PDF/A level A, an alternate text is required for each page of the image.
15    // This is optional for other PDF/A levels, e.g. PDF/A-2b.
16    profile.Language = "en";
17    profile.AlternateText.Add(alternateText);
18
19    // Optionally other profile parameters can be changed according to the 
20    // requirements of your conversion process.
21
22    // Create output stream
23    using var outStr = File.Create(outPath);
24
25    // Convert the image to a tagged PDF/A document
26    using var outDoc = new Converter().Convert(inDoc, outStr, profile);
27}
1private static void Image2Pdf(String inPath, String alternateText, String outPath) throws Exception
2{
3    // Create the profile that defines the conversion parameters.
4    // The Archive profile converts images to PDF/A documents for archiving.
5    Archive profile = new Archive();
6
7    // Set conformance of output document to PDF/A-2a
8    profile.setConformance(new Conformance(new Conformance.PdfAVersion(2, Level.A)));
9
10    // For PDF/A level A, an alternate text is required for each page of the image.
11    // This is optional for other PDF/A levels, e.g. PDF/A-2b.
12    profile.setLanguage("en");
13    profile.getAlternateText().add(alternateText);
14
15    // Optionally other profile parameters can be changed according to the 
16    // requirements of your conversion process.
17
18    try (
19        // Open input document
20        FileStream inStr = new FileStream(inPath, FileStream.Mode.READ_ONLY);
21        Document inDoc = Document.open(inStr);
22
23        // Create output stream
24        FileStream outStream = new FileStream(outPath, FileStream.Mode.READ_WRITE_NEW);
25
26        // Convert the image to a tagged PDF/A document
27        com.pdftools.pdf.Document outDoc = new Converter().convert(inDoc, outStream, profile))
28    {
29    }
30}

Convert image to PDF

1private static void Image2Pdf(string inPath, string outPath)
2{
3    // Open image document
4    using var inStr = File.OpenRead(inPath);
5    using var inDoc = Document.Open(inStr);
6
7    // Create the profile that defines the conversion parameters.
8    // The Default profile converts images to PDF documents.
9    var profile = new Profiles.Default();
10
11    // Optionally the profile's parameters can be changed according to the 
12    // requirements of your conversion process.
13
14    // Create output stream
15    using var outStr = File.Create(outPath);
16
17    // Convert the image to a PDF document
18    using var outDoc = new Converter().Convert(inDoc, outStr, profile);
19}
1private static void Image2Pdf(String inPath, String outPath) throws Exception
2{
3    // Create the profile that defines the conversion parameters.
4    // The Default profile converts images to PDF documents.
5    Default profile = new Default();
6
7    // Optionally the profile's parameters can be changed according to the 
8    // requirements of your conversion process.
9
10    try (
11        // Open input document
12        FileStream inStr = new FileStream(inPath, FileStream.Mode.READ_ONLY);
13        Document inDoc = Document.open(inStr);
14
15        // Create output stream
16        FileStream outStream = new FileStream(outPath, FileStream.Mode.READ_WRITE_NEW);
17
18        // Convert the image to a PDF document
19        com.pdftools.pdf.Document outDoc = new Converter().convert(inDoc, outStream, profile))
20    {
21    }
22}

Optimizing documents

Optimize a PDF

1private static void Optimize(string inPath, string outPath)
2{
3    // Open input document
4    using var inStr = File.OpenRead(inPath);
5    using var inDoc = Document.Open(inStr);
6
7    // Create the profile that defines the optimization parameters.
8    // The Web profile is suitable to optimize documents for electronic document exchange.
9    var profile = new Profiles.Web();
10
11    // Optionally the profile's parameters can be changed according to the 
12    // requirements of your optimization process.
13
14    // Create output stream
15    using var outStr = File.Create(outPath);
16
17    // Optimize the document
18    using var outDoc = new Optimizer().OptimizeDocument(inDoc, outStr, profile);
19}
1private static void Optimize(String inPath, String outPath) throws Exception
2{
3    // Create the profile that defines the optimization parameters.
4    // The Web profile is suitable to optimize documents for electronic document exchange.
5    Web profile = new Web();
6
7    // Optionally the profile's parameters can be changed according to the 
8    // requirements of your optimization process.
9
10    try (
11        // Open input document
12        FileStream inStr = new FileStream(inPath, FileStream.Mode.READ_ONLY);
13        Document inDoc = Document.open(inStr);
14
15        // Create output stream
16        FileStream outStr = new FileStream(outPath, FileStream.Mode.READ_WRITE_NEW);
17
18        // Optimize the document
19        Document outDoc = new Optimizer().optimizeDocument(inDoc, outStr, profile))
20    {
21    }
22}
1// Open input document
2pInStream = _tfopen(szInPath, _T("rb"));
3GOTO_CLEANUP_IF_NULL_PRINT_ERROR(pInStream, _T("Failed to open the input file \"%s\" for reading.\n"), szInPath);
4TPdfToolsSys_StreamDescriptor inDesc;
5PdfToolsSysCreateFILEStreamDescriptor(&inDesc, pInStream, 0);
6pInDoc = PdfToolsPdf_Document_Open(&inDesc, _T(""));
7GOTO_CLEANUP_IF_NULL_PRINT_ERROR(pInDoc, _T("Failed to create a document from the input file \"%s\". %s (ErrorCode: 0x%08x).\n"), szInPath, szErrorBuff, PdfTools_GetLastError());
8
9// Create output stream for writing
10pOutStream = _tfopen(szOutPath, _T("wb+"));
11GOTO_CLEANUP_IF_NULL_PRINT_ERROR(pOutStream, _T("Failed to open the output file \"%s\" for writing.\n"), szOutPath);
12TPdfToolsSys_StreamDescriptor outDesc;
13PdfToolsSysCreateFILEStreamDescriptor(&outDesc, pOutStream, 0);
14
15// Create the profile that defines the optimization parameters.
16// The Web profile is suitable to optimize documents for electronic document exchange.
17pProfile = (TPdfToolsOptimizationProfiles_Profile*)PdfToolsOptimizationProfiles_Web_New();
18
19// Optionally the profile's parameters can be changed according to the 
20// requirements of your optimization process.
21
22// Optimize the document
23pOptimizer = PdfToolsOptimization_Optimizer_New();
24pOutDoc = PdfToolsOptimization_Optimizer_OptimizeDocument(pOptimizer, pInDoc, &outDesc, pProfile, NULL);
25GOTO_CLEANUP_IF_NULL_PRINT_ERROR(pOutDoc, _T("The processing has failed. (ErrorCode: 0x%08x).\n"), PdfTools_GetLastError());
26

Convert a PDF document to PDF/A-2b if necessary

1static void ConvertIfNotConforming(string inPath, string outPath, Conformance conformance)
2{
3    // Open input document
4    using var inStr = File.OpenRead(inPath);
5    using var inDoc = Document.Open(inStr);
6
7    // Create validator to analyze PDF/A standard conformance of input document
8    var validator = new Validator();
9    var analysisOptions = new AnalysisOptions() { Conformance = conformance };
10    var analysisResult = validator.Analyze(inDoc, analysisOptions);
11
12    // Check if conversion to PDF/A is necessary
13    if (analysisResult.IsConforming)
14    {
15        Console.WriteLine($"Document conforms to {inDoc.Conformance} already.");
16        return;
17    }
18
19    // Create a converter object
20    var converter = new Converter();
21
22    // Add handler for conversion events
23    var eventsSeverity = EventSeverity.Information;
24    converter.ConversionEvent += (s, e) =>
25    {
26        // Get the event's suggested severity
27        var severity = e.Severity;
28
29        // Optionally the suggested severity can be changed according to
30        // the requirements of your conversion process and, for example,
31        // the event's category (e.Category).
32
33        if (severity > eventsSeverity)
34            eventsSeverity = severity;
35
36        // Report conversion event
37        Console.WriteLine("- {0} {1}: {2} ({3}{4})",
38            severity.ToString()[0], e.Category, e.Message, e.Context, e.PageNo > 0 ? " page " + e.PageNo : ""
39        );
40    };
41
42    // Create stream for output file
43    using var outStr = File.Create(outPath);
44
45    // Convert the input document to PDF/A using the converter object
46    // and its conversion event handler
47    using var outDoc = converter.Convert(analysisResult, inDoc, outStr);
48
49    // Check if critical conversion events occurred
50    switch (eventsSeverity)
51    {
52        case EventSeverity.Information:
53            Console.WriteLine($"Successfully converted document to {outDoc.Conformance}.");
54            break;
55
56        case EventSeverity.Warning:
57            Console.WriteLine($"Warnings occurred during the conversion of document to {outDoc.Conformance}.");
58            Console.WriteLine($"Check the output file to decide if the result is acceptable.");
59            break;
60
61        case EventSeverity.Error:
62            throw new Exception($"Unable to convert document to {conformance} because of critical conversion events.");
63    }
64}
1private static void ConvertIfNotConforming(String inPath, String outPath, Conformance conformance) throws Exception
2{
3    // Open input document
4    try (FileStream inStr = new FileStream(inPath, FileStream.Mode.READ_ONLY);
5         Document inDoc = Document.open(inStr))
6    {
7        // Create validator to analyze PDF/A standard conformance of input document
8        AnalysisOptions analysisOptions = new AnalysisOptions();
9        analysisOptions.setConformance(conformance);
10        Validator validator = new Validator();
11        AnalysisResult analysisResult = validator.analyze(inDoc, analysisOptions);
12
13        // Check if conversion to PDF/A is necessary
14        if (analysisResult.getIsConforming())
15        {
16            System.out.println("Document conforms to " + inDoc.getConformance() + " already.");
17            return;
18        }
19
20        // Create output stream
21        try (FileStream outStr = new FileStream(outPath, FileStream.Mode.READ_WRITE_NEW))
22        {
23            // Create a converter object
24            Converter converter = new Converter();
25
26            // Add handler for conversion events
27            class EventListener implements ConversionEventListener
28            {
29                private EventSeverity eventsSeverity = EventSeverity.INFORMATION;
30
31                public EventSeverity getEventsSeverity() {
32                    return eventsSeverity;
33                }
34
35                @Override
36                public void conversionEvent(ConversionEvent event) {
37                    // Get the event's suggested severity
38                    EventSeverity severity = event.getSeverity();
39
40                    // Optionally the suggested severity can be changed according to
41                    // the requirements of your conversion process and, for example,
42                    // the event's category (e.Category).
43
44                    if (severity.ordinal() > eventsSeverity.ordinal())
45                        eventsSeverity = severity;
46
47                    // Report conversion event
48                    System.out.format("- %c %s: %s (%s%s)%n", severity.toString().charAt(0), event.getCategory(), event.getMessage(), event.getContext(), event.getPageNo() > 0 ? " on page " + event.getPageNo() : "");
49                }
50            }
51            EventListener el = new EventListener();
52
53            converter.addConversionEventListener(el);
54
55            // Convert the input document to PDF/A using the converter object
56            // and its conversion event handler
57            try (Document outDoc = converter.convert(analysisResult, inDoc, outStr))
58            {
59                // Check if critical conversion events occurred
60                switch (el.getEventsSeverity())
61                {
62                    case INFORMATION:
63                        System.out.println("Successfully converted document to " + outDoc.getConformance() + ".");
64                        break;
65
66                    case WARNING:
67                        System.out.println("Warnings occurred during the conversion of document to " + outDoc.getConformance() + ".");
68                        System.out.println("Check the output file to decide if the result is acceptable.");
69                        break;
70
71                    case ERROR:
72                        throw new Exception("Unable to convert document to " + conformance + " because of critical conversion events.");
73                }
74            }
75        }
76
77    }
78}
1void EventListener(void* pContext, const char* szDataPart, const char* szMessage, TPdfToolsPdfAConversion_EventSeverity iSeverity, TPdfToolsPdfAConversion_EventCategory iCategory, TPdfToolsPdfAConversion_EventCode iCode, const char* szContext, int iPageNo)
2{
3    // iSeverity is the event's suggested severity
4    // Optionally the suggested severity can be changed according to
5    // the requirements of your conversion process and, for example,
6    // the event's category (e.Category).
7
8    if (iSeverity > iEventsSeverity)
9        iEventsSeverity = iSeverity;
10
11    // Report conversion event
12    TCHAR cSeverity = iSeverity == ePdfToolsPdfAConversion_EventSeverity_Information ? 'I' :
13                                   ePdfToolsPdfAConversion_EventSeverity_Warning     ? 'W' :
14                                                                                       'E';
15    if (iPageNo > 0)
16        _tprintf(_T("- %c %d: %s (%s on page %d)\n"), cSeverity, iCategory, szMessage, szContext, iPageNo);
17    else
18        _tprintf(_T("- %c %d: %s (%s)\n"), cSeverity, iCategory, szMessage, szContext);
19}
1void ConvertIfNotConforming(const TCHAR* szInPath, const TCHAR* szOutPath, TPdfToolsPdf_Conformance iConf)
2{
3    TPdfToolsPdfAValidation_AnalysisOptions* pAOpt = NULL;
4    TPdfToolsPdfAValidation_Validator * pValidator = NULL;
5    TPdfToolsPdfAValidation_AnalysisResult* pARes = NULL;
6    TPdfToolsPdfAConversion_ConversionOptions* pConvOpt = NULL;
7    TPdfToolsPdfAConversion_Converter* pConv = NULL;
8    TPdfToolsPdf_Document* pOutDoc = NULL;
9    TPdfToolsPdf_Document* pInDoc = NULL;
10    FILE* pInStream = NULL;
11    FILE* pOutStream = NULL;
12
13    // Open input document
14    pInStream = _tfopen(szInPath, _T("rb"));
15    GOTO_CLEANUP_IF_NULL_PRINT_ERROR(pInStream, _T("Failed to open the input file \"%s\" for reading.\n"), szInPath);
16    TPdfToolsSys_StreamDescriptor inDesc;
17    PdfToolsSysCreateFILEStreamDescriptor(&inDesc, pInStream, 0);
18    pInDoc = PdfToolsPdf_Document_Open(&inDesc, _T(""));
19    GOTO_CLEANUP_IF_NULL_PRINT_ERROR(pInDoc, _T("Failed to open document \"%s\". %s (ErrorCode: 0x%08x).\n"), szInPath, szErrBuf, PdfTools_GetLastError());
20
21    // Create validator to analyze PDF/A standard conformance of input document
22    pAOpt = PdfToolsPdfAValidation_AnalysisOptions_New();
23    PdfToolsPdfAValidation_AnalysisOptions_SetConformance(pAOpt, iConf);
24    pValidator = PdfToolsPdfAValidation_Validator_New();
25    pARes = PdfToolsPdfAValidation_Validator_Analyze(pValidator, pInDoc, pAOpt);
26    GOTO_CLEANUP_IF_NULL_PRINT_ERROR(pARes, _T("Failed to analyze document. %s (ErrorCode: 0x%08x).\n"), szErrBuf, PdfTools_GetLastError());
27
28    // Check if conversion to PDF/A is necessary
29    if (PdfToolsPdfAValidation_AnalysisResult_IsConforming(pARes))
30    {
31        printf("Document conforms to %s already.\n", PdfToolsPdf_Conformance_ToStringA(iConf));
32        goto cleanup;
33    }
34
35    // Create output stream for writing
36    pOutStream = _tfopen(szOutPath, _T("wb+"));
37    GOTO_CLEANUP_IF_NULL_PRINT_ERROR(pOutStream, _T("Failed to create the output file \"%s\".\n"), szOutPath);
38    TPdfToolsSys_StreamDescriptor outDesc;
39    PdfToolsSysCreateFILEStreamDescriptor(&outDesc, pOutStream, 0);
40
41    // Convert the input document to PDF/A using the converter object
42    // and its conversion event handler
43    pConvOpt = PdfToolsPdfAConversion_ConversionOptions_New();
44    pConv = PdfToolsPdfAConversion_Converter_New();
45    PdfToolsPdfAConversion_Converter_AddConversionEventHandlerA(pConv, NULL, (TPdfToolsPdfAConversion_Converter_ConversionEventA)EventListener);
46    pOutDoc = PdfToolsPdfAConversion_Converter_Convert(pConv, pARes, pInDoc, &outDesc, pConvOpt, NULL);
47    GOTO_CLEANUP_IF_NULL_PRINT_ERROR(pOutDoc, _T("Failed to convert document. %s (ErrorCode: 0x%08x).\n"), szErrBuf, PdfTools_GetLastError());
48
49    // Check if critical conversion events occurred
50    switch (iEventsSeverity)
51    {
52        case ePdfToolsPdfAConversion_EventSeverity_Information:
53        {
54            TPdfToolsPdf_Conformance iOutConf;
55            PdfToolsPdf_Document_GetConformance(pOutDoc, &iOutConf);
56            printf("Successfully converted document to %s.\n", PdfToolsPdf_Conformance_ToStringA(iOutConf));
57            break;
58        }
59
60        case ePdfToolsPdfAConversion_EventSeverity_Warning:
61        {
62            TPdfToolsPdf_Conformance iOutConf;
63            PdfToolsPdf_Document_GetConformance(pOutDoc, &iOutConf);
64            printf("Warnings occurred during the conversion of document to %s.\n", PdfToolsPdf_Conformance_ToStringA(iOutConf));
65            printf("Check the output file to decide if the result is acceptable.\n");
66            break;
67        }
68
69        case ePdfToolsPdfAConversion_EventSeverity_Error:
70        {
71            printf("Unable to convert document to %s because of critical conversion events.\n", PdfToolsPdf_Conformance_ToStringA(iConf));
72            break;
73        }
74    }
75
76cleanup:
77    PdfToolsPdf_Document_Close(pOutDoc);
78    PdfTools_Release(pConv);
79    PdfTools_Release(pConvOpt);
80    PdfTools_Release(pARes);
81    PdfTools_Release(pValidator);
82    PdfTools_Release(pAOpt);
83    PdfToolsPdf_Document_Close(pInDoc);
84    if (pInStream)
85        fclose(pInStream);
86    if (pOutStream)
87        fclose(pOutStream);
88}

Converting documents to rasterized images

Convert PDF to image

1private static void Pdf2Image(string inPath, string outPath)
2{
3    // Open input document
4    using var inStr = File.OpenRead(inPath);
5    using var inDoc = Document.Open(inStr);
6
7    // Create the profile that defines the conversion parameters.
8    // The Archive profile converts PDF documents to TIFF images for archiving.
9    var profile = new Profiles.Archive();
10
11    // Optionally the profile's parameters can be changed according to the 
12    // requirements of your conversion process.
13
14    // Create output stream
15    using var outStr = File.Create(outPath);
16
17    // Convert the PDF document to an image document
18    using var outDoc = new Converter().ConvertDocument(inDoc, outStr, profile);
19}
1private static void Pdf2Image(String inPath, String outPath) throws Exception
2{
3    // Create the profile that defines the conversion parameters.
4    // The Archive profile converts PDF documents to TIFF images for archiving.
5    Archive profile = new Archive();
6
7    // Optionally the profile's parameters can be changed according to the 
8    // requirements of your conversion process.
9
10    try (
11        // Open input document
12        FileStream inStr = new FileStream(inPath, FileStream.Mode.READ_ONLY);
13        Document inDoc = Document.open(inStr);
14
15        // Create output stream
16        FileStream outStream = new FileStream(outPath, FileStream.Mode.READ_WRITE_NEW);
17
18        // Convert the PDF document to an image document
19        com.pdftools.image.Document outDoc = new Converter().convertDocument(inDoc, outStream, profile))
20    {
21    }
22}
1// Open input document
2pInStream = _tfopen(szInPath, _T("rb"));
3GOTO_CLEANUP_IF_NULL_PRINT_ERROR(pInStream, _T("Failed to open the input file \"%s\" for reading.\n"), szInPath);
4TPdfToolsSys_StreamDescriptor inDesc;
5PdfToolsSysCreateFILEStreamDescriptor(&inDesc, pInStream, 0);
6pInDoc = PdfToolsPdf_Document_Open(&inDesc, _T(""));
7GOTO_CLEANUP_IF_NULL_PRINT_ERROR(pInDoc, _T("Failed to create a document from the input file \"%s\". %s (ErrorCode: 0x%08x).\n"), szInPath, szErrorBuff, PdfTools_GetLastError());
8
9// Create output stream for writing
10pOutStream = _tfopen(szOutPath, _T("wb+"));
11GOTO_CLEANUP_IF_NULL_PRINT_ERROR(pOutStream, _T("Failed to open the output file \"%s\" for writing.\n"), szOutPath);
12TPdfToolsSys_StreamDescriptor outDesc;
13PdfToolsSysCreateFILEStreamDescriptor(&outDesc, pOutStream, 0);
14
15// Create the profile that defines the conversion parameters.
16// The Archive profile converts PDF documents to TIFF images for archiving.
17pProfile = (TPdfToolsPdf2ImageProfiles_Profile*)PdfToolsPdf2ImageProfiles_Archive_New();
18
19// Optionally the profile's parameters can be changed according to the 
20// requirements of your conversion process.
21
22// Convert the PDF document to an image document
23pConverter = PdfToolsPdf2Image_Converter_New();
24pOutDoc = (TPdfToolsImage_Document*)PdfToolsPdf2Image_Converter_ConvertDocument(pConverter, pInDoc, &outDesc, pProfile);
25GOTO_CLEANUP_IF_NULL_PRINT_ERROR(pOutDoc, _T("The processing has failed. (ErrorCode: 0x%08x).\n"), PdfTools_GetLastError());
26

Validate the conformance of documents

Validate the PDF conformance

1private static ValidationResult Validate(string inPath)
2{
3    // Open the document
4    using var inStr = File.OpenRead(inPath);
5    using var inDoc = Document.Open(inStr);
6
7    // Create a validator object that writes all validation error messages to the console
8    var validator = new Validator();
9    validator.Error += (s, e) => Console.WriteLine("- {0}: {1} ({2}{3})", e.Category, e.Message, e.Context, e.PageNo > 0 ? " on page" + e.PageNo : "");
10
11    // Validate the standard conformance of the document
12    return validator.Validate(inDoc);
13}
1private static ValidationResult Validate(String inPath) throws Exception
2{
3    // Open input document
4    try (FileStream inStr = new FileStream(inPath, FileStream.Mode.READ_ONLY);
5         Document inDoc = Document.open(inStr))
6    {
7        // Create a validator object that writes all validation error messages to the console
8        Validator validator = new Validator();
9        validator.addErrorListener(
10            (Validator.Error error) ->
11            System.out.format("- %s: %s (%s%s)%n", error.getCategory(), error.getMessage(), error.getContext(), error.getPageNo() > 0 ? String.format(" on page %d", error.getPageNo()) : "")
12        );
13
14        // Validate the standard conformance of the document
15        return validator.validate(inDoc);
16    }
17}
1void ErrorListener(void* pContext, const TCHAR* szDataPart, const TCHAR* szMessage, TPdfToolsPdfAValidation_ErrorCategory iCategory, const TCHAR* szContext, int iPageNo, int iObjectNo)
2{
3    if (iPageNo > 0)
4        _tprintf(_T("- %d: %s (%s on page %d)\n"), iCategory, szMessage, szContext, iPageNo);
5    else
6        _tprintf(_T("- %d: %s (%s)\n"), iCategory, szMessage, szContext);
7}
1void Validate(const TCHAR* szInPath)
2{
3    TPdfToolsPdf_Document* pInDoc = NULL;
4    TPdfToolsPdfAValidation_Validator* pValidator = NULL;
5    TPdfToolsPdfAValidation_ValidationResult* pResult = NULL;
6
7    // Open input document
8    FILE* pInStream = _tfopen(szInPath, _T("rb"));
9    GOTO_CLEANUP_IF_NULL_PRINT_ERROR(pInStream, _T("Failed to open the input file \"%s\" for reading.\n"), szInPath);
10    TPdfToolsSys_StreamDescriptor inDesc;
11    PdfToolsSysCreateFILEStreamDescriptor(&inDesc, pInStream, 0);
12    pInDoc = PdfToolsPdf_Document_Open(&inDesc, _T(""));
13    GOTO_CLEANUP_IF_NULL_PRINT_ERROR(pInDoc, _T("Failed to open document \"%s\". %s (ErrorCode: 0x%08x).\n"), szInPath, szErrBuf, PdfTools_GetLastError());
14
15    // Create a validator object that writes all validation error messages to the console
16    pValidator = PdfToolsPdfAValidation_Validator_New();
17    PdfToolsPdfAValidation_Validator_AddErrorHandler(pValidator, NULL, (TPdfToolsPdfAValidation_Validator_Error)ErrorListener);
18
19    // Validate the standard conformance of the document
20    pResult = PdfToolsPdfAValidation_Validator_Validate(pValidator, pInDoc, NULL);
21    GOTO_CLEANUP_IF_NULL_PRINT_ERROR(pResult, _T("Failed to validate document. %s (ErrorCode: 0x%08x).\n"), szErrBuf, PdfTools_GetLastError());
22
23    // Report validation result
24    TPdfToolsPdf_Conformance iClaimedConformance;
25    PdfToolsPdf_Document_GetConformance(pInDoc, &iClaimedConformance);
26    if (PdfToolsPdfAValidation_ValidationResult_IsConforming(pResult))
27        printf("Document conforms to %s.\n", PdfToolsPdf_Conformance_ToStringA(iClaimedConformance));
28    else
29        printf("Document does not conform to %s.\n", PdfToolsPdf_Conformance_ToStringA(iClaimedConformance));
30
31cleanup:
32    PdfTools_Release(pResult);
33    PdfTools_Release(pValidator);
34    PdfToolsPdf_Document_Close(pInDoc);
35    if (pInStream)
36        fclose(pInStream);
37}