Skip to main content
Version: Version 1.7

Pdftools SDK code samples

Start using the Pdftools SDK library with code samples. Integrate advanced PDF manipulation, optimization, and validation tasks into your application in Java, .NET, C, and Python.

info

Select a code sample in a specific language and download it. The code samples illustrate how to integrate the SDK into your projects for specific use cases. Each code sample includes a README file that gives instructions on how to run the code sample to process one or multiple files.

tip

Do you miss a specific sample and want us to include it here? Let us know through the Contact page, and we'll add it to our sample backlog.

Assembling documents

Merge PDFs

1// Create output stream
2pOutStream = _tfopen(szOutPath, _T("wb+"));
3GOTO_CLEANUP_IF_NULL_PRINT_ERROR(pOutStream, _T("Failed to create output file \"%s\" for writing.\n"), szOutPath);
4TPdfToolsSys_StreamDescriptor outDesc;
5PdfToolsSysCreateFILEStreamDescriptor(&outDesc, pOutStream, 0);
6pAssembler = PdfToolsDocumentAssembly_DocumentAssembler_New(&outDesc, NULL, NULL);
7
8for (int i = 1; i < argc - 1; i++)
9{
10    szInPath = argv[i];
11    // Open input document
12    pInStream = _tfopen(szInPath, _T("rb"));
13    GOTO_CLEANUP_IF_NULL_PRINT_ERROR(pInStream, _T("Failed to open the input file \"%s\" for reading.\n"),
14                                     szInPath);
15    TPdfToolsSys_StreamDescriptor inDesc;
16    PdfToolsSysCreateFILEStreamDescriptor(&inDesc, pInStream, 0);
17    pInDoc = PdfToolsPdf_Document_Open(&inDesc, _T(""));
18    GOTO_CLEANUP_IF_NULL_PRINT_ERROR(
19        pInDoc, _T("Failed to create a document from the input file \"%s\". %s (ErrorCode: 0x%08x).\n"), szInPath,
20        szErrorBuff, PdfTools_GetLastError());
21
22    // Append the content of the input documents to the output document
23    GOTO_CLEANUP_IF_FALSE_PRINT_ERROR(
24        PdfToolsDocumentAssembly_DocumentAssembler_Append(pAssembler, pInDoc, NULL, NULL, NULL, NULL),
25        _T("Failed to append a page. (ErrorCode: 0x%08x).\n"), PdfTools_GetLastError());
26
27    PdfToolsPdf_Document_Close(pInDoc);
28    fclose(pInStream);
29    pInDoc    = NULL;
30    pInStream = NULL;
31}
32// Merge input documents into an output document
33pOutDoc = PdfToolsDocumentAssembly_DocumentAssembler_Assemble(pAssembler);
34
35GOTO_CLEANUP_IF_NULL_PRINT_ERROR(pOutDoc, _T("The processing has failed. (ErrorCode: 0x%08x).\n"),
36                                 PdfTools_GetLastError());
37
Download code sample
1private static void Merge(IEnumerable<string> inPaths, string outPath)
2{
3    // Create output stream
4    using var outStream = File.Create(outPath);
5    using var docAssembler = new PdfTools.DocumentAssembly.DocumentAssembler(outStream);
6
7    foreach (var inPath in inPaths)
8    {
9        using var inStream = File.OpenRead(inPath);
10        using var inDoc = PdfTools.Pdf.Document.Open(inStream);
11        // Append the content of the input documents to the output document
12        docAssembler.Append(inDoc);
13    }
14
15    // Merge input documents into an output document
16    docAssembler.Assemble();
17}
Download code sample
1    private static void merge(String[] inPaths, String outPath) throws Exception
2    {
3    	try (
4            // Create output stream
5            FileStream outStream = new FileStream(outPath, FileStream.Mode.READ_WRITE_NEW);
6            DocumentAssembler docAssembler = new DocumentAssembler(outStream)) {
7            for (String inPath : inPaths) {
8	            try (
9	                // Open input document
10	                FileStream inStr = new FileStream(inPath, FileStream.Mode.READ_ONLY);
11	                Document inDoc = Document.open(inStr)) {
12	                // Append the content of each input document to the output document
13	                docAssembler.append(inDoc);
14	            }
15            }
16            // Merge input documents into an output document
17            docAssembler.assemble();
18    	}
19    }
Download code sample
1
2
3merge(args.input_path, args.output_path)
4
1def merge(input_paths: str, output_path: str):
2    # Create output stream
3    with io.FileIO(output_path, 'wb+') as output_stream:
4        with DocumentAssembler(output_stream, None, None) as assembler:
5
6            for input_path in input_paths:
7                with open(input_path, 'rb') as input_stream:
8                    with Document.open(input_stream) as input_document:
9                        # Append the content of the input documents to the output document
10                        assembler.append(input_document)
11
12            # Merge input documents into an output document
13            assembler.assemble()
Download code sample
1Private Sub Merge(inPaths As IEnumerable(Of String), outPath As String)
2    ' Create output stream
3    Using outStream = File.Create(outPath)
4        Using docAssembler = New PdfTools.DocumentAssembly.DocumentAssembler(outStream)
5
6            For Each inPath In inPaths
7                Using inStream = File.OpenRead(inPath)
8                    Using inDoc = PdfTools.Pdf.Document.Open(inStream)
9                        ' Append the content of the input documents to the output document
10                        docAssembler.Append(inDoc)
11                    End Using
12                End Using
13            Next
14
15            ' Merge input documents into an output document
16            docAssembler.Assemble()
17        End Using
18    End Using
19End Sub
Download code sample

Split PDF document

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(""));
7
8GOTO_CLEANUP_IF_NULL_PRINT_ERROR(
9    pInDoc, _T("Failed to create a document from the input file \"%s\". %s (ErrorCode: 0x%08x).\n"), szInPath,
10    szErrorBuff, PdfTools_GetLastError());
11
12// Split input document by generating one output document per page
13int   nPageCount = PdfToolsPdf_Document_GetPageCount(pInDoc);
14TCHAR szPageFileName[256];
15for (int i = 1; i <= nPageCount; i++)
16{
17    CreateOutputFileName(szPageFileName, szOutPath, i);
18
19    // Create output stream for each page of the input document
20    pOutStream = _tfopen(szPageFileName, _T("wb+"));
21    GOTO_CLEANUP_IF_NULL_PRINT_ERROR(pOutStream, _T("Failed to open the input file \"%s\" for reading.\n"),
22                                     szPageFileName);
23    TPdfToolsSys_StreamDescriptor outDesc;
24    PdfToolsSysCreateFILEStreamDescriptor(&outDesc, pOutStream, 0);
25
26    // Split pdf into pages
27    pAssembler = PdfToolsDocumentAssembly_DocumentAssembler_New(&outDesc, NULL, NULL);
28    GOTO_CLEANUP_IF_FALSE_PRINT_ERROR(
29        PdfToolsDocumentAssembly_DocumentAssembler_Append(pAssembler, pInDoc, &i, &i, NULL, NULL),
30        _T("Failed to append a page. (ErrorCode: 0x%08x).\n"), PdfTools_GetLastError());
31    pOutDoc = PdfToolsDocumentAssembly_DocumentAssembler_Assemble(pAssembler);
32    PdfToolsDocumentAssembly_DocumentAssembler_Close(pAssembler);
33
34    if (pOutDoc)
35        PdfToolsPdf_Document_Close(pOutDoc);
36    if (pOutStream)
37        fclose(pOutStream);
38    GOTO_CLEANUP_IF_NULL_PRINT_ERROR(pOutDoc, _T("The processing has failed. (ErrorCode: 0x%08x).\n"),
39                                     PdfTools_GetLastError());
40}
41
Download code sample
1private static void Split(string inPath, string outPathPrefix)
2{
3    // Open input document
4    using var inStream = File.OpenRead(inPath);
5    using var inDoc = PdfTools.Pdf.Document.Open(inStream);
6
7    // Split the input document page by page
8    for (int i = 1; i <= inDoc.PageCount; ++i)
9    {
10        using var outStream = File.Create(outPathPrefix + "_page_" + i + ".pdf");
11        using var docAssembler = new PdfTools.DocumentAssembly.DocumentAssembler(outStream);
12        docAssembler.Append(inDoc, i, i);
13        docAssembler.Assemble();
14    }
15}
Download code sample
1private static void split(String inPath, String outPathPrefix) 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        for (int i = 1; i <= inDoc.getPageCount(); ++i) {
8            try (
9                // Create output stream for each page of the input document
10                FileStream outStream = new FileStream(outPathPrefix + "_page_" + i + ".pdf", FileStream.Mode.READ_WRITE_NEW);
11                DocumentAssembler docAssembler = new DocumentAssembler(outStream)) {
12                docAssembler.append(inDoc, i, i);
13                docAssembler.assemble();
14            }
15        }
16    }
17}
Download code sample
1def split_pdf(input_file_path: str, output_file_path: str):
2    # Open input document
3    with open(input_file_path, 'rb') as input_stream:
4        with Document.open(input_stream) as input_document:
5            # Split the input document page by page
6            for i in range(1, input_document.page_count + 1):
7                current_out_file = construct_file_name(output_file_path, i)
8                with open(current_out_file, 'wb+') as output_stream:
9                    with DocumentAssembler(output_stream, None, None) as assembler:
10                        assembler.append(input_document, i, i)
11                        assembler.assemble()
1# Construct file name from input path and page number of input document
2def construct_file_name(input_file: str, page_number: int):
3    # Split the directory and file name from the input path
4    directory, basename = os.path.split(input_file)
5
6    # Split the file base name and extension
7    base, extension = os.path.splitext(basename)
8
9    return os.path.join(directory, f"{base}_page_{page_number}{extension}") 
Download code sample
1Private Sub Split(inPath As String, outPathPrefix As String)
2    ' Open input document
3    Using inStream = File.OpenRead(inPath)
4        Using inDoc = PdfTools.Pdf.Document.Open(inStream)
5
6            ' Split the input document page by page
7            For i As Integer = 1 To inDoc.PageCount
8                Using outStream = File.Create(outPathPrefix & "_page_" & i & ".pdf")
9                    Using docAssembler = New PdfTools.DocumentAssembly.DocumentAssembler(outStream)
10                        docAssembler.Append(inDoc, i, i)
11                        docAssembler.Assemble()
12                    End Using
13                End Using
14            Next
15        End Using
16    End Using
17End Sub
Download code sample

Converting documents to PDF/A

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

1void EventListener(void* pContext, const char* szDataPart, const char* szMessage,
2                   TPdfToolsPdfAConversion_EventSeverity iSeverity, TPdfToolsPdfAConversion_EventCategory iCategory,
3                   TPdfToolsPdfAConversion_EventCode iCode, const char* szContext, int iPageNo)
4{
5    // iSeverity is the event's suggested severity
6    // Optionally the suggested severity can be changed according to
7    // the requirements of your conversion process and, for example,
8    // the event's category (e.Category).
9
10    if (iSeverity > iEventsSeverity)
11        iEventsSeverity = iSeverity;
12
13    // Report conversion event
14    TCHAR cSeverity = iSeverity == ePdfToolsPdfAConversion_EventSeverity_Information ? 'I'
15                      : ePdfToolsPdfAConversion_EventSeverity_Warning                ? 'W'
16                                                                                     : 'E';
17    if (iPageNo > 0)
18        _tprintf(_T("- %c %d: %s (%s on page %d)\n"), cSeverity, iCategory, szMessage, szContext, iPageNo);
19    else
20        _tprintf(_T("- %c %d: %s (%s)\n"), cSeverity, iCategory, szMessage, szContext);
21}
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,
20                                     szErrBuf, PdfTools_GetLastError());
21
22    // Create validator to analyze PDF/A standard conformance of input document
23    pAOpt = PdfToolsPdfAValidation_AnalysisOptions_New();
24    PdfToolsPdfAValidation_AnalysisOptions_SetConformance(pAOpt, iConf);
25    pValidator = PdfToolsPdfAValidation_Validator_New();
26    pARes      = PdfToolsPdfAValidation_Validator_Analyze(pValidator, pInDoc, pAOpt);
27    GOTO_CLEANUP_IF_NULL_PRINT_ERROR(pARes, _T("Failed to analyze document. %s (ErrorCode: 0x%08x).\n"), szErrBuf,
28                                     PdfTools_GetLastError());
29
30    // Check if conversion to PDF/A is necessary
31    if (PdfToolsPdfAValidation_AnalysisResult_IsConforming(pARes))
32    {
33        printf("Document conforms to %s already.\n", PdfToolsPdf_Conformance_ToStringA(iConf));
34        goto cleanup;
35    }
36
37    // Create output stream for writing
38    pOutStream = _tfopen(szOutPath, _T("wb+"));
39    GOTO_CLEANUP_IF_NULL_PRINT_ERROR(pOutStream, _T("Failed to create the output file \"%s\".\n"), szOutPath);
40    TPdfToolsSys_StreamDescriptor outDesc;
41    PdfToolsSysCreateFILEStreamDescriptor(&outDesc, pOutStream, 0);
42
43    // Convert the input document to PDF/A using the converter object
44    // and its conversion event handler
45    pConvOpt = PdfToolsPdfAConversion_ConversionOptions_New();
46    pConv    = PdfToolsPdfAConversion_Converter_New();
47    PdfToolsPdfAConversion_Converter_AddConversionEventHandlerA(
48        pConv, NULL, (TPdfToolsPdfAConversion_Converter_ConversionEventA)EventListener);
49    pOutDoc = PdfToolsPdfAConversion_Converter_Convert(pConv, pARes, pInDoc, &outDesc, pConvOpt, NULL);
50    GOTO_CLEANUP_IF_NULL_PRINT_ERROR(pOutDoc, _T("Failed to convert document. %s (ErrorCode: 0x%08x).\n"), szErrBuf,
51                                     PdfTools_GetLastError());
52
53    // Check if critical conversion events occurred
54    switch (iEventsSeverity)
55    {
56    case ePdfToolsPdfAConversion_EventSeverity_Information:
57    {
58        TPdfToolsPdf_Conformance iOutConf;
59        PdfToolsPdf_Document_GetConformance(pOutDoc, &iOutConf);
60        printf("Successfully converted document to %s.\n", PdfToolsPdf_Conformance_ToStringA(iOutConf));
61        break;
62    }
63
64    case ePdfToolsPdfAConversion_EventSeverity_Warning:
65    {
66        TPdfToolsPdf_Conformance iOutConf;
67        PdfToolsPdf_Document_GetConformance(pOutDoc, &iOutConf);
68        printf("Warnings occurred during the conversion of document to %s.\n",
69               PdfToolsPdf_Conformance_ToStringA(iOutConf));
70        printf("Check the output file to decide if the result is acceptable.\n");
71        break;
72    }
73
74    case ePdfToolsPdfAConversion_EventSeverity_Error:
75    {
76        printf("Unable to convert document to %s because of critical conversion events.\n",
77               PdfToolsPdf_Conformance_ToStringA(iConf));
78        break;
79    }
80    }
81
82cleanup:
83    PdfToolsPdf_Document_Close(pOutDoc);
84    PdfTools_Release(pConv);
85    PdfTools_Release(pConvOpt);
86    PdfTools_Release(pARes);
87    PdfTools_Release(pValidator);
88    PdfTools_Release(pAOpt);
89    PdfToolsPdf_Document_Close(pInDoc);
90    if (pInStream)
91        fclose(pInStream);
92    if (pOutStream)
93        fclose(pOutStream);
94}
Download code sample
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 the Validator object, and use the Conformance object to create
8    // an AnalysisOptions object that controls the behavior of the Validator.
9    var validator = new Validator();
10    var analysisOptions = new AnalysisOptions() { Conformance = conformance };
11
12    // Run the analysis, and check the results.
13    // Only proceed if document is not conforming.
14    var analysisResult = validator.Analyze(inDoc, analysisOptions);
15    if (analysisResult.IsConforming)
16    {
17        Console.WriteLine($"Document conforms to {inDoc.Conformance} already.");
18        return;
19    }
20
21    // Create a converter object
22    var converter = new Converter();
23
24    // Add handler for conversion events
25    var eventsSeverity = EventSeverity.Information;
26    converter.ConversionEvent += (s, e) =>
27    {
28        // Get the event's suggested severity
29        var severity = e.Severity;
30
31        // Optionally the suggested severity can be changed according to
32        // the requirements of your conversion process and, for example,
33        // the event's category (e.Category).
34
35        if (severity > eventsSeverity)
36            eventsSeverity = severity;
37
38        // Report conversion event
39        Console.WriteLine("- {0} {1}: {2} ({3}{4})",
40            severity.ToString()[0], e.Category, e.Message, e.Context, e.PageNo > 0 ? " page " + e.PageNo : ""
41        );
42    };
43
44    // Create stream for output file
45    using var outStr = File.Create(outPath);
46
47    // Convert the input document to PDF/A using the converter object
48    // and its conversion event handler
49    using var outDoc = converter.Convert(analysisResult, inDoc, outStr);
50
51    // Check if critical conversion events occurred
52    switch (eventsSeverity)
53    {
54        case EventSeverity.Information:
55            Console.WriteLine($"Successfully converted document to {outDoc.Conformance}.");
56            break;
57
58        case EventSeverity.Warning:
59            Console.WriteLine($"Warnings occurred during the conversion of document to {outDoc.Conformance}.");
60            Console.WriteLine($"Check the output file to decide if the result is acceptable.");
61            break;
62
63        case EventSeverity.Error:
64            throw new Exception($"Unable to convert document to {conformance} because of critical conversion events.");
65    }
66}
Download code sample
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 the Validator object, and use the Conformance object to create
8        // an AnalysisOptions object that controls the behavior of the Validator.
9        Validator validator = new Validator();
10        AnalysisOptions analysisOptions = new AnalysisOptions();
11        analysisOptions.setConformance(conformance);
12
13        // Run the analysis, and check the results.
14        // Only proceed if document is not conforming.
15        AnalysisResult analysisResult = validator.analyze(inDoc, analysisOptions);
16        if (analysisResult.getIsConforming())
17        {
18            System.out.println("Document conforms to " + inDoc.getConformance() + " already.");
19            return;
20        }
21
22        // Create output stream
23        try (FileStream outStr = new FileStream(outPath, FileStream.Mode.READ_WRITE_NEW))
24        {
25            // Create a converter object
26            Converter converter = new Converter();
27
28            // Add handler for conversion events
29            class EventListener implements ConversionEventListener
30            {
31                private EventSeverity eventsSeverity = EventSeverity.INFORMATION;
32
33                public EventSeverity getEventsSeverity() {
34                    return eventsSeverity;
35                }
36
37                @Override
38                public void conversionEvent(ConversionEvent event) {
39                    // Get the event's suggested severity
40                    EventSeverity severity = event.getSeverity();
41
42                    // Optionally the suggested severity can be changed according to
43                    // the requirements of your conversion process and, for example,
44                    // the event's category (e.Category).
45
46                    if (severity.ordinal() > eventsSeverity.ordinal())
47                        eventsSeverity = severity;
48
49                    // Report conversion event
50                    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() : "");
51                }
52            }
53            EventListener el = new EventListener();
54
55            converter.addConversionEventListener(el);
56
57            // Convert the input document to PDF/A using the converter object
58            // and its conversion event handler
59            try (Document outDoc = converter.convert(analysisResult, inDoc, outStr))
60            {
61                // Check if critical conversion events occurred
62                switch (el.getEventsSeverity())
63                {
64                    case INFORMATION:
65                        System.out.println("Successfully converted document to " + outDoc.getConformance() + ".");
66                        break;
67
68                    case WARNING:
69                        System.out.println("Warnings occurred during the conversion of document to " + outDoc.getConformance() + ".");
70                        System.out.println("Check the output file to decide if the result is acceptable.");
71                        break;
72
73                    case ERROR:
74                        throw new Exception("Unable to convert document to " + conformance + " because of critical conversion events.");
75                }
76            }
77        }
78
79    }
80}
Download code sample
1def convert_if_not_conforming(input_file_path: str, output_file_path: str, conformance: Conformance):
2    with io.FileIO(input_file_path, 'rb') as in_stream:
3        with Document.open(in_stream) as input_document:
4
5            # Create the Validator object, and use the Conformance object to create
6            # an AnalysisOptions object that controls the behavior of the Validator.
7            validator = Validator()
8            analysis_options = AnalysisOptions()
9            analysis_options.conformance = conformance
10
11            # Run the analysis, and check the results.
12            # Only proceed if document is not conforming.
13            analysis_result = validator.analyze(input_document, analysis_options)
14            if analysis_result.is_conforming:
15                print(f"Document conforms to {input_document.conformance.name} already.")
16                return
17
18            # Create a converter object
19            converter = Converter()
20
21            # Add handler for conversion events
22            converter.add_conversion_event_handler(event_handler)
23
24            with io.FileIO(output_file_path, 'wb+') as output_stream:
25
26                # Convert the input document to PDF/A using the converter object
27                # and its conversion event handler
28                output_document = converter.convert(analysis_result, input_document, output_stream, None)
29
30                # Check if critical conversion events occurred
31                match events_severity:
32                    case EventSeverity.INFORMATION:
33                        print(f"Successfully converted document to {output_document.conformance.name}.")
34
35                    case EventSeverity.WARNING:
36                        print(f"Warnings occurred during the conversion of document to {output_document.conformance.name}.")
37                        print("Check the output file to decide if the result is acceptable.")
38
39                    case EventSeverity.ERROR:
40                        raise Exception(f"Unable to convert document to {conformance.name} because of critical conversion events.")
1def event_handler(data_part: str, message: str, severity: EventSeverity, category: EventCategory, code: EventCode, context_info: str, page_no: int):
2
3    # Get the event's suggested severity
4    suggested_severity = severity
5
6    # Optionally, the suggested severity can be changed according to
7    # the requirements of your conversion process and, for example,
8    # the event's category.
9
10    global events_severity
11
12    if suggested_severity > events_severity:
13        events_severity = suggested_severity
14
15    # Report conversion event
16    if suggested_severity == EventSeverity.INFORMATION:
17        severity_char = 'I'
18    elif suggested_severity == EventSeverity.WARNING:
19        severity_char = 'W'
20    else:
21        severity_char = 'E'
22
23    if page_no > 0:
24        print(f"- {severity_char} {category.name}: {message} ({context_info} on page {page_no})")
25    else:
26        print(f"- {severity_char} {category.name}: {message} ({context_info})")   
Download code sample
1Sub ConvertIfNotConforming(inPath As String, outPath As String, conformance As Conformance)
2    ' Open input document
3    Using inStr = File.OpenRead(inPath)
4        Using inDoc = Document.Open(inStr)
5            ' Create the Validator object, and use the Conformance object to create
6            ' an AnalysisOptions object that controls the behavior of the Validator.
7            Dim validator = New Validator()
8            Dim analysisOptions = New AnalysisOptions() With {.conformance = conformance}
9
10            ' Run the analysis, and check the results.
11            ' Only proceed if document is not conforming.
12            Dim analysisResult = validator.Analyze(inDoc, analysisOptions)
13            If analysisResult.IsConforming Then
14                Console.WriteLine($"Document conforms to {inDoc.Conformance} already.")
15                Return
16            End If
17
18            ' Create a converter object
19            Dim converter = New Converter()
20
21            ' Add handler for conversion events
22            Dim eventsSeverity = EventSeverity.Information
23            AddHandler converter.ConversionEvent, Sub(s, e)
24                                                      ' Get the event's suggested severity
25                                                      Dim severity = e.Severity
26
27                                                      ' Optionally the suggested severity can be changed according to
28                                                      ' the requirements of your conversion process and, for example,
29                                                      ' the event's category (e.Category).
30
31                                                      If severity > eventsSeverity Then
32                                                          eventsSeverity = severity
33                                                      End If
34
35                                                      ' Report conversion event
36                                                      Console.WriteLine("- {0} {1}: {2} ({3}{4})",
37                                                        severity.ToString()(0), e.Category, e.Message, e.Context, If(e.PageNo > 0, " page " & e.PageNo, "")
38                                                      )
39                                                  End Sub
40
41            ' Create stream for output file
42            Using outStr = File.Create(outPath)
43                ' Convert the input document to PDF/A using the converter object
44                ' and its conversion event handler
45                Using outDoc = converter.Convert(analysisResult, inDoc, outStr)
46                    ' Check if critical conversion events occurred
47                    Select Case eventsSeverity
48                        Case EventSeverity.Information
49                            Console.WriteLine($"Successfully converted document to {outDoc.Conformance}.")
50                        Case EventSeverity.Warning
51                            Console.WriteLine($"Warnings occurred during the conversion of document to {outDoc.Conformance}.")
52                            Console.WriteLine($"Check the output file to decide if the result is acceptable.")
53                        Case EventSeverity.Error
54                            Throw New Exception($"Unable to convert document to {conformance} because of critical conversion events.")
55                    End Select
56                End Using
57            End Using
58        End Using
59    End Using
60End Sub
Download code sample

Create a ZUGFeRD invoice

1void EventListener(void* pContext, const char* szDataPart, const char* szMessage,
2                   TPdfToolsPdfAConversion_EventSeverity iSeverity, TPdfToolsPdfAConversion_EventCategory iCategory,
3                   TPdfToolsPdfAConversion_EventCode iCode, const char* szContext, int iPageNo)
4{
5    // iSeverity is the event's suggested severity
6    // Optionally the suggested severity can be changed according to
7    // the requirements of your conversion process and, for example,
8    // the event's category (e.Category).
9
10    if (iSeverity > iEventsSeverity)
11        iEventsSeverity = iSeverity;
12
13    // Report conversion event
14    TCHAR cSeverity = iSeverity == ePdfToolsPdfAConversion_EventSeverity_Information ? 'I'
15                      : ePdfToolsPdfAConversion_EventSeverity_Warning                ? 'W'
16                                                                                     : 'E';
17    if (iPageNo > 0)
18        _tprintf(_T("- %c %d: %s (%s on page %d)\n"), cSeverity, iCategory, szMessage, szContext, iPageNo);
19    else
20        _tprintf(_T("- %c %d: %s (%s)\n"), cSeverity, iCategory, szMessage, szContext);
21}
1void AddZugferdInvoice(const TCHAR* szInPath, const TCHAR* szInvoicePath, const TCHAR* szOutPath)
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*                                      pInvoiceStream = NULL;
12    FILE*                                      pOutStream     = NULL;
13
14    // Open input document
15    pInStream = _tfopen(szInPath, _T("rb"));
16    GOTO_CLEANUP_IF_NULL_PRINT_ERROR(pInStream, _T("Failed to open the input file \"%s\" for reading.\n"), szInPath);
17    TPdfToolsSys_StreamDescriptor inDesc;
18    PdfToolsSysCreateFILEStreamDescriptor(&inDesc, pInStream, 0);
19    pInDoc = PdfToolsPdf_Document_Open(&inDesc, _T(""));
20    GOTO_CLEANUP_IF_NULL_PRINT_ERROR(pInDoc, _T("Failed to open document \"%s\". %s (ErrorCode: 0x%08x).\n"), szInPath,
21                                     szErrBuf, PdfTools_GetLastError());
22
23    // Create validator to analyze PDF/A standard conformance of input document
24    pAOpt = PdfToolsPdfAValidation_AnalysisOptions_New();
25    // The conformance has to be set to PDF/A-3 when adding the XML invoice file
26    PdfToolsPdfAValidation_AnalysisOptions_SetConformance(pAOpt, ePdfToolsPdf_Conformance_PdfA3U);
27    pValidator = PdfToolsPdfAValidation_Validator_New();
28    pARes      = PdfToolsPdfAValidation_Validator_Analyze(pValidator, pInDoc, pAOpt);
29    GOTO_CLEANUP_IF_NULL_PRINT_ERROR(pARes, _T("Failed to analyze document. %s (ErrorCode: 0x%08x).\n"), szErrBuf,
30                                     PdfTools_GetLastError());
31
32    // Create output stream for writing
33    pOutStream = _tfopen(szOutPath, _T("wb+"));
34    GOTO_CLEANUP_IF_NULL_PRINT_ERROR(pOutStream, _T("Failed to create the output file \"%s\".\n"), szOutPath);
35    TPdfToolsSys_StreamDescriptor outDesc;
36    PdfToolsSysCreateFILEStreamDescriptor(&outDesc, pOutStream, 0);
37
38    // Create a converter object and add a conversion event handler
39    pConvOpt = PdfToolsPdfAConversion_ConversionOptions_New();
40    pConv    = PdfToolsPdfAConversion_Converter_New();
41    PdfToolsPdfAConversion_Converter_AddConversionEventHandlerA(
42        pConv, NULL, (TPdfToolsPdfAConversion_Converter_ConversionEventA)EventListener);
43
44    // Create invoice stream for reading
45    pInvoiceStream = _tfopen(szInvoicePath, _T("rb"));
46    GOTO_CLEANUP_IF_NULL_PRINT_ERROR(pInvoiceStream, _T("Failed to open the invoice file \"%s\" for reading.\n"),
47                                     szInvoicePath);
48    TPdfToolsSys_StreamDescriptor invoiceDesc;
49    PdfToolsSysCreateFILEStreamDescriptor(&invoiceDesc, pInvoiceStream, 0);
50    // Add invoice XML file
51    PdfToolsPdfAConversion_Converter_AddInvoiceXml(pConv, ePdfToolsPdfAConversion_InvoiceType_Zugferd, &invoiceDesc,
52                                                   NULL);
53    // Convert the input document to PDF/A-3U
54    pOutDoc = PdfToolsPdfAConversion_Converter_Convert(pConv, pARes, pInDoc, &outDesc, pConvOpt, NULL);
55    GOTO_CLEANUP_IF_NULL_PRINT_ERROR(pOutDoc, _T("Failed to convert document. %s (ErrorCode: 0x%08x).\n"), szErrBuf,
56                                     PdfTools_GetLastError());
57
58    // Check if critical conversion events occurred
59    switch (iEventsSeverity)
60    {
61    case ePdfToolsPdfAConversion_EventSeverity_Information:
62    {
63        TPdfToolsPdf_Conformance iOutConf;
64        PdfToolsPdf_Document_GetConformance(pOutDoc, &iOutConf);
65        printf("Successfully converted document to %s.\n", PdfToolsPdf_Conformance_ToStringA(iOutConf));
66        break;
67    }
68
69    case ePdfToolsPdfAConversion_EventSeverity_Warning:
70    {
71        TPdfToolsPdf_Conformance iOutConf;
72        PdfToolsPdf_Document_GetConformance(pOutDoc, &iOutConf);
73        printf("Warnings occurred during the conversion of document to %s.\n",
74               PdfToolsPdf_Conformance_ToStringA(iOutConf));
75        printf("Check the output file to decide if the result is acceptable.\n");
76        break;
77    }
78
79    case ePdfToolsPdfAConversion_EventSeverity_Error:
80    {
81        printf("Unable to convert document to PDF/A-3U because of critical conversion events.\n");
82        break;
83    }
84    }
85
86cleanup:
87    PdfToolsPdf_Document_Close(pOutDoc);
88    PdfTools_Release(pConv);
89    PdfTools_Release(pConvOpt);
90    PdfTools_Release(pARes);
91    PdfTools_Release(pValidator);
92    PdfTools_Release(pAOpt);
93    PdfToolsPdf_Document_Close(pInDoc);
94    if (pInStream)
95        fclose(pInStream);
96    if (pOutStream)
97        fclose(pOutStream);
98    if (pInvoiceStream)
99        fclose(pInvoiceStream);
100}
Download code sample
1static void AddZugferdInvoice(string inPath, string invoicePath, 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 Validator object, and use the Conformance object to create
8    // an AnalysisOptions object that controls the behavior of the Validator.
9    var validator = new Validator();
10    // The conformance has to be set to PDF/A-3 when adding the XML invoice file
11    var analysisOptions = new AnalysisOptions() { Conformance = new Conformance(3, Conformance.PdfALevel.U) };
12
13    // Run the analysis
14    var analysisResult = validator.Analyze(inDoc, analysisOptions);
15
16    // Create a converter object
17    var converter = new Converter();
18
19    // Add invoice XML file
20    using var invoiceStr = File.OpenRead(invoicePath);
21    converter.AddInvoiceXml(InvoiceType.Zugferd, invoiceStr);
22
23    // Add handler for conversion events
24    var eventsSeverity = EventSeverity.Information;
25    converter.ConversionEvent += (s, e) =>
26    {
27        // Get the event's suggested severity
28        var severity = e.Severity;
29
30        // Optionally the suggested severity can be changed according to
31        // the requirements of your conversion process and, for example,
32        // the event's category (e.Category).
33
34        if (severity > eventsSeverity)
35            eventsSeverity = severity;
36
37        // Report conversion event
38        Console.WriteLine("- {0} {1}: {2} ({3}{4})",
39            severity.ToString()[0], e.Category, e.Message, e.Context, e.PageNo > 0 ? " page " + e.PageNo : ""
40        );
41    };
42
43    // Create stream for output file
44    using var outStr = File.Create(outPath);
45
46    // Convert the input document to PDF/A using the converter object
47    // and its conversion event handler
48    using var outDoc = converter.Convert(analysisResult, inDoc, outStr);
49
50    // Check if critical conversion events occurred
51    switch (eventsSeverity)
52    {
53        case EventSeverity.Information:
54            Console.WriteLine($"Successfully converted document to {outDoc.Conformance}.");
55            break;
56
57        case EventSeverity.Warning:
58            Console.WriteLine($"Warnings occurred during the conversion of document to {outDoc.Conformance}.");
59            Console.WriteLine($"Check the output file to decide if the result is acceptable.");
60            break;
61
62        case EventSeverity.Error:
63            throw new Exception($"Unable to convert document to PDF/A-3U because of critical conversion events.");
64    }
65}
Download code sample
1    private static void addZugferdInvoice(String inPath, String invoicePath, String outPath) 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 the Validator object, and use the Conformance object to create
8            // an AnalysisOptions object that controls the behavior of the Validator.
9            Validator validator = new Validator();
10            AnalysisOptions analysisOptions = new AnalysisOptions();
11            // The conformance has to be set to PDF/A-3 when adding the XML invoice file
12            analysisOptions.setConformance(new Conformance(new Conformance.PdfAVersion(3, Conformance.PdfAVersion.Level.U)));
13
14            // Run the analysis
15            AnalysisResult analysisResult = validator.analyze(inDoc, analysisOptions);
16
17            // Create output stream
18            try (FileStream outStr = new FileStream(outPath, FileStream.Mode.READ_WRITE_NEW))
19            {
20                // Create a converter object
21                Converter converter = new Converter();
22
23                // Add invoice XML file
24                try (FileStream invoiceStr = new FileStream(invoicePath, FileStream.Mode.READ_ONLY))
25                {
26	                converter.addInvoiceXml(InvoiceType.ZUGFERD, invoiceStr);
27
28	                // Add handler for conversion events
29	                class EventListener implements ConversionEventListener
30	                {
31	                    private EventSeverity eventsSeverity = EventSeverity.INFORMATION;
32
33	                    public EventSeverity getEventsSeverity() {
34	                        return eventsSeverity;
35	                    }
36
37	                    @Override
38	                    public void conversionEvent(ConversionEvent event) {
39	                        // Get the event's suggested severity
40	                        EventSeverity severity = event.getSeverity();
41
42	                        // Optionally the suggested severity can be changed according to
43	                        // the requirements of your conversion process and, for example,
44	                        // the event's category (e.Category).
45
46	                        if (severity.ordinal() > eventsSeverity.ordinal())
47	                            eventsSeverity = severity;
48
49	                        // Report conversion event
50	                        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() : "");
51	                    }
52	                }
53	                EventListener el = new EventListener();
54
55	                converter.addConversionEventListener(el);
56
57	                // Convert the input document to PDF/A using the converter object
58	                // and its conversion event handler
59	                try (Document outDoc = converter.convert(analysisResult, inDoc, outStr))
60	                {
61	                    // Check if critical conversion events occurred
62	                    switch (el.getEventsSeverity())
63	                    {
64	                        case INFORMATION:
65	                            System.out.println("Successfully converted document to " + outDoc.getConformance() + ".");
66	                            break;
67
68	                        case WARNING:
69	                            System.out.println("Warnings occurred during the conversion of document to " + outDoc.getConformance() + ".");
70	                            System.out.println("Check the output file to decide if the result is acceptable.");
71	                            break;
72
73	                        case ERROR:
74	                            throw new Exception("Unable to convert document to PDF/A-3U because of critical conversion events.");
75	                    }
76	                }
77                }
78            }
79        }
80    }
Download code sample
1def add_zugferd_invoice(input_path: str, zugferd_xml_path: str, output_path: str):
2    # Open input document
3    with io.FileIO(input_path, 'rb') as input_stream:
4        with Document.open(input_stream) as input_document:
5            # Create the Validator object, and use the Conformance object to create
6            # an AnalysisOptions object that controls the behavior of the Validator.
7            validator = Validator()
8            # The conformance has to be set to PDF/A-3 when adding the XML invoice file
9            analysis_options = AnalysisOptions()
10            analysis_options.conformance = Conformance.PDF_A3_U
11
12            # Run the analysis
13            analysis_result = validator.analyze(input_document, analysis_options)
14
15            # Create a converter object
16            converter = Converter()
17
18            # Add the invoice XML file
19            with io.FileIO(zugferd_xml_path, 'rb') as invoice_stream:
20                converter.add_invoice_xml(InvoiceType.ZUGFERD, invoice_stream)
21
22                # Add handler for conversion events
23                event_severity_holder = [EventSeverity.INFORMATION]
24                converter.add_conversion_event_handler(lambda *args: handle_conversion_event(*args, event_severity_holder))
25
26                # Create output file
27                with io.FileIO(output_path, 'wb+') as output_stream:
28                    # Convert the input document to PDF/A
29                    with converter.convert(analysis_result, input_document, output_stream) as output_document:
30                        if event_severity_holder[0] == EventSeverity.INFORMATION:
31                            print(f"Successfully converted document to {output_document.conformance.name}.")
32                        elif event_severity_holder[0] == EventSeverity.WARNING:
33                            print(f"Warnings occurred during the conversion to {output_document.conformance}.")
34                            print("Check the output file to decide if the result is acceptable.")
35                        elif event_severity_holder[0] == EventSeverity.ERROR:
36                            raise Exception(f"Unable to convert document to PDF/A-3U because of critical conversion events.")
1def handle_conversion_event(data_part: str, message: str, severity: EventSeverity, category: EventCategory, code: EventCode, context: str, page_no: int, event_severity_holder: list[EventSeverity]):
2    # Optionally the suggested severity can be changed according to
3    # the requirements of your conversion process and, for example,
4    # the event's category (e.Category).
5
6    if severity > event_severity_holder[0]:
7        event_severity_holder[0] = severity
8
9    print(f"- {severity.name} {category.name}: {message} ({context}{f' on page {page_no}' if page_no > 0 else ''})")
Download code sample
1Sub AddZugferdInvoice(inPath As String, invoicePath As String, outPath As String)
2    ' Open input document
3    Using inStr = File.OpenRead(inPath)
4        Using inDoc = Document.Open(inStr)
5
6            ' Create the Validator object, and use the Conformance object to create
7            ' an AnalysisOptions object that controls the behavior of the Validator.
8            Dim validator = New Validator()
9            ' The conformance has to be set to PDF/A-3 when adding the XML invoice file
10            Dim analysisOptions = New AnalysisOptions() With {.Conformance = New Conformance(3, Conformance.PdfALevel.U)}
11
12            ' Run the analysis
13            Dim analysisResult = validator.Analyze(inDoc, analysisOptions)
14
15            ' Create a converter object
16            Dim converter = New Converter()
17
18            ' Add invoice XML file
19            Using invoiceStr = File.OpenRead(invoicePath)
20                converter.AddInvoiceXml(InvoiceType.Zugferd, invoiceStr)
21
22                ' Add handler for conversion events
23                Dim eventsSeverity = EventSeverity.Information
24                AddHandler converter.ConversionEvent, Sub(s, e)
25                                                          ' Get the event's suggested severity
26                                                          Dim severity = e.Severity
27
28                                                          ' Optionally the suggested severity can be changed according to
29                                                          ' the requirements of your conversion process and, for example,
30                                                          ' the event's category (e.Category).
31
32                                                          If severity > eventsSeverity Then
33                                                              eventsSeverity = severity
34                                                          End If
35
36                                                          ' Report conversion event
37                                                          Console.WriteLine("- {0} {1}: {2} ({3}{4})", severity.ToString()(0), e.Category, e.Message, e.Context, If(e.PageNo > 0, " page " & e.PageNo, ""))
38                                                      End Sub
39
40                ' Create stream for output file
41                Using outStr = File.Create(outPath)
42
43                    ' Convert the input document to PDF/A using the converter object
44                    ' and its conversion event handler
45                    Using outDoc = converter.Convert(analysisResult, inDoc, outStr)
46
47                        ' Check if critical conversion events occurred
48                        Select Case eventsSeverity
49                            Case EventSeverity.Information
50                                Console.WriteLine($"Successfully converted document to {outDoc.Conformance}.")
51                            Case EventSeverity.Warning
52                                Console.WriteLine($"Warnings occurred during the conversion of document to {outDoc.Conformance}.")
53                                Console.WriteLine($"Check the output file to decide if the result is acceptable.")
54                            Case EventSeverity.Error
55                                Throw New Exception($"Unable to convert document to PDF/A-3U because of critical conversion events.")
56                        End Select
57                    End Using
58                End Using
59            End Using
60        End Using
61    End Using
62End Sub
Download code sample

Converting documents to rasterized images

Convert PDF to image

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(
8    pInDoc, _T("Failed to create a document from the input file \"%s\". %s (ErrorCode: 0x%08x).\n"), szInPath,
9    szErrorBuff, PdfTools_GetLastError());
10
11// Create output stream for writing
12pOutStream = _tfopen(szOutPath, _T("wb+"));
13GOTO_CLEANUP_IF_NULL_PRINT_ERROR(pOutStream, _T("Failed to open the output file \"%s\" for writing.\n"), szOutPath);
14TPdfToolsSys_StreamDescriptor outDesc;
15PdfToolsSysCreateFILEStreamDescriptor(&outDesc, pOutStream, 0);
16
17// Create the profile that defines the conversion parameters.
18// The Archive profile converts PDF documents to TIFF images for archiving.
19pProfile = (TPdfToolsPdf2ImageProfiles_Profile*)PdfToolsPdf2ImageProfiles_Archive_New();
20
21// Optionally the profile's parameters can be changed according to the
22// requirements of your conversion process.
23
24// Convert the PDF document to an image document
25pConverter = PdfToolsPdf2Image_Converter_New();
26pOutDoc =
27    (TPdfToolsImage_Document*)PdfToolsPdf2Image_Converter_ConvertDocument(pConverter, pInDoc, &outDesc, pProfile);
28GOTO_CLEANUP_IF_NULL_PRINT_ERROR(pOutDoc, _T("The processing has failed. (ErrorCode: 0x%08x).\n"),
29                                 PdfTools_GetLastError());
30
Download code sample
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}
Download code sample
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}
Download code sample
1
2
3pdf_to_image(args.input_path, args.output_path)
4
1def pdf_to_image(input_pdf_path: str, output_image_path: str):
2    # Open input document
3    with io.FileIO(input_pdf_path, 'rb') as input_pdf_stream:
4        with Document.open(input_pdf_stream) as input_pdf_document:
5            # Create the profile that defines the conversion parameters.
6            # The Archive profile converts PDF documents to TIFF images for archiving.
7            profile = Archive()
8
9            # Optionally the profile's parameters can be changed according to the 
10            # requirements of your conversion process.
11
12            # Create output stream
13            with io.FileIO(output_image_path, 'wb+') as output_stream:
14                # Convert the PDF document to an image document
15                converter = Converter()
16                converter.convert_document(input_pdf_document, output_stream, profile)
Download code sample
1Private Sub Pdf2Image(inPath As String, outPath As String)
2    ' Open input document
3    Using inStr = File.OpenRead(inPath)
4        Using inDoc = Document.Open(inStr)
5
6            ' Create the profile that defines the conversion parameters.
7            ' The Archive profile converts PDF documents to TIFF images for archiving.
8            Dim profile = New Profiles.Archive()
9
10            ' Optionally the profile's parameters can be changed according to the 
11            ' requirements of your conversion process.
12
13            ' Create output stream
14            Using outStr = File.Create(outPath)
15
16                ' Convert the PDF document to an image document
17                Using outDoc = New Converter().ConvertDocument(inDoc, outStr, profile)
18                End Using
19            End Using
20        End Using
21    End Using
22End Sub
Download code sample

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}
Download code sample
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}
Download code sample
1
2
3image_to_pdf(args.input_path, args.alternate_text, args.output_path)
4
1def image_to_pdf(input_path: str, alternate_text: str, output_path: str):
2    # Open image document
3    with io.FileIO(input_path, 'rb') as image_stream:
4        with Document.open(image_stream) as image_document:
5            # Create the profile that defines the conversion parameters.
6            # The Archive profile converts images to PDF/A documents for archiving.
7            profile = Archive()
8
9            # Set conformance of output document to PDF/A-2a
10            profile.conformance = Conformance.PDF_A2_A
11
12            # For PDF/A level A, an alternate text is required for each page of the image.
13            # This is optional for other PDF/A levels, e.g. PDF/A-2b.
14            profile.language = "en"
15            profile.alternate_text.append(alternate_text)
16
17            # Optionally other profile parameters can be changed according to the 
18            # requirements of your conversion process.
19
20            # Create output stream
21            with io.FileIO(output_path, 'wb+') as output_stream:
22                # Convert the image to a tagged PDF/A document
23                converter = Converter()
24                converter.convert(image_document, output_stream, profile)
Download code sample
1Private Sub Image2Pdf(inPath As String, alternateText As String, outPath As String)
2    ' Open image document
3    Using inStr = File.OpenRead(inPath)
4        Using inDoc = Document.Open(inStr)
5
6            ' Create the profile that defines the conversion parameters.
7            ' The Archive profile converts images to PDF/A documents for archiving.
8            Dim profile = New Profiles.Archive()
9
10            ' Set conformance of output document to PDF/A-2a
11            profile.Conformance = New Conformance(2, Conformance.PdfALevel.A)
12
13            ' For PDF/A level A, an alternate text is required for each page of the image.
14            ' This is optional for other PDF/A levels, e.g. PDF/A-2b.
15            profile.Language = "en"
16            profile.AlternateText.Add(alternateText)
17
18            ' Optionally other profile parameters can be changed according to the 
19            ' requirements of your conversion process.
20
21            ' Create output stream
22            Using outStr = File.Create(outPath)
23
24                ' Convert the image to a tagged PDF/A document
25                Using outDoc = New Converter().Convert(inDoc, outStr, profile)
26                End Using
27            End Using
28        End Using
29    End Using
30End Sub
Download code sample

Convert image to PDF

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 = PdfToolsImage_Document_Open(&inDesc);
7GOTO_CLEANUP_IF_NULL_PRINT_ERROR(
8    pInDoc, _T("Failed to create a document from the input file \"%s\". %s (ErrorCode: 0x%08x).\n"), szInPath,
9    szErrorBuff, PdfTools_GetLastError());
10
11// Create output stream for writing
12pOutStream = _tfopen(szOutPath, _T("wb+"));
13GOTO_CLEANUP_IF_NULL_PRINT_ERROR(pOutStream, _T("Failed to open the output file \"%s\" for writing.\n"), szOutPath);
14TPdfToolsSys_StreamDescriptor outDesc;
15PdfToolsSysCreateFILEStreamDescriptor(&outDesc, pOutStream, 0);
16
17// Create the profile that defines the conversion parameters.
18// The Default profile converts images to PDF documents.
19pProfile = (TPdfToolsImage2PdfProfiles_Profile*)PdfToolsImage2PdfProfiles_Default_New();
20
21// Convert the image to a PDF document
22pConverter = PdfToolsImage2Pdf_Converter_New();
23pOutDoc = (TPdfToolsPdf_Document*)PdfToolsImage2Pdf_Converter_Convert(pConverter, pInDoc, &outDesc, pProfile, NULL);
24GOTO_CLEANUP_IF_NULL_PRINT_ERROR(pOutDoc, _T("The processing has failed. (ErrorCode: 0x%08x).\n"),
25                                 PdfTools_GetLastError());
26
Download code sample
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}
Download code sample
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}
Download code sample
1
2
3convert_image_to_pdf(args.input_path, args.output_path)
4
1def convert_image_to_pdf(input_path: str, output_path: str):
2    # Open image document
3    with io.FileIO(input_path, 'rb') as in_stream:
4        with Document.open(in_stream) as input_document:
5
6            # Create the profile that defines the conversion parameters (Default profile)
7            profile = Default()
8
9            # Optionally, you can adjust the profile's parameters if needed
10
11            # Create output stream
12            with io.FileIO(output_path, 'wb+') as output_stream:
13
14                # Convert the image to a PDF document
15                converter = Converter()
16                converter.convert(input_document, output_stream, profile)
Download code sample
1Private Sub Image2Pdf(inPath As String, outPath As String)
2    ' Open image document
3    Using inStr = File.OpenRead(inPath)
4        Using inDoc = Document.Open(inStr)
5
6            ' Create the profile that defines the conversion parameters.
7            ' The Default profile converts images to PDF documents.
8            Dim profile = New Profiles.Default()
9
10            ' Optionally, the profile's parameters can be changed according to the 
11            ' requirements of your conversion process.
12
13            ' Create output stream
14            Using outStr = File.Create(outPath)
15
16                ' Convert the image to a PDF document
17                Using outDoc = New Converter().Convert(inDoc, outStr, profile)
18                End Using
19            End Using
20        End Using
21    End Using
22End Sub
Download code sample

Convert multiple images to a PDF

1private static void Images2Pdf(IEnumerable<string> inPaths, string outPath)
2{
3    var streams = new List<FileStream>();
4    var images = new DocumentList();
5    try
6    {
7        // Open input images and store in list
8        foreach (var inPath in inPaths)
9        {
10            var stream = File.OpenRead(inPath);
11            streams.Add(stream);
12            images.Add(Document.Open(stream));
13        }
14
15        // Create the profile that defines the conversion parameters.
16        var profile = new Profiles.Default();
17
18        // Optionally the profile's parameters can be changed according to the 
19        // requirements of your conversion process.
20
21        // Create output stream
22        using var outStream = File.Create(outPath);
23        using var outPdf = new Converter().ConvertMultiple(images, outStream, profile);
24    }
25    finally
26    {
27        foreach (var image in images)
28            image.Dispose();
29        foreach (var stream in streams)
30            stream.Dispose();
31    }
32}
Download code sample
1private static void Images2Pdf(String[] inPaths, String outPath) throws Exception
2{
3    // Create the profile that defines the conversion parameters.
4    Default profile = new Default();
5
6    List<FileStream> streams = new ArrayList<>();
7    DocumentList images = new DocumentList();
8
9    // Optionally the profile's parameters can be changed according to the 
10    // requirements of your conversion process.
11    try {
12        // Open input documents
13        for (String inPath : inPaths) {
14            FileStream stream = new FileStream(inPath, FileStream.Mode.READ_ONLY);
15            streams.add(stream);
16            images.add(Document.open(stream));
17        }
18
19        try (
20            // Create output stream
21            FileStream outStream = new FileStream(outPath, FileStream.Mode.READ_WRITE_NEW);
22            // Convert the image to a PDF document
23            com.pdftools.pdf.Document outDoc = new Converter().convertMultiple(images, outStream, profile)) {
24            }
25    }
26    finally {
27        for (Document image : images) 
28            image.close();
29        for (FileStream stream : streams)
30            stream.close();
31    }
32}
Download code sample
1
2
3images_to_pdf(args.input_path, args.output_path)
4
1def images_to_pdf(input_image_paths: list[str], output_file_path: str):
2    try:
3        stream_list = []
4        images = ImageDocumentList()
5
6        # Open input images and store in list
7        for input_image_path in input_image_paths:
8            image_stream = io.FileIO(input_image_path, 'rb')
9            stream_list.append(image_stream)
10            images.append(ImageDocument.open(image_stream))
11
12        # Create the profile that defines the conversion parameters.
13        profile = Default()
14
15        # Optionally the profile's parameters can be changed according to the 
16        # requirements of your conversion process.
17
18        # Create output stream
19        with io.FileIO(output_file_path, 'wb+') as output_stream:
20            converter = Converter()
21            converter.convert_multiple(images, output_stream, profile)
22    finally:
23        if 'images' in locals():
24            for image in images:
25                image.__exit__(None, None, None)
26        if 'stream_list' in locals(): 
27            for stream in stream_list:
28                stream.__exit__(None, None, None)
Download code sample
1Private Sub Images2Pdf(inPaths As IEnumerable(Of String), outPath As String)
2    Dim streams = New List(Of FileStream)()
3    Dim images = New DocumentList()
4    Try
5        ' Open input images and store in list
6        For Each inPath In inPaths
7            Dim stream = File.OpenRead(inPath)
8            streams.Add(stream)
9            images.Add(Document.Open(stream))
10        Next
11
12        ' Create the profile that defines the conversion parameters.
13        Dim profile = New Profiles.Default()
14
15        ' Optionally the profile's parameters can be changed according to the 
16        ' requirements of your conversion process.
17        ' Create output stream
18        Using outStream = File.Create(outPath)
19            Using outPdf = New Converter().ConvertMultiple(images, outStream, profile)
20            End Using
21        End Using
22    Finally
23        For Each item In images
24            item.Dispose()
25        Next
26        For Each stream In streams
27            stream.Dispose()
28        Next
29    End Try
30End Sub
Download code sample

Encrypt documents

Decrypt an encrypted PDF

1// Use password to open encrypted 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, szPassword);
7GOTO_CLEANUP_IF_NULL_PRINT_ERROR(
8    pInDoc, _T("Failed to create a document from the input file \"%s\". %s (ErrorCode: 0x%08x).\n"), szInPath,
9    szErrorBuff, PdfTools_GetLastError());
10
11// Create output stream for writing
12pOutStream = _tfopen(szOutPath, _T("wb+"));
13GOTO_CLEANUP_IF_NULL_PRINT_ERROR(pOutStream, _T("Failed to open the output file \"%s\" for writing.\n"), szOutPath);
14TPdfToolsSys_StreamDescriptor outDesc;
15PdfToolsSysCreateFILEStreamDescriptor(&outDesc, pOutStream, 0);
16
17// Check if input file is encrypted
18BOOL bIsGetPermissionsSuccessful = PdfToolsPdf_Document_GetPermissions(pInDoc, &iPermissions);
19if (!bIsGetPermissionsSuccessful)
20{
21    if (PdfTools_GetLastError() == 0)
22    {
23        _tprintf(_T("Validation failed, input file \"%s\" is not encrypted.\n"), szInPath);
24        iRet = 1;
25        goto cleanup;
26    }
27    else
28    {
29        nBufSize = PdfTools_GetLastErrorMessage(NULL, 0);
30        PdfTools_GetLastErrorMessage(szErrorBuff, MIN(ARRAY_SIZE(szErrorBuff), nBufSize));
31        _tprintf(_T("Failed to get permissions for input file \"%s\", error %s \n"), szInPath, szErrorBuff);
32        iRet = 1;
33        goto cleanup;
34    }
35}
36
37// Set encryption options
38pOptions = PdfToolsSign_OutputOptions_New();
39
40// Set encryption parameters to no encryption
41PdfToolsPdf_OutputOptions_SetEncryption((TPdfToolsPdf_OutputOptions*)pOptions, NULL);
42
43// Allow removal of signatures. Otherwise the Encryption property is ignored for signed input documents
44// (see warning category Sign.WarningCategory.SignedDocEncryptionUnchanged).
45PdfToolsSign_OutputOptions_SetRemoveSignatures(pOptions, ePdfToolsSign_SignatureRemoval_Signed);
46
47// Decrypt the document
48pSigner = PdfToolsSign_Signer_New();
49pOutDoc = PdfToolsSign_Signer_Process(pSigner, pInDoc, &outDesc, pOptions, NULL);
50GOTO_CLEANUP_IF_NULL_PRINT_ERROR(pOutDoc, _T("The processing has failed. (ErrorCode: 0x%08x).\n"),
51                                 PdfTools_GetLastError());
52
53
Download code sample
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}
Download code sample
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}
Download code sample
1
2
3# Decrypt a PDF document
4decrypt(args.password, args.input_path, args.output_path)
5
1def decrypt(password: str, input_path: str, output_path: str):
2    # Use password to open encrypted input document
3    with io.FileIO(input_path, 'rb') as in_stream:
4        with Document.open(in_stream, password) as input_document:
5            if input_document.permissions == None:
6                print(f"Input file is not encrypted.")
7                return
8
9            # Create stream for output file
10            with io.FileIO(output_path, 'wb+') as output_stream:
11                # Set encryption options
12                output_options = SignOutputOptions()
13                # Set encryption parameters to no encryption
14                output_options.encryption = None
15                # Allow removal of signatures. Otherwise the Encryption property is ignored for signed input documents
16                # (see warning category Sign.WarningCategory.SignedDocEncryptionUnchanged).
17                output_options.remove_signatures = SignatureRemoval.SIGNED
18
19                # Decrypt the document
20                signer = Signer()
21                signer.process(input_document, output_stream, output_options)
Download code sample
1Sub Decrypt(password As String, inPath As String, outPath As String)
2    ' Use password to open encrypted input document
3    Using inStr = File.OpenRead(inPath)
4        Using inDoc = Document.Open(inStr, password)
5
6            If inDoc.Permissions Is Nothing Then
7                Throw New Exception("Input file is not encrypted.")
8            End If
9
10            ' Create stream for output file
11            Using outStr = File.Create(outPath)
12
13                ' Set encryption options
14                Dim outputOptions = New Sign.OutputOptions() With {
15                    .Encryption = Nothing,
16                    .RemoveSignatures = Sign.SignatureRemoval.Signed
17                }
18
19                ' Decrypt the document
20                Using outDoc = New Sign.Signer().Process(inDoc, outStr, outputOptions)
21                End Using
22            End Using
23        End Using
24    End Using
25End Sub
Download code sample

Encrypt a PDF

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(
8    pInDoc, _T("Failed to create a document from the input file \"%s\". %s (ErrorCode: 0x%08x).\n"), szInPath,
9    szErrorBuff, PdfTools_GetLastError());
10
11// Create output stream for writing
12pOutStream = _tfopen(szOutPath, _T("wb+"));
13GOTO_CLEANUP_IF_NULL_PRINT_ERROR(pOutStream, _T("Failed to open the output file \"%s\" for writing.\n"), szOutPath);
14TPdfToolsSys_StreamDescriptor outDesc;
15PdfToolsSysCreateFILEStreamDescriptor(&outDesc, pOutStream, 0);
16
17// Set encryption options
18pOptions = PdfToolsSign_OutputOptions_New();
19
20// Set a user password that will be required to open the document.
21// Note that this will remove PDF/A conformance of input files (see warning category
22// ePdfToolsSign_WarningCategory_PdfARemoved)
23pEncryption = PdfToolsPdf_Encryption_New(szPassword, NULL, ePdfToolsPdf_Permission_All);
24PdfToolsPdf_OutputOptions_SetEncryption((TPdfToolsPdf_OutputOptions*)pOptions, pEncryption);
25
26// Allow removal of signatures. Otherwise the Encryption property is ignored for signed input documents
27// (see warning category ePdfToolsSign_WarningCategory_SignedDocEncryptionUnchanged).
28PdfToolsSign_OutputOptions_SetRemoveSignatures(pOptions, ePdfToolsSign_SignatureRemoval_Signed);
29
30// Encrypt the document
31pSigner = PdfToolsSign_Signer_New();
32pOutDoc = PdfToolsSign_Signer_Process(pSigner, pInDoc, &outDesc, pOptions, NULL);
33GOTO_CLEANUP_IF_NULL_PRINT_ERROR(pOutDoc, _T("The processing has failed. (ErrorCode: 0x%08x).\n"),
34                                 PdfTools_GetLastError());
35
36
Download code sample
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}
Download code sample
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}
Download code sample
1
2
3# Encrypt a PDF document
4encrypt(args.password, args.input_path, args.output_path)
5
1def encrypt(password: str, input_path: str, output_path: str):
2    # Open input document
3    with io.FileIO(input_path, 'rb') as in_stream:
4        with Document.open(in_stream) as input_document:
5            # Create stream for output file
6            with io.FileIO(output_path, 'wb+') as output_stream:
7                # Set encryption options
8                output_options = SignOutputOptions()
9                # Set a user password that will be required to open the document.
10                # Note that this will remove PDF/A conformance of input files (see warning category Sign.WarningCategory.PdfARemoved)
11                output_options.encryption = Encryption(password, None, Permission.ALL)
12                # Allow removal of signatures. Otherwise the Encryption property is ignored for signed input documents
13                # (see warning category Sign.WarningCategory.SignedDocEncryptionUnchanged).
14                output_options.remove_signatures = SignatureRemoval.SIGNED
15
16                # Encrypt the document
17                signer = Signer()
18                signer.process(input_document, output_stream, output_options)
Download code sample
1Sub Encrypt(password As String, inPath As String, outPath As String)
2    ' Open input document
3    Using inStr = File.OpenRead(inPath)
4        Using inDoc = Document.Open(inStr)
5
6            ' Create stream for output file
7            Using outStr = File.Create(outPath)
8
9                ' Set encryption options
10                Dim outputOptions = New Sign.OutputOptions() With {
11                    .Encryption = New Encryption(password, Nothing, Permission.All),
12                    .RemoveSignatures = Sign.SignatureRemoval.Signed
13                }
14
15                ' Encrypt the document
16                Using outDoc = New Sign.Signer().Process(inDoc, outStr, outputOptions)
17                End Using
18            End Using
19        End Using
20    End Using
21End Sub
Download code sample

Getting started

Hello, Pdftools SDK!

1// 1. Open input image document using memory stream
2pCoverImageStream = _tfopen(szCoverImagePath, _T("rb"));
3GOTO_CLEANUP_IF_NULL_PRINT_ERROR(pCoverImageStream, _T("Failed to open the input file \"%s\" for reading.\n"),
4                                 szCoverImagePath);
5PdfToolsSysCreateFILEStreamDescriptor(&inImageDesc, pCoverImageStream, 0);
6pCoverImageDoc = PdfToolsImage_Document_Open(&inImageDesc);
7GOTO_CLEANUP_IF_NULL_PRINT_ERROR(
8    pCoverImageDoc, _T("Failed to create a document from the input file \"%s\". %s (ErrorCode: 0x%08x).\n"),
9    szCoverImagePath, szErrorBuff, PdfTools_GetLastError());
10
11// 2. Create output stream in memory for the cover page (image as PDF)
12PdfToolsSys_MemoryStreamDescriptor_Create(&outImageDesc);
13pProfile        = (TPdfToolsImage2PdfProfiles_Profile*)PdfToolsImage2PdfProfiles_Default_New();
14pConverter      = PdfToolsImage2Pdf_Converter_New();
15pOutCoverPdfDoc = (TPdfToolsPdf_Document*)PdfToolsImage2Pdf_Converter_Convert(pConverter, pCoverImageDoc,
16                                                                              &outImageDesc, pProfile, NULL);
17GOTO_CLEANUP_IF_NULL_PRINT_ERROR(
18    pOutCoverPdfDoc, "The processing 'Image to PDF' has failed. (ErrorCode: 0x%08x).\n", PdfTools_GetLastError());
19
20// 3. Open input content document in-memory
21pInputPdfStream = _tfopen(szInContentPath, _T("rb"));
22GOTO_CLEANUP_IF_NULL_PRINT_ERROR(pInputPdfStream, _T("Failed to open the input file \"%s\" for reading.\n"),
23                                 szInContentPath);
24PdfToolsSysCreateFILEStreamDescriptor(&inContentDesc, pInputPdfStream, 0);
25pInContentDoc = PdfToolsPdf_Document_Open(&inContentDesc, _T(""));
26GOTO_CLEANUP_IF_NULL_PRINT_ERROR(
27    pInContentDoc, _T("Failed to create a document from the input file \"%s\". %s (ErrorCode: 0x%08x).\n"),
28    szInContentPath, szErrorBuff, PdfTools_GetLastError());
29
30// 4. Create final output document in-memory
31pOutFinalStream = _tfopen(szOutFinalPath, _T("wb+"));
32GOTO_CLEANUP_IF_NULL_PRINT_ERROR(pOutFinalStream, _T("Failed to create output file \"%s\" for writing.\n"),
33                                 szOutFinalPath);
34PdfToolsSysCreateFILEStreamDescriptor(&outFinalDesc, pOutFinalStream, 0);
35pAssembler = PdfToolsDocumentAssembly_DocumentAssembler_New(&outFinalDesc, NULL, NULL);
36
37// Define first and last page (only one page for the cover)
38int firstPage = 1;
39int lastPage  = 1;
40// 5. Append the first page of the image document to the final output
41GOTO_CLEANUP_IF_FALSE_PRINT_ERROR(PdfToolsDocumentAssembly_DocumentAssembler_Append(
42                                      pAssembler, pOutCoverPdfDoc, &firstPage, &lastPage, NULL, NULL),
43                                  "Failed to append the image document. (ErrorCode: 0x%08x).\n",
44                                  PdfTools_GetLastError());
45
46// 6. Append content document to the final output
47GOTO_CLEANUP_IF_FALSE_PRINT_ERROR(
48    PdfToolsDocumentAssembly_DocumentAssembler_Append(pAssembler, pInContentDoc, NULL, NULL, NULL, NULL),
49    "Failed to append the content document. (ErrorCode: 0x%08x).\n", PdfTools_GetLastError());
50
51// 7. Merge input documents into an output document
52pOutFinalDoc = PdfToolsDocumentAssembly_DocumentAssembler_Assemble(pAssembler);
53GOTO_CLEANUP_IF_NULL_PRINT_ERROR(
54    pOutFinalDoc,
55    "The processing of merging the first page with the PDF content has failed. (ErrorCode: 0x%08x).\n",
56    PdfTools_GetLastError());
57
Download code sample
1private static void Image2Pdf(string inPath, MemoryStream imageStream)
2{
3    // Open image document
4    using var inStr = File.OpenRead(inPath);
5    using var inDoc = PdfTools.Image.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    // Convert the image to a PDF document
15    var outDoc = new Converter().Convert(inDoc, imageStream, profile);
16}
1private static void Merge(MemoryStream coverStream, FileStream inputContentStream, string outPath)
2{
3    // Create output stream
4    using var outStream = File.Create(outPath);
5    using var docAssembler = new PdfTools.DocumentAssembly.DocumentAssembler(outStream);
6
7    docAssembler.Append(PdfTools.Pdf.Document.Open(coverStream), 1, 1);
8    docAssembler.Append(PdfTools.Pdf.Document.Open(inputContentStream));
9
10    // Merge input documents into an output document
11    docAssembler.Assemble();
12}
Download code sample
1private static void image2Pdf(String inPath, MemoryStream imageStream) throws Exception {
2    // Create the profile that defines the conversion parameters.
3    Default profile = new Default();
4
5    try (
6        // Open input document
7        FileStream inStr = new FileStream(inPath, FileStream.Mode.READ_ONLY);
8        com.pdftools.image.Document inDoc = com.pdftools.image.Document.open(inStr)
9    ) {
10        // Convert the image to a PDF document
11    	new Converter().convert(inDoc, imageStream, profile);
12    } catch (Exception e) {
13        System.out.println("Error during image to PDF conversion: " + e.getMessage());
14        e.printStackTrace();
15        throw e;
16    }
17}
1private static void merge(MemoryStream coverStream, FileStream inputContentStream, String outPath) throws Exception {
2    try (
3        FileStream outStream = new FileStream(outPath, FileStream.Mode.READ_WRITE_NEW);
4        DocumentAssembler docAssembler = new DocumentAssembler(outStream)) {
5
6        // Append only the first page of the cover stream
7        docAssembler.append(com.pdftools.pdf.Document.open(coverStream), 1, 1);
8        // Append the content document
9        docAssembler.append(com.pdftools.pdf.Document.open(inputContentStream));
10
11        // Assemble the merged document
12        docAssembler.assemble();
13    }
14}
Download code sample
1# Convert the image cover to a PDF (stored in memory)
2with io.BytesIO() as cover_stream:
3    with io.FileIO(cover_image, 'rb') as image_stream:
4        with ImageDocument.open(image_stream) as image_document:
5
6            # Create the profile for converting the image to PDF
7            profile = Default()
8
9            # Convert image to PDF
10            converter = Converter()
11            converter.convert(image_document, cover_stream, profile)
12
13    # Prepare the content PDF and merge with the cover
14    with io.FileIO(content_pdf_path, 'rb') as content_pdf_stream:
15        with PdfDocument.open(content_pdf_stream) as content_pdf_document:
16
17            # Open output stream and append cover and content
18            with io.FileIO(output_path, 'wb+') as output_stream:
19                with DocumentAssembler(output_stream, None, None) as assembler:
20                    # Append cover page (convert from memory stream to PDF)
21                    assembler.append(PdfDocument.open(io.BytesIO(cover_stream.getvalue())), 1, 1)
22
23                    # Append the content PDF
24                    assembler.append(content_pdf_document)
25
26                    # Finalize the merged document
27                    assembler.assemble()
28
Download code sample

Optimizing documents

Flatten Annotations

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(
8    pInDoc, _T("Failed to create a document from the input file \"%s\". %s (ErrorCode: 0x%08x).\n"), szInPath,
9    szErrorBuff, PdfTools_GetLastError());
10
11// Create output stream for writing
12pOutStream = _tfopen(szOutPath, _T("wb+"));
13GOTO_CLEANUP_IF_NULL_PRINT_ERROR(pOutStream, _T("Failed to open the output file \"%s\" for writing.\n"), szOutPath);
14TPdfToolsSys_StreamDescriptor outDesc;
15PdfToolsSysCreateFILEStreamDescriptor(&outDesc, pOutStream, 0);
16
17// Create the profile that defines the optimization parameters.
18// The MinimalFileSize profile is used to to produce a minimal file size
19pProfile = (TPdfToolsOptimizationProfiles_Profile*)PdfToolsOptimizationProfiles_MinimalFileSize_New();
20
21// Optionally the profile's parameters can be changed according to the
22// requirements of your optimization process.
23// Set the profile to flatten annotations (include as well Forms and Links)
24TPdfToolsOptimization_RemovalOptions* pRemovalOptions =
25    PdfToolsOptimizationProfiles_Profile_GetRemovalOptions(pProfile);
26PdfToolsOptimization_RemovalOptions_SetAnnotations(pRemovalOptions,
27                                                   ePdfToolsOptimization_ConversionStrategy_Flatten);
28PdfToolsOptimization_RemovalOptions_SetFormFields(pRemovalOptions,
29                                                  ePdfToolsOptimization_ConversionStrategy_Flatten);
30PdfToolsOptimization_RemovalOptions_SetLinks(pRemovalOptions, ePdfToolsOptimization_ConversionStrategy_Flatten);
31
32// Optimize the document
33pOptimizer = PdfToolsOptimization_Optimizer_New();
34pOutDoc    = PdfToolsOptimization_Optimizer_OptimizeDocument(pOptimizer, pInDoc, &outDesc, pProfile, NULL);
35GOTO_CLEANUP_IF_NULL_PRINT_ERROR(pOutDoc, _T("The processing has failed. (ErrorCode: 0x%08x).\n"),
36                                 PdfTools_GetLastError());
37
Download code sample
1private static void FlattenAnnotations(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 MinimalFileSize profile is used to to produce a minimal file size
9    var profile = new Profiles.MinimalFileSize();
10
11    // Optionally the profile's parameters can be changed according to the 
12    // requirements of your optimization process.
13    profile.RemovalOptions.Annotations = ConversionStrategy.Flatten;
14    profile.RemovalOptions.FormFields = ConversionStrategy.Flatten;
15    profile.RemovalOptions.Links = ConversionStrategy.Flatten;
16
17    // Create output stream
18    using var outStr = File.Create(outPath);
19
20    // Optimize the document
21    using var outDoc = new Optimizer().OptimizeDocument(inDoc, outStr, profile);
22}
Download code sample
1private static void flattenAnnotations(String inPath, String outPath) throws Exception
2{
3    // Create the profile that defines the optimization parameters.
4    // The MinimalFileSize profile is used to to produce a minimal file size
5	MinimalFileSize profile = new MinimalFileSize();
6
7    // Optionally the profile's parameters can be changed according to the 
8    // requirements of your optimization process.
9    profile.getRemovalOptions().setAnnotations(ConversionStrategy.FLATTEN);
10    profile.getRemovalOptions().setFormFields(ConversionStrategy.FLATTEN);
11    profile.getRemovalOptions().setLinks(ConversionStrategy.FLATTEN);
12
13    try (
14        // Open input document
15        FileStream inStr = new FileStream(inPath, FileStream.Mode.READ_ONLY);
16        Document inDoc = Document.open(inStr);
17
18        // Create output stream
19        FileStream outStr = new FileStream(outPath, FileStream.Mode.READ_WRITE_NEW);
20
21        // Optimize the document
22        Document outDoc = new Optimizer().optimizeDocument(inDoc, outStr, profile))
23    {
24    }
25}
Download code sample
1
2
3flatten_annotations(args.input_path, args.output_path)
4
1def flatten_annotations(input_path: str, output_path: str):
2    # Open input document
3    with io.FileIO(input_path, 'rb') as in_stream:
4        with Document.open(in_stream) as input_document:
5
6            # Create the optimization profile for minimal file size
7            profile = MinimalFileSize()
8
9            # Flatten annotations, form fields, and links
10            profile.removal_options.annotations = ConversionStrategy.FLATTEN
11            profile.removal_options.form_fields = ConversionStrategy.FLATTEN
12            profile.removal_options.links = ConversionStrategy.FLATTEN
13
14            # Create output stream
15            with io.FileIO(output_path, 'wb+') as output_stream:
16
17                # Optimize the document
18                optimizer = Optimizer()
19                optimizer.optimize_document(input_document, output_stream, profile)
Download code sample

Optimize a PDF

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(
8    pInDoc, _T("Failed to create a document from the input file \"%s\". %s (ErrorCode: 0x%08x).\n"), szInPath,
9    szErrorBuff, PdfTools_GetLastError());
10
11// Create output stream for writing
12pOutStream = _tfopen(szOutPath, _T("wb+"));
13GOTO_CLEANUP_IF_NULL_PRINT_ERROR(pOutStream, _T("Failed to open the output file \"%s\" for writing.\n"), szOutPath);
14TPdfToolsSys_StreamDescriptor outDesc;
15PdfToolsSysCreateFILEStreamDescriptor(&outDesc, pOutStream, 0);
16
17// Create the profile that defines the optimization parameters.
18// The Web profile is suitable to optimize documents for electronic document exchange.
19pProfile = (TPdfToolsOptimizationProfiles_Profile*)PdfToolsOptimizationProfiles_Web_New();
20
21// Optionally the profile's parameters can be changed according to the
22// requirements of your optimization process.
23
24// Optimize the document
25pOptimizer = PdfToolsOptimization_Optimizer_New();
26pOutDoc    = PdfToolsOptimization_Optimizer_OptimizeDocument(pOptimizer, pInDoc, &outDesc, pProfile, NULL);
27GOTO_CLEANUP_IF_NULL_PRINT_ERROR(pOutDoc, _T("The processing has failed. (ErrorCode: 0x%08x).\n"),
28                                 PdfTools_GetLastError());
29
Download code sample
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 used 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}
Download code sample
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 used 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}
Download code sample
1
2
3optimize_pdf(args.input_path, args.output_path)
4
1def optimize_pdf(input_file_path: str, output_file_path: str):
2    # Open input document
3    with io.FileIO(input_file_path, 'rb') as in_stream:
4        with Document.open(in_stream) as input_document:
5            # Create the profile that defines the optimization parameters.
6            # The Web profile is used to optimize documents for electronic document exchange.
7            profile = Web()
8
9            # Optionally the profile's parameters can be changed according to the 
10            # requirements of your optimization process.
11
12            # Create output stream
13            with io.FileIO(output_file_path, 'wb+') as output_stream:
14                # Optimize the document
15                optimizer = Optimizer()
16                optimizer.optimize_document(input_document, output_stream, profile)
Download code sample
1Private Sub Optimize(inPath As String, outPath As String)
2    ' Open input document
3    Using inStr = File.OpenRead(inPath)
4        Using inDoc = Document.Open(inStr)
5
6            ' Create the profile that defines the optimization parameters.
7            ' The Web profile is used to optimize documents for electronic document exchange.
8            Dim profile = New Profiles.Web()
9
10            ' Optionally the profile's parameters can be changed according to the 
11            ' requirements of your optimization process.
12
13            ' Create output stream
14            Using outStr = File.Create(outPath)
15
16                ' Optimize the document
17                Using outDoc = New Optimizer().OptimizeDocument(inDoc, outStr, profile)
18                End Using
19            End Using
20        End Using
21    End Using
22End Sub
Download code sample

Powering AI applications

Convert images to an accessible PDF/A document

1
2# Store stream descriptors and images in lists
3stream_list = []
4images = ImageDocumentList()
5
6# Loop over all the image paths and store opened images into list
7for input_image_path in image_paths:
8    image_stream = io.FileIO(input_image_path, 'rb')
9    stream_list.append(image_stream)
10    images.append(ImageDocument.open(image_stream))
11
12# Create output stream for writing
13with io.FileIO(output_file_path, 'wb+') as output_stream:
14
15    # Create the profile that defines the conversion parameters.
16    # The Archive profile converts images to PDF/A documents for archiving.
17    profile = Archive()
18
19    # Set conformance of output document to PDF/A-2a
20    profile.conformance = Conformance.PDF_A2_A
21
22    # For PDF/A level A, an alternate text is required for each page of the image.
23    # This is optional for other PDF/A levels, e.g. PDF/A-2b.
24    profile.language = "en"
25
26    # Set alternate texts created by AI
27    alternate_text_list = profile.alternate_text
28    for image_path in image_paths:                
29        alternate_text = get_alternate_text(image_path)
30        alternate_text_list.append(alternate_text)
31
32    converter = Converter()
33    out_document = converter.convert_multiple(images, output_stream, profile)
34    if not out_document:
35        print(f"Error while converting images to Pdf.")
36        exit(1)
37
38
1# AI: Create alternate text.
2def get_alternate_text(image_path: str):
3
4    # Getting base64 representation of input image
5    with io.FileIO(image_path, 'rb') as image_stream:
6        base64_image = base64.b64encode(image_stream.read()).decode('utf-8')
7
8    # Instantiate OpenAI client and let AI create the alternate text
9    client = OpenAI(api_key="***insert-open-ai-api-key***")
10    response = client.chat.completions.create(
11        model="gpt-4-turbo",
12        messages=[
13            {
14            "role": "user",
15            "content": [
16                {"type": "text", "text": "Write a short sentence what can be seen on the image. It shall explain to a person with impaired vision what is on the image. Write the answer in a poetic way in english."},
17                {
18                    "type": "image_url",
19                    "image_url":
20                        {
21                            "url": f"data:image/jpeg;base64,{base64_image}",
22                        },
23                },
24            ],
25            }
26        ],
27        max_tokens=300,
28    )
29
30    return response.choices[0].message.content.strip()
Download code sample

Sign documents

Sign a PDF and add a visual appearance on an unsigned signature field

1static void AddAppearanceSignatureField(string certificateFile, string password, string appConfigFile, string inPath, string outPath)
2{
3    // Create a session to the built-in cryptographic provider
4    using var session = new PdfTools.Crypto.Providers.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    // Open input document
11    using var inStr = File.OpenRead(inPath);
12    using var inDoc = Document.Open(inStr);
13
14    // Choose first signature field
15    foreach (var field in inDoc.SignatureFields)
16    {
17        if (field != null)
18        {
19            signature.FieldName = field.FieldName;
20            break;
21        }
22    }
23
24    // Create stream for output file
25    using var outStr = File.Create(outPath);
26
27    // Create appearance from either an XML or a json file
28    using var appStream = File.OpenRead(appConfigFile);
29    if (Path.GetExtension(appConfigFile) == ".xml")
30        signature.Appearance = Appearance.CreateFromXml(appStream);
31    else
32        signature.Appearance = Appearance.CreateFromJson(appStream);
33
34    signature.Appearance.CustomTextVariables.Add("company", "Daily Planet");
35
36    // Sign the input document
37    using var outDoc = new Signer().Sign(inDoc, signature, outStr);
38}
Download code sample
1private static void sign(String certificateFile, String password, String appConfigFile, 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        // Open input document
11        FileStream inStr = new FileStream(inPath, FileStream.Mode.READ_ONLY);
12        Document inDoc = Document.open(inStr);)
13    {
14        // Create signature configuration from PFX (or P12) file
15        SignatureConfiguration signature = session.createSignatureFromCertificate(pfxStr, password);
16
17        // Choose first signature field
18        for (int i = 0; i < inDoc.getSignatureFields().size(); i++) {
19            if (inDoc.getSignatureFields().get(i) != null) {
20                signature.setFieldName(inDoc.getSignatureFields().get(i).getFieldName());
21                break;
22            }
23        }
24
25        try (
26           // Create appearance from either an XML or a json file
27            FileStream appConfigStr = new FileStream(appConfigFile, FileStream.Mode.READ_ONLY))
28        {
29            if (appConfigFile.toLowerCase().endsWith(".xml"))
30                signature.setAppearance(Appearance.createFromXml(appConfigStr));
31            else
32                signature.setAppearance(Appearance.createFromJson(appConfigStr));
33
34            signature.getAppearance().getCustomTextVariables().put("company", "Daily Planet");
35
36            try(
37                // Create a stream for the output file
38                FileStream outStr = new FileStream(outPath, FileStream.Mode.READ_WRITE_NEW);
39
40                // Sign the input document
41                Document outDoc = new Signer().sign(inDoc, signature, outStr))
42            {
43            }
44        }
45    }
46}
Download code sample
1
2
3# Sign the input document
4add_appearance_signature_field(args.certificate_file, args.password, args.app_config_file, args.input_path, args.output_path)
5
1def add_appearance_signature_field(certificate_file: str, password: str, appearance_config_file: str, input_path: str, output_path: str):
2    # Create a session to the built-in cryptographic provider
3    with Provider() as session:
4        # Create signature configuration from PFX (or P12) file
5        with io.FileIO(certificate_file, 'rb') as pfx_str:
6            signature = session.create_signature_from_certificate(pfx_str, password)
7
8            # Open input document
9            with io.FileIO(input_path, 'rb') as input_pdf_stream:
10                with Document.open(input_pdf_stream) as input_pdf_document:
11                    # Choose first signature field
12                    for field in input_pdf_document.signature_fields:
13                        if field:
14                            signature.field_name = field.field_name
15                            break
16
17                    # Create stream for output file
18                    with io.FileIO(output_path, 'wb+') as output_stream:
19                        # Create appearance configuration from either XML or JSON file
20                        with io.FileIO(appearance_config_file, 'rb') as appearance_config_stream:
21                            if os.path.splitext(appearance_config_file)[1].lower() == ".xml":
22                                signature.appearance = Appearance.create_from_xml(appearance_config_stream)
23                            else:
24                                signature.appearance = Appearance.create_from_json(appearance_config_stream)
25
26                            signature.appearance.custom_text_variables["company"] = "Daily Planet"
27
28                            # Sign the input document
29                            signer = Signer()
30                            signer.sign(input_pdf_document, signature, output_stream)
Download code sample
1Sub AddAppearanceSignatureField(certificateFile As String, password As String, appConfigFile As String, inPath As String, outPath As String)
2    ' Create a session to the built-in cryptographic provider
3    Using session As New PdfTools.Crypto.Providers.BuiltIn.Provider()
4
5        ' Create signature configuration from PFX (or P12) file
6        Using pfxStr = File.OpenRead(certificateFile)
7            Dim signature = session.CreateSignatureFromCertificate(pfxStr, password)
8
9            ' Open input document
10            Using inStr = File.OpenRead(inPath)
11                Using inDoc = Document.Open(inStr)
12
13                    ' Choose first signature field
14                    For Each field In inDoc.SignatureFields
15                        If field IsNot Nothing Then
16                            signature.FieldName = field.FieldName
17                            Exit For
18                        End If
19                    Next
20
21                    ' Create stream for output file
22                    Using outStr = File.Create(outPath)
23
24                        ' Create appearance from either an XML or a JSON file
25                        Using appStream = File.OpenRead(appConfigFile)
26                            If Path.GetExtension(appConfigFile).ToLower() = ".xml" Then
27                                signature.Appearance = Appearance.CreateFromXml(appStream)
28                            Else
29                                signature.Appearance = Appearance.CreateFromJson(appStream)
30                            End If
31
32                            signature.Appearance.CustomTextVariables.Add("company", "Daily Planet")
33
34                            ' Sign the input document
35                            Using outDoc = New Signer().Sign(inDoc, signature, outStr)
36                            End Using
37                        End Using
38                    End Using
39                End Using
40            End Using
41        End Using
42    End Using
43End Sub
Download code sample

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}
Download code sample
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}
Download code sample
1
2
3# Sign the input document
4add_signature_field(args.input_path, args.output_path)
5
1def add_signature_field(input_path: str, output_path: str):
2    # Open input document
3    with io.FileIO(input_path, 'rb') as in_stream:
4        with Document.open(in_stream) as input_document:
5            # Create empty field appearance that is 6cm by 3cm in size
6            appearance = Appearance.create_field_bounding_box(Size(170.08, 85.04))
7
8            # Add field to last page of document
9            appearance.page_number = input_document.page_count
10
11            # Position field
12            appearance.bottom = 85.04
13            appearance.left = 184.25
14
15            # Create a signature field configuration
16            field = SignatureFieldOptions(appearance)
17
18            # Create stream for output file
19            with io.FileIO(output_path, 'wb+') as output_stream:
20                # Sign the input document
21                signer = Signer()
22                signer.add_signature_field(input_document, field, output_stream)
Download code sample
1Sub AddSignatureField(inPath As String, outPath As String)
2    ' Open input document
3    Using inStr = File.OpenRead(inPath)
4        Using inDoc = Document.Open(inStr)
5
6            ' Create empty field appearance that is 6cm by 3cm in size
7            Dim appearance = Sign.Appearance.CreateFieldBoundingBox(Size.cm(6, 3))
8
9            ' Add field to last page of document
10            appearance.PageNumber = inDoc.PageCount
11
12            ' Position field
13            appearance.Bottom = Length.cm(3)
14            appearance.Left = Length.cm(6.5)
15
16            ' Create a signature field configuration
17            Dim field = New SignatureFieldOptions(appearance)
18
19            ' Create stream for output file
20            Using outStr = File.Create(outPath)
21
22                ' Sign the input document
23                Using outDoc = New Signer().AddSignatureField(inDoc, field, outStr)
24                End Using
25            End Using
26        End Using
27    End Using
28End Sub
Download code sample

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}
Download code sample
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}
Download code sample
1
2
3# Optional: Set your proxy configuration
4# Sdk.Proxy = new Uri("http://myproxy:8080");
5
6# Add a document time-stamp to a PDF
7add_timestamp(args.time_stamp_url, args.input_path, args.output_path)
8
1def add_timestamp(time_stamp_url: str, input_path: str, output_path: str):
2    # Create a session to the built-in cryptographic provider
3    with Provider() as session:
4        session.timestamp_url = time_stamp_url
5
6        # Create time-stamp configuration
7        timestamp = session.create_timestamp()
8
9        # Open input document
10        with io.FileIO(input_path, 'rb') as in_stream:
11            with Document.open(in_stream) as input_document:
12
13                # Create stream for output file
14                with io.FileIO(output_path, 'wb+') as output_stream:
15
16                    # Add the document time-stamp
17                    signer = Signer()
18                    signer.add_timestamp(input_document, timestamp, output_stream)
Download code sample
1Sub AddTimestamp(timeStampUrl As Uri, inPath As String, outPath As String)
2    ' Create a session to the built-in cryptographic provider
3    Using session As New BuiltIn.Provider()
4        session.TimestampUrl = timeStampUrl
5
6        ' Create time-stamp configuration
7        Dim timestamp = session.CreateTimestamp()
8
9        ' Open input document
10        Using inStr = File.OpenRead(inPath)
11            Using inDoc = Document.Open(inStr)
12
13                ' Create stream for output file
14                Using outStr = File.Create(outPath)
15
16                    ' Add the document time-stamp
17                    Using outDoc = New Signer().AddTimestamp(inDoc, timestamp, outStr)
18                    End Using
19                End Using
20            End Using
21        End Using
22    End Using
23End Sub
Download code sample

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}
Download code sample
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}
Download code sample
1
2
3# Certify a PDF document
4certify_document(args.certificate_file, args.password, args.input_path, args.output_path)
5
1def certify_document(certificate_file: str, password: str, input_path: str, output_path: str):
2    # Create a session to the built-in cryptographic provider
3    with Provider() as session:
4        with io.FileIO(certificate_file, 'rb') as pfx_stream:
5            # Create signature configuration from PFX (or P12) file
6            signature = session.create_signature_from_certificate(pfx_stream, password)
7
8            # Embed validation information to enable the long-term validation (LTV) of the signature
9            signature.validation_information = ValidationInformation.EMBED_IN_DOCUMENT
10
11            # Open input document
12            with io.FileIO(input_path, 'rb') as in_stream:
13                with Document.open(in_stream) as input_document:
14
15                    # Create stream for output file
16                    with io.FileIO(output_path, 'wb+') as output_stream:
17                        # Certify the document with the MDP signature
18                        signer = Signer()
19                        signer.certify(input_document, signature, output_stream)
Download code sample
1Sub Certify(certificateFile As String, password As String, inPath As String, outPath As String)
2    ' Create a session to the built-in cryptographic provider
3    Using session As New BuiltIn.Provider()
4
5        ' Create signature configuration from PFX (or P12) file
6        Using pfxStr = File.OpenRead(certificateFile)
7            Dim signature = session.CreateSignatureFromCertificate(pfxStr, password)
8
9            ' Embed validation information to enable the long term validation (LTV) of the signature (default)
10            signature.ValidationInformation = PdfTools.Crypto.ValidationInformation.EmbedInDocument
11
12            ' Open input document
13            Using inStr = File.OpenRead(inPath)
14                Using inDoc = Document.Open(inStr)
15
16                    ' Create stream for output file
17                    Using outStr = File.Create(outPath)
18
19                        ' Add a document certification (MDP) signature
20                        ' Optionally, the access permissions can be set.
21                        Using outDoc = New Signer().Certify(inDoc, signature, outStr)
22                        End Using
23                    End Using
24                End Using
25            End Using
26        End Using
27    End Using
28End Sub
Download code sample

Sign a PDF using a PFX soft certificate

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(
8    pInDoc, _T("Failed to create a document from the input file \"%s\". %s (ErrorCode: 0x%08x).\n"), szInPath,
9    szErrorBuff, PdfTools_GetLastError());
10
11// Create output stream for writing
12pOutStream = _tfopen(szOutPath, _T("wb+"));
13GOTO_CLEANUP_IF_NULL_PRINT_ERROR(pOutStream, _T("Failed to open the output file \"%s\" for writing.\n"), szOutPath);
14TPdfToolsSys_StreamDescriptor outDesc;
15PdfToolsSysCreateFILEStreamDescriptor(&outDesc, pOutStream, 0);
16
17// Create a session to the built-in cryptographic provider
18pSession = PdfToolsCryptoProvidersBuiltIn_Provider_New();
19
20// Create signature configuration from PFX (or P12) file
21pCertificateFileStream = _tfopen(szCertificateFile, _T("rb"));
22GOTO_CLEANUP_IF_NULL_PRINT_ERROR(
23    pCertificateFileStream, _T("Failed to open the certificate file \"%s\" for reading.\n"), szCertificateFile);
24TPdfToolsSys_StreamDescriptor certificateFileDesc;
25PdfToolsSysCreateFILEStreamDescriptor(&certificateFileDesc, pCertificateFileStream, 0);
26pSignatureConfiguration = PdfToolsCryptoProvidersBuiltIn_Provider_CreateSignatureFromCertificate(
27    pSession, &certificateFileDesc, szPassword);
28
29// Embed validation information to enable the long term validation (LTV) of the signature (default)
30PdfToolsCryptoProvidersBuiltIn_SignatureConfiguration_SetValidationInformation(
31    pSignatureConfiguration, ePdfToolsCrypto_ValidationInformation_EmbedInDocument);
32
33// Sign the input document
34pSigner = PdfToolsSign_Signer_New();
35pOutDoc = PdfToolsSign_Signer_Sign(pSigner, pInDoc, pSignatureConfiguration, &outDesc, NULL);
36GOTO_CLEANUP_IF_NULL_PRINT_ERROR(pOutDoc, _T("The processing has failed. (ErrorCode: 0x%08x).\n"),
37                                 PdfTools_GetLastError());
38
Download code sample
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}
Download code sample
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 a stream for the output file
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}
Download code sample
1
2
3# Sign a PDF document
4sign(args.certificate_file, args.password, args.input_path, args.output_path)
5
1def sign(certificate_file: str, password: str, input_path: str, output_path: str):
2    # Create a session to the built-in cryptographic provider
3    with Provider() as session:
4        with io.FileIO(certificate_file, 'rb') as pfx_str:
5            # Create signature configuration from PFX (or P12) file
6            signature = session.create_signature_from_certificate(pfx_str, password)
7
8            # Embed validation information to enable long-term validation (LTV) of the signature
9            signature.validation_information = ValidationInformation.EMBED_IN_DOCUMENT
10
11            signature.appearance = Appearance.create_field_bounding_box(Size(width=200, height=300))
12            signature.appearance.page_number = 1
13
14            # Open input document
15            with io.FileIO(input_path, 'rb') as input_pdf_stream:
16                with Document.open(input_pdf_stream) as input_pdf_document:
17                    # Create stream for output file
18                    with io.FileIO(output_path, 'wb+') as output_stream:
19                        # Sign the input document
20                        signer = Signer()
21                        signer.sign(input_pdf_document, signature, output_stream)
Download code sample
1Sub Sign(certificateFile As String, password As String, inPath As String, outPath As String)
2    ' Create a session to the built-in cryptographic provider
3    Using session As New BuiltIn.Provider()
4
5        ' Create signature configuration from PFX (or P12) file
6        Using pfxStr = File.OpenRead(certificateFile)
7            Dim signature = session.CreateSignatureFromCertificate(pfxStr, password)
8
9            ' Embed validation information to enable the long term validation (LTV) of the signature (default)
10            signature.ValidationInformation = PdfTools.Crypto.ValidationInformation.EmbedInDocument
11
12            ' Open input document
13            Using inStr = File.OpenRead(inPath)
14                Using inDoc = Document.Open(inStr)
15
16                    ' Create stream for output file
17                    Using outStr = File.Create(outPath)
18
19                        ' Sign the input document
20                        Using outDoc = New Signer().Sign(inDoc, signature, outStr)
21                        End Using
22                    End Using
23                End Using
24            End Using
25        End Using
26    End Using
27End Sub
Download code sample

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}
Download code sample
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}
Download code sample
1
2
3# Configure the SSL client certificate to connect to the service
4http_client_handler = HttpClientHandler()
5with io.FileIO("C:\path\to\clientcert.cer", 'rb') as cert_stream:
6    with io.FileIO("C:\path\to\privateKey.key", 'rb') as key_stream:
7        http_client_handler.set_client_certificate_and_key(cert_stream, key_stream, "***insert password***")
8
9        # Connect to the GlobalSign DSS service
10        with Session("https://emea.api.dss.globalsign.com:8443", "***insert api_key***", "***insert api_secret***", http_client_handler) as session:
11
12            # Add a document time-stamp to a PDF
13            add_timestamp(session, input_path, output_path)
14
1def add_timestamp(session: Session, input_path: str, output_path: str):
2    # Create time-stamp configuration
3    timestamp = session.create_timestamp()
4
5    # Open input document
6    with io.FileIO(input_path, 'rb') as in_stream:
7        with Document.open(in_stream) as input_document:
8
9            # Create stream for output file
10            with io.FileIO(output_path, 'wb+') as output_stream:
11
12                # Add the document time-stamp
13                signer = Signer()
14                signer.add_timestamp(input_document, timestamp, output_stream)
Download code sample
1' Configure the SSL client certificate to connect to the service
2Dim httpClientHandler = New HttpClientHandler()
3Using sslClientCert = File.OpenRead("C:\path\to\clientcert.cer")
4    Using sslClientKey = File.OpenRead("C:\path\to\privateKey.key")
5        httpClientHandler.SetClientCertificateAndKey(sslClientCert, sslClientKey, "***insert password***")
6    End Using
7End Using
8
9' Connect to the GlobalSign Digital Signing Service
10Using session = New GlobalSignDss.Session(New Uri("https://emea.api.dss.globalsign.com:8443"), "***insert api_key***", "***insert api_secret***", httpClientHandler)
11
12    ' Add a document time-stamp to a PDF
13    AddTimestamp(session, inPath, outPath)
14End Using
1Sub AddTimestamp(session As GlobalSignDss.Session, inPath As String, outPath As String)
2    ' Create time-stamp configuration
3    Dim timestamp = session.CreateTimestamp()
4
5    ' Open input document
6    Using inStr = File.OpenRead(inPath)
7        Using inDoc = Document.Open(inStr)
8
9            ' Create stream for output file
10            Using outStr = File.Create(outPath)
11
12                ' Add the document time-stamp
13                Using outDoc = New Signer().AddTimestamp(inDoc, timestamp, outStr)
14                End Using
15            End Using
16        End Using
17    End Using
18End Sub
Download code sample

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}
Download code sample
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    SignatureConfiguration 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}
Download code sample
1
2
3# Configure the SSL client certificate to connect to the service
4http_client_handler = HttpClientHandler()
5with io.FileIO("C:\path\to\clientcert.cer", 'rb') as cert_stream:
6    with io.FileIO("C:\path\to\privateKey.key", 'rb') as key_stream:
7        http_client_handler.set_client_certificate_and_key(cert_stream, key_stream, "***insert password***")
8
9        # Connect to the GlobalSign DSS service
10        with Session("https://emea.api.dss.globalsign.com:8443", "***insert api_key***", "***insert api_secret***", http_client_handler) as session:
11            # Sign a PDF document
12            sign(session, common_name, input_path, output_path);
13
1def sign(session: Session, common_name: str, input_path: str, output_path: str):
2    # Create a signing certificate for an account with a dynamic identity
3    identity = json.dumps({"subject_dn": {"common_name": common_name}})
4    signature = session.create_signature_for_dynamic_identity(identity)
5
6    # Embed validation information to enable the long term validation (LTV) of the signature (default)
7    signature.validation_information = ValidationInformation.EMBED_IN_DOCUMENT
8
9    # Open input document
10    with io.FileIO(input_path, 'rb') as in_stream:
11        with Document.open(in_stream) as input_document:
12
13            # Create stream for output file
14            with io.FileIO(output_path, 'wb+') as output_stream:
15
16                # Sign the document
17                signer = Signer()
18                signer.sign(input_document, signature, output_stream)
Download code sample
1' Configure the SSL client certificate to connect to the service
2Dim httpClientHandler = New HttpClientHandler()
3Using sslClientCert = File.OpenRead("C:\path\to\clientcert.cer")
4    Using sslClientKey = File.OpenRead("C:\path\to\privateKey.key")
5        httpClientHandler.SetClientCertificateAndKey(sslClientCert, sslClientKey, "***insert password***")
6    End Using
7End Using
8
9' Connect to the GlobalSign Digital Signing Service
10Using session = New GlobalSignDss.Session(New Uri("https://emea.api.dss.globalsign.com:8443"), "***insert api_key***", "***insert api_secret***", httpClientHandler)
11
12    ' Sign a PDF document
13    Sign(session, commonName, inPath, outPath)
14End Using
1Sub Sign(session As GlobalSignDss.Session, commonName As String, inPath As String, outPath As String)
2    ' Create a signing certificate for an account with a dynamic identity
3    Dim identity = JsonSerializer.Serialize(New With {.subject_dn = New With {.common_name = commonName}})
4    Dim signature = session.CreateSignatureForDynamicIdentity(identity)
5
6    ' Embed validation information to enable the long term validation (LTV) of the signature (default)
7    signature.ValidationInformation = PdfTools.Crypto.ValidationInformation.EmbedInDocument
8
9    ' Open input document
10    Using inStr = File.OpenRead(inPath)
11        Using inDoc = Document.Open(inStr)
12
13            ' Create stream for output file
14            Using outStr = File.Create(outPath)
15
16                ' Sign the document
17                Using outDoc = New Signer().Sign(inDoc, signature, outStr)
18                End Using
19            End Using
20        End Using
21    End Using
22End Sub
Download code sample

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)
7// Use Devices[i] if you have more than one device installed instead of Devices.GetSingle()
8using var session = module.Devices.GetSingle().CreateSession(password);
9
10// Sign a PDF document
11Sign(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}
Download code sample
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    SignatureConfiguration 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}
Download code sample
1
2
3# Load the PKCS#11 driver module (middleware)
4# The module can only be loaded once in the application.
5with Module.load(pkcs11_library) as module:
6
7    # Create a session to the cryptographic device and log in with the password (pin)
8    # Use devices[i] if you have more than one device installed instead of devices.get_single()
9    with module.devices.get_single().create_session(password) as session:
10        # Sign a PDF document
11        sign(session, certificate, input_path, output_path)
12
1def sign(session: Session, certificate: str, input_path: str, output_path: str):
2    # Create the signature configuration for the certificate
3    signature = session.create_signature_from_name(certificate)
4
5    # Open input document
6    with io.FileIO(input_path, 'rb') as in_stream:
7        with Document.open(in_stream) as input_document:
8
9            # Create stream for output file
10            with io.FileIO(output_path, 'wb+') as output_stream:
11
12                # Sign the input document
13                signer = Signer()
14                signer.sign(input_document, signature, output_stream)
Download code sample
1' Load the PKCS#11 driver module (middleware)
2' The module can only be loaded once in the application.
3Using [module] = Pkcs11.Module.Load(pkcs11Library)
4
5    ' Create a session to the cryptographic device and log in
6    ' with the password (pin)
7    Using session = [module].Devices.GetSingle().CreateSession(password)
8
9        ' Sign a PDF document
10        Sign(session, certificate, inPath, outPath)
11    End Using
12End Using
1Sub Sign(session As Pkcs11.Session, certificate As String, inPath As String, outPath As String)
2    ' Create the signature configuration
3    ' This can be re-used to sign multiple documents
4    Dim signature = session.CreateSignatureFromName(certificate)
5
6    ' Open input document
7    Using inStr = File.OpenRead(inPath)
8        Using inDoc = Document.Open(inStr)
9
10            ' Create stream for output file
11            Using outStr = File.Create(outPath)
12
13                ' Sign the input document
14                Using outDoc = New Signer().Sign(inDoc, signature, outStr)
15                End Using
16            End Using
17        End Using
18    End Using
19End Sub
Download code sample

Validate the signatures contained an input document

1
2// Helper functions to print signature validation details
3
1static int Validate(string inputFile, string certDir)
2{
3    // Use the default validation profile as a base for further settings
4    var profile = new Default();
5
6    // For offline operation, build a custom trust list from the file system 
7    // and disable external revocation checks
8    if (certDir != null && certDir.Length != 0)
9    {
10        Console.WriteLine("Using 'offline' validation mode with custom trust list.");
11        Console.WriteLine();
12
13        // create a CustomTrustList to hold the certificates
14        var ctl = new CustomTrustList();
15
16        // Iterate through files in the certificate directory and add certificates
17        // to the custom trust list
18        if (Directory.Exists(certDir))
19        {
20            var directoryListing = Directory.EnumerateFiles(certDir);
21            foreach (string fileName in directoryListing)
22            {
23                try
24                {
25                    using var certStr = File.OpenRead(fileName);
26
27                    if (fileName.EndsWith(".cer") || fileName.EndsWith(".pem"))
28                    {
29                        ctl.AddCertificates(certStr);
30                    }
31                    else if (fileName.EndsWith(".p12") || fileName.EndsWith(".pfx"))
32                    {
33                        // If a password is required, use addArchive(certStr, password).
34                        ctl.AddArchive(certStr);
35                    }
36                }
37                catch (Exception e)
38                {
39                    Console.WriteLine("Could not add certificate '" + fileName + "' to custom trust list: " + e.Message);
40                }
41            }
42        }
43        else
44        {
45            // Handle the case where dir is not a directory
46            Console.WriteLine("Directory " + certDir + " is missing. No certificates were added to the custom trust list.");
47        }
48        Console.WriteLine();
49
50        // Assign the custom trust list to the validation profile
51        profile.CustomTrustList = ctl;
52
53        // Allow validation from embedded file sources and the custom trust list
54        var vo = profile.ValidationOptions;
55        vo.TimeSource = TimeSource.ProofOfExistence | TimeSource.ExpiredTimeStamp | TimeSource.SignatureTime;
56        vo.CertificateSources = DataSource.EmbedInSignature | DataSource.EmbedInDocument | DataSource.CustomTrustList;
57
58        // Disable revocation checks.
59        profile.SigningCertTrustConstraints.RevocationCheckPolicy = RevocationCheckPolicy.NoCheck;
60        profile.TimeStampTrustConstraints.RevocationCheckPolicy = RevocationCheckPolicy.NoCheck;
61    }
62
63    // Validate ALL signatures in the document (not only the latest)
64    var signatureSelector = SignatureSelector.All;
65
66    // Create the validator object and event listeners
67    var validator = new Validator();
68    validator.Constraint += (s, e) =>
69    {
70        Console.WriteLine("  - " + e.Signature.Name + (e.DataPart.Length > 0 ? (": " + e.DataPart) : "") + ": " +
71            ConstraintToString(e.Indication, e.SubIndication, e.Message));
72    };
73
74    try
75    {
76        using var inStr = File.OpenRead(inputFile);
77        // Open input document
78        // If a password is required, use Open(inStr, password)
79        using var document = Document.Open(inStr);
80
81        // Run the validate method passing the document, profile and selector
82        Console.WriteLine("Validation Constraints");
83        var results = validator.Validate(document, profile, signatureSelector);
84
85        Console.WriteLine();
86        Console.WriteLine("Signatures validated: " + results.Count);
87        Console.WriteLine();
88
89        // Print results
90        foreach (var result in results)
91        {
92            var field = result.SignatureField;
93            Console.WriteLine(field.FieldName + " of " + field.Name);
94            try
95            {
96                Console.WriteLine("  - Revision  : " + (field.Revision.IsLatest ? "latest" : "intermediate"));
97            }
98            catch (Exception ex)
99            {
100                Console.WriteLine("Unable to validate document Revision: " + ex.Message);
101            }
102
103            PrintContent(result.SignatureContent);
104            Console.WriteLine();
105        }
106
107        return 0;
108    }
109    catch (Exception ex)
110    {
111        Console.WriteLine("Unable to validate file: " + ex.Message);
112        return 5;
113    }
114}
1private static void PrintContent(SignatureContent content)
2{
3    if(content != null)
4    {
5        Console.WriteLine("  - Validity  : " + ConstraintToString(content.Validity));
6        switch (content)
7        {
8            case UnsupportedSignatureContent:
9                break;
10            case CmsSignatureContent signature:
11                {
12                    Console.WriteLine("  - Validation: " + signature.ValidationTime + " from " + signature.ValidationTimeSource);
13                    Console.WriteLine("  - Hash      : " + signature.HashAlgorithm);
14                    Console.WriteLine("  - Signing Cert");
15                    PrintContent(signature.SigningCertificate);
16                    Console.WriteLine("  - Chain");
17                    foreach (var cert in signature.CertificateChain)
18                    {
19                        Console.WriteLine("  - Issuer Cert " + (signature.CertificateChain.IndexOf(cert) + 1));
20                        PrintContent(cert);
21                    }
22                    Console.WriteLine("  - Chain     : " + (signature.CertificateChain.IsComplete ? "complete" : "incomplete") + " chain");
23                    Console.WriteLine("  Time-Stamp");
24                    PrintContent(signature.TimeStamp);
25                    break;
26                }
27            case TimeStampContent timeStamp:
28                {
29                    Console.WriteLine("  - Validation: " + timeStamp.ValidationTime + " from " + timeStamp.ValidationTimeSource);
30                    Console.WriteLine("  - Hash      : " + timeStamp.HashAlgorithm);
31                    Console.WriteLine("  - Time      : " + timeStamp.Date);
32                    Console.WriteLine("  - Signing Cert");
33                    PrintContent(timeStamp.SigningCertificate);
34                    Console.WriteLine("  - Chain");
35                    foreach (var cert in timeStamp.CertificateChain)
36                    {
37                        Console.WriteLine("  - Issuer Cert " + (timeStamp.CertificateChain.IndexOf(cert) + 1));
38                        PrintContent(cert);
39                    }
40                    Console.WriteLine("  - Chain      : " + (timeStamp.CertificateChain.IsComplete ? "complete" : "incomplete") + " chain");
41                    break;
42                }
43            default:
44                Console.WriteLine("Unsupported signature content type " + content.GetType().Name);
45                break;
46        }                
47    }
48    else
49    {
50        Console.WriteLine("  - null");
51    }
52}
1private static void PrintContent(Certificate cert)
2{
3    if(cert != null)
4    {
5        Console.WriteLine("    - Subject    : " + cert.SubjectName);
6        Console.WriteLine("    - Issuer     : " + cert.IssuerName);
7        Console.WriteLine("    - Validity   : " + cert.NotBefore + " - " + cert.NotAfter);
8        try
9        {
10            Console.WriteLine("    - Fingerprint: " + FormatSha1Digest(new BigInteger(SHA1.Create().ComputeHash(cert.RawData)).ToByteArray(), "-"));
11        }
12        catch (Exception ex)
13        {
14            Console.WriteLine(ex.Message);
15        }
16        Console.WriteLine("    - Source     : " + cert.Source);
17        Console.WriteLine("    - Validity   : " + ConstraintToString(cert.Validity));
18    }
19    else
20    {
21        Console.WriteLine("    - null");
22    }
23}
1private static String ConstraintToString(ConstraintResult constraint)
2{
3    return ConstraintToString(constraint.Indication, constraint.SubIndication, constraint.Message);
4}
1private static String ConstraintToString(Indication indication, SubIndication subIndication, String message)
2{
3    return (indication == Indication.Valid ? "" : (indication == Indication.Indeterminate ? "?" : "!")) + "" +
4        subIndication + " " +
5        message;
6}
1// Helper function to generate a delimited SHA-1 digest string
2private static String FormatSha1Digest(byte[] bytes, String delimiter)
3{
4    var result = new StringBuilder();
5    foreach (byte aByte in bytes)
6    {
7        int number = (int)aByte & 0xff;
8        String hex = number.ToString("X2");
9        result.Append(hex.ToUpper() + delimiter);
10    }
11    return result.ToString().Substring(0, result.Length - delimiter.Length);
12}
Download code sample
1
2// Helper functions to print signature validation details
3
1private static int validate(String inputFile, String certDir)
2{
3    // Use the default validation profile as a base for further settings
4    Profile profile = new Default();
5
6    // For offline operation, build a custom trust list from the file system
7    // and disable external revocation checks
8    if (certDir != null && !certDir.isEmpty())
9    {            
10        System.out.println("Using 'offline' validation mode with custom trust list.");
11        System.out.println();
12
13        // create a CustomTrustList to hold the certificates
14        CustomTrustList ctl = new CustomTrustList();
15
16        // Iterate through files in the certificate directory and add certificates
17        // to the custom trust list
18        File dir = new File(certDir);
19        File[] directoryListing = dir.listFiles();
20        if (directoryListing != null)
21        {
22            for (File child : directoryListing)
23            {                    
24                String fileName = child.getName();
25                try (
26                    FileStream certStr = new FileStream(child.getPath(), FileStream.Mode.READ_ONLY))
27                {
28                    if (fileName.endsWith(".cer") || fileName.endsWith(".pem"))
29                    {
30                        ctl.addCertificates(certStr);
31                    }
32                    else if (fileName.endsWith(".p12") || fileName.endsWith(".pfx"))
33                    {                            
34                        // If a password is required, use addArchive(certStr, password).
35                        ctl.addArchive(certStr);
36                    }
37                }
38                catch (Exception e)
39                {
40                    System.out.println("Could not add certificate '" + child.getName() + "' to custom trust list: " + e.getMessage());
41                }
42            }
43        }
44        else
45        {
46            // Handle the case where dir is not a directory
47            System.out.println("Directory " + certDir + " is missing. No certificates were added to the custom trust list.");
48        }
49        System.out.println();
50
51        // Assign the custom trust list to the validation profile
52        profile.setCustomTrustList(ctl);
53
54        // Allow validation from embedded file sources and the custom trust list
55        ValidationOptions vo = profile.getValidationOptions();
56        vo.setTimeSource(EnumSet.of(TimeSource.PROOF_OF_EXISTENCE, TimeSource.EXPIRED_TIME_STAMP, TimeSource.SIGNATURE_TIME));
57        vo.setCertificateSources(EnumSet.of(DataSource.EMBED_IN_SIGNATURE, DataSource.EMBED_IN_DOCUMENT, DataSource.CUSTOM_TRUST_LIST));
58
59        // Disable revocation checks.
60        profile.getSigningCertTrustConstraints().setRevocationCheckPolicy(RevocationCheckPolicy.NO_CHECK);
61        profile.getTimeStampTrustConstraints().setRevocationCheckPolicy(RevocationCheckPolicy.NO_CHECK);
62    }
63
64    // Validate ALL signatures in the document (not only the latest)
65    SignatureSelector signatureSelector = SignatureSelector.ALL;
66
67    // Create the validator object and event listeners
68    Validator validator = new Validator();
69    validator.addConstraintListener(e -> {
70        System.out.println("  - " + e.getSignature().getName() + (e.getDataPart().length() > 0 ? (": " + e.getDataPart()) : "") + ": " + 
71            constraintToString(e.getIndication(), e.getSubIndication(), e.getMessage()));
72    });
73
74    try (
75        FileStream inStr = new FileStream(inputFile, FileStream.Mode.READ_ONLY);
76        // Open input document
77        // If a password is required, use open(inStr, password)
78        Document document = Document.open(inStr);
79    )
80    {            
81        // Run the validate method passing the document, profile and selector
82        System.out.println("Validation Constraints");
83        ValidationResults results = validator.validate(document, profile, signatureSelector);
84
85        System.out.println();
86        System.out.println("Signatures validated: " + results.size());
87        System.out.println();
88
89        // Print results
90        results.forEach(result -> {
91            SignedSignatureField field = result.getSignatureField();
92            System.out.println(field.getFieldName() + " of " + field.getName());
93            try
94            {
95                System.out.println("  - Revision  : " + (field.getRevision().getIsLatest() ? "latest" : "intermediate"));
96            }
97            catch (Exception ex)
98            {
99                System.out.println("Unable to validate document Revision: " + ex.getMessage());
100            }
101
102            printContent(result.getSignatureContent());
103            System.out.println();
104        });
105
106        return 0;
107    }
108    catch (Exception ex)
109    {
110        System.out.println("Unable to validate file: " + ex.getMessage());
111        return 5;
112    }
113}
1private static void printContent(SignatureContent content)
2{        
3    if(content != null)
4    {
5        System.out.println("  - Validity  : " + constraintToString(content.getValidity()));
6        switch (content.getClass().getSimpleName())
7        {
8            case "UnsupportedSignatureContent":
9                break;
10            case "CmsSignatureContent":
11                {
12                    CmsSignatureContent signature = (CmsSignatureContent)content;
13                    System.out.println("  - Validation: " + signature.getValidationTime() + " from " + signature.getValidationTimeSource());
14                    System.out.println("  - Hash      : " + signature.getHashAlgorithm());
15                    System.out.println("  - Signing Cert");
16                    printContent(signature.getSigningCertificate());
17                    System.out.println("  - Chain");
18                    signature.getCertificateChain().forEach(cert -> {
19                        System.out.println("  - Issuer Cert " + (signature.getCertificateChain().indexOf(cert) + 1));
20                        printContent(cert);
21                    });
22                    System.out.println("  - Chain     : " + (signature.getCertificateChain().getIsComplete() ? "complete" : "incomplete") + " chain");
23                    System.out.println("  Time-Stamp");
24                    printContent(signature.getTimeStamp());
25                    break;
26                }
27            case "TimeStampContent":
28                {
29                    TimeStampContent timeStamp = (TimeStampContent)content;
30                    System.out.println("  - Validation: " + timeStamp.getValidationTime() + " from " + timeStamp.getValidationTimeSource());
31                    System.out.println("  - Hash      : " + timeStamp.getHashAlgorithm());
32                    System.out.println("  - Time      : " + timeStamp.getDate());
33                    System.out.println("  - Signing Cert");
34                    printContent(timeStamp.getSigningCertificate());
35                    System.out.println("  - Chain");
36                    timeStamp.getCertificateChain().forEach(cert -> {
37                        System.out.println("  - Issuer Cert " + (timeStamp.getCertificateChain().indexOf(cert) + 1));
38                        printContent(cert);
39                    });
40                    System.out.println("  - Chain      : " + (timeStamp.getCertificateChain().getIsComplete() ? "complete" : "incomplete") + " chain");
41                    break;
42                }
43            default:
44                System.out.println("Unsupported signature content type " + content.getClass().getName());
45                break;
46        }              
47    }
48    else
49    {
50        System.out.println("  - null");
51    }
52}
1private static void printContent(Certificate cert)
2{ 
3    if(cert != null)
4    {
5        System.out.println("    - Subject    : " + cert.getSubjectName());
6        System.out.println("    - Issuer     : " + cert.getIssuerName());
7        System.out.println("    - Validity   : " + cert.getNotBefore() + " - " + cert.getNotAfter());
8        try {
9            System.out.println("    - Fingerprint: " + formatSha1Digest(new java.math.BigInteger(1, (MessageDigest.getInstance("SHA-1").digest(cert.getRawData()))).toByteArray(), "-"));
10        } catch (Exception ex) {
11            System.out.println(ex.getMessage());
12        }
13        System.out.println("    - Source     : " + cert.getSource());
14        System.out.println("    - Validity   : " + constraintToString(cert.getValidity()));
15    }
16    else
17    {
18        System.out.println("    - null");
19    }
20}
1private static String constraintToString(ConstraintResult constraint)
2{
3    return constraintToString(constraint.getIndication(), constraint.getSubIndication(), constraint.getMessage());
4}
1private static String constraintToString(Indication indication, SubIndication subIndication, String message)
2{
3    return (indication == Indication.VALID ? "" : (indication == Indication.INDETERMINATE ? "?" : "!")) + "" +
4        subIndication + " " +
5        message;
6}
1// Helper function to generate a delimited SHA-1 digest string
2private static String formatSha1Digest(byte[] bytes, String delimiter) {
3    StringBuilder result = new StringBuilder();
4    for (byte aByte : bytes) {
5        int decimal = (int) aByte & 0xff;               
6        String hex = Integer.toHexString(decimal);
7        if (hex.length() % 2 == 1)                   
8            hex = "0" + hex;
9        result.append(hex.toUpperCase() + delimiter);
10    }
11    return result.substring(0, result.length() - delimiter.length());
12}
Download code sample
1def validate(input_file: str, cert_dir:str):
2    # Use the default validation profile as a base for further settings
3    profile = Default()
4
5    # For offline operation, build a custom trust list from the file system and disable external revocation checks
6    if cert_dir:
7        print("Using 'offline' validation mode with custom trust list.")
8        print("\n")
9
10        # create a CustomTrustList to hold the certificates
11        ctl = CustomTrustList()
12
13        # Iterate through files in the certificate directory and add certificates to the custom trust list
14        if os.path.isdir(cert_dir):
15            for file_name in os.listdir(cert_dir):
16                try:
17                    with io.FileIO(os.path.join(cert_dir, file_name), 'rb') as cert_stream:
18                        if file_name.endswith(".cer") or file_name.endswith(".pem"):
19                            ctl.add_certificates(cert_stream)
20                        elif file_name.endswith(".p12") or file_name.endswith(".pfx"):
21                            # If a password is required, use add_archive(certStr, password).
22                            ctl.add_archive(cert_stream)
23                except Exception as e:
24                    print(f"Could not add certificate '{file_name}' to custom trust list: {e}")
25        else:
26            print(f"Directory {cert_dir} is missing. No certificates were added to the custom trust list.")
27        print("\n")
28
29        profile.custom_trust_list = ctl
30
31        # Configure validation options
32        validation_options = profile.validation_options
33        validation_options.time_source = TimeSource.PROOF_OF_EXISTENCE | TimeSource.EXPIRED_TIME_STAMP | TimeSource.SIGNATURE_TIME
34        validation_options.certificate_sources = DataSource.EMBED_IN_SIGNATURE | DataSource.EMBED_IN_DOCUMENT | DataSource.CUSTOM_TRUST_LIST
35
36        # Disable revocation checks.
37        profile.signing_cert_trust_constraints.revocation_check_policy = RevocationCheckPolicy.NO_CHECK
38        profile.time_stamp_trust_constraints.revocation_check_policy = RevocationCheckPolicy.NO_CHECK
39
40    # Validate ALL signatures in the document (not only the latest)
41    signatureSelector = SignatureSelector.ALL
42
43    # Create the validator object and event listeners
44    validator = Validator()
45    validator.add_constraint_handler(on_constraint_event)
46
47    try:
48        with io.FileIO(input_file, 'rb') as in_stream:
49            # Open input document
50            # If a password is required, use Open(inStr, password)
51            with Document.open(in_stream) as document:
52                print("Validation Constraints")
53                results = validator.validate(document, profile, signatureSelector)
54                print("\n")
55                print(f"Signatures validated: {len(results)}")
56                print("\n")
57
58                for result in results:
59                    field = result.signature_field
60                    print(f"{field.field_name} of {field.name}")
61                    try:
62                        print(f"  - Revision  : {'latest' if field.revision.is_latest else 'intermediate'}")
63                    except Exception as ex:
64                        print(f"Unable to validate document Revision: {str(ex)}")
65
66                    print_signature_content(result.signature_content)
67                    print("\n")
68    except Exception as e:
69        print(f"Unable to validate file: {e}")
1def on_constraint_event(message: str, indication: Indication, sub_indication: SubIndication, signature: DocumentSignature, data_part: str):
2    print(f"  - {signature.name}" + (f": {data_part}" if len(data_part) > 0 else "") + ": " +
3          constraint_to_string(indication, sub_indication.name, message))
1# Helper functions to print signature validation details
2
3def print_signature_content(content: SignatureContent):
4    if content is not None:
5        print(f"  - Validity  : {constraint_to_string(content.validity.indication, content.validity.sub_indication.name, content.validity.message)}")
6
7        if isinstance(content, UnsupportedSignatureContent):
8            pass  # No action for unsupported content
9        elif isinstance(content, CmsSignatureContent):
10            print(f"  - Validation: {content.validation_time} from {content.validation_time_source.name}")
11            print(f"  - Hash      : {content.hash_algorithm.name}")
12            print("  - Signing Cert")
13            print_certificate(content.signing_certificate)
14            print("  - Chain")
15            for index, cert in enumerate(content.certificate_chain, start=1):
16                print(f"  - Issuer Cert {index}")
17                print_certificate(cert)
18            print(f"  - Chain     : {'complete' if content.certificate_chain.is_complete else 'incomplete'} chain")
19            print("  Time-Stamp")
20            print_signature_content(content.time_stamp)
21        elif isinstance(content, TimeStampContent):
22            print(f"  - Validation: {content.validation_time} from {content.validation_time_source.name}")
23            print(f"  - Hash      : {content.hash_algorithm.name}")
24            print(f"  - Time      : {content.date}")
25            print("  - Signing Cert")
26            print_certificate(content.signing_certificate)
27            print("  - Chain")
28            for index, cert in enumerate(content.certificate_chain, start=1):
29                print(f"  - Issuer Cert {index}")
30                print_certificate(cert)
31            print(f"  - Chain     : {'complete' if content.certificate_chain.is_complete else 'incomplete'} chain")
32        else:
33            print(f"Unsupported signature content type {str(type(content))}")
34    else:
35        print("  - null")
1def print_certificate(cert: Certificate):
2    if cert is not None:
3        print(f"    - Subject    : {cert.subject_name}")
4        print(f"    - Issuer     : {cert.issuer_name}")
5        print(f"    - Validity   : {cert.not_before} - {cert.not_after}")
6        try:
7            # Convert the list of integers to bytes
8            raw_data_bytes = bytes(cert.raw_data)
9
10            # Fingerprint calculation using hashlib
11            fingerprint = hashlib.sha1(raw_data_bytes).hexdigest().upper()
12            print(f"    - Fingerprint: {format_sha1_digest(fingerprint, '-')}")
13        except Exception as ex:
14            print(str(ex))
15        # Extract and print the individual DataSource names
16        sources = [source.name for source in DataSource if source in cert.source]
17        print(f"    - Source     : {', '.join(sources)}")
18        print(f"    - Validity   : {constraint_to_string(cert.validity.indication, cert.validity.sub_indication.name, cert.validity.message)}")
19    else:
20        print("    - null")
1def format_sha1_digest(fingerprint: str, delimiter: str):
2    return delimiter.join(fingerprint[i:i+2] for i in range(0, len(fingerprint), 2))
1def constraint_to_string(indication: Indication, sub_indication: str, message: str):
2    # Convert indication to a string based on its value
3    indication_str = (
4        "" if indication == Indication.VALID else
5        "?" if indication == Indication.INDETERMINATE else
6        "!"
7    )
8
9    # Return the formatted string
10    return f"{indication_str}{sub_indication} {message}"
Download code sample
1Function Validate(inputFile As String, certDir As String) As Integer
2    ' Use the default validation profile as a base for further settings
3    Dim profile = New PdfTools.SignatureValidation.Profiles.Default()
4
5    ' For offline operation, build a custom trust list from the file system 
6    ' and disable external revocation checks
7    If Not String.IsNullOrEmpty(certDir) Then
8        Console.WriteLine("Using 'offline' validation mode with custom trust list.")
9        Console.WriteLine()
10
11        ' create a CustomTrustList to hold the certificates
12        Dim ctl = New CustomTrustList()
13
14        ' Iterate through files in the certificate directory and add certificates
15        ' to the custom trust list
16        If Directory.Exists(certDir) Then
17            Dim directoryListing = Directory.EnumerateFiles(certDir)
18            For Each fileName In directoryListing
19                Try
20                    Using certStr = File.OpenRead(fileName)
21                        If fileName.EndsWith(".cer") OrElse fileName.EndsWith(".pem") Then
22                            ctl.AddCertificates(certStr)
23                        ElseIf fileName.EndsWith(".p12") OrElse fileName.EndsWith(".pfx") Then
24                            ' If a password is required, use addArchive(certStr, password).
25                            ctl.AddArchive(certStr)
26                        End If
27                    End Using
28                Catch e As Exception
29                    Console.WriteLine("Could not add certificate '" & fileName & "' to custom trust list: " & e.Message)
30                End Try
31            Next
32        Else
33            ' Handle the case where dir is not a directory
34            Console.WriteLine("Directory " & certDir & " is missing. No certificates were added to the custom trust list.")
35        End If
36        Console.WriteLine()
37
38        ' Assign the custom trust list to the validation profile
39        profile.CustomTrustList = ctl
40
41        ' Allow validation from embedded file sources and the custom trust list
42        Dim vo = profile.ValidationOptions
43        vo.TimeSource = TimeSource.ProofOfExistence Or TimeSource.ExpiredTimeStamp Or TimeSource.SignatureTime
44        vo.CertificateSources = DataSource.EmbedInSignature Or DataSource.EmbedInDocument Or DataSource.CustomTrustList
45
46        ' Disable revocation checks.
47        profile.SigningCertTrustConstraints.RevocationCheckPolicy = RevocationCheckPolicy.NoCheck
48        profile.TimeStampTrustConstraints.RevocationCheckPolicy = RevocationCheckPolicy.NoCheck
49    End If
50
51    ' Validate ALL signatures in the document (not only the latest)
52    Dim signatureSelector = SignatureValidation.SignatureSelector.All
53
54    ' Create the validator object and event listeners
55    Dim validator = New Validator()
56    AddHandler validator.Constraint, Sub(s, e)
57                                         Console.WriteLine("  - " & e.Signature.Name & If(e.DataPart.Length > 0, ": " & e.DataPart, "") & ": " &
58                                           ConstraintToString(e.Indication, e.SubIndication, e.Message))
59                                     End Sub
60
61    Try
62        Using inStr = File.OpenRead(inputFile)
63            ' Open input document
64            ' If a password is required, use Open(inStr, password)
65            Using document = Pdf.Document.Open(inStr)
66
67                ' Run the validate method passing the document, profile and selector
68                Console.WriteLine("Validation Constraints")
69                Dim results = validator.Validate(document, profile, signatureSelector)
70
71                Console.WriteLine()
72                Console.WriteLine("Signatures validated: " & results.Count)
73                Console.WriteLine()
74
75                ' Print results
76                For Each result In results
77                    Dim field = result.SignatureField
78                    Console.WriteLine(field.FieldName & " of " & field.Name)
79                    Try
80                        Console.WriteLine("  - Revision  : " & If(field.Revision.IsLatest, "latest", "intermediate"))
81                    Catch ex As Exception
82                        Console.WriteLine("Unable to validate document Revision: " & ex.Message)
83                    End Try
84
85                    PrintContent(result.SignatureContent)
86                    Console.WriteLine()
87                Next
88
89                Return 0
90            End Using
91        End Using
92    Catch ex As Exception
93        Console.WriteLine("Unable to validate file: " & ex.Message)
94        Return 5
95    End Try
96End Function
1' Helper functions to print signature validation details
2Private Sub PrintContent(content As SignatureContent)
3    If content IsNot Nothing Then
4        Console.WriteLine("  - Validity  : " & ConstraintToString(content.Validity))
5        If TypeOf content Is UnsupportedSignatureContent Then
6            ' Do nothing
7        ElseIf TypeOf content Is CmsSignatureContent Then
8            Dim signature As CmsSignatureContent = CType(content, CmsSignatureContent)
9            Console.WriteLine("  - Validation: " & signature.ValidationTime.ToString() & " from " & signature.ValidationTimeSource.ToString())
10            Console.WriteLine("  - Hash      : " & signature.HashAlgorithm.ToString())
11            Console.WriteLine("  - Signing Cert")
12            PrintContent(signature.SigningCertificate)
13            Console.WriteLine("  - Chain")
14            For Each cert In signature.CertificateChain
15                Console.WriteLine("  - Issuer Cert " & (signature.CertificateChain.IndexOf(cert) + 1))
16                PrintContent(cert)
17            Next
18            Console.WriteLine("  - Chain     : " & If(signature.CertificateChain.IsComplete, "complete", "incomplete") & " chain")
19            Console.WriteLine("  Time-Stamp")
20            PrintContent(signature.TimeStamp)
21        ElseIf TypeOf content Is TimeStampContent Then
22            Dim timeStamp As TimeStampContent = CType(content, TimeStampContent)
23            Console.WriteLine("  - Validation: " & timeStamp.ValidationTime.ToString() & " from " & timeStamp.ValidationTimeSource.ToString())
24            Console.WriteLine("  - Hash      : " & timeStamp.HashAlgorithm.ToString())
25            Console.WriteLine("  - Time      : " & timeStamp.Date.ToString())
26            Console.WriteLine("  - Signing Cert")
27            PrintContent(timeStamp.SigningCertificate)
28            Console.WriteLine("  - Chain")
29            For Each cert In timeStamp.CertificateChain
30                Console.WriteLine("  - Issuer Cert " & (timeStamp.CertificateChain.IndexOf(cert) + 1))
31                PrintContent(cert)
32            Next
33            Console.WriteLine("  - Chain      : " & If(timeStamp.CertificateChain.IsComplete, "complete", "incomplete") & " chain")
34        Else
35            Console.WriteLine("Unsupported signature content type " & content.GetType().Name)
36        End If
37    Else
38        Console.WriteLine("  - null")
39    End If
40End Sub
1Private Sub PrintContent(cert As Certificate)
2    If cert IsNot Nothing Then
3        Console.WriteLine("    - Subject    : " & cert.SubjectName)
4        Console.WriteLine("    - Issuer     : " & cert.IssuerName)
5        Console.WriteLine("    - Validity   : " & cert.NotBefore.ToString() & " - " & cert.NotAfter.ToString())
6        Try
7            Console.WriteLine("    - Fingerprint: " & FormatSha1Digest(New BigInteger(SHA1.Create().ComputeHash(cert.RawData)).ToByteArray(), "-"))
8        Catch ex As Exception
9            Console.WriteLine(ex.Message)
10        End Try
11        Console.WriteLine("    - Source     : " & cert.Source.ToString())
12        Console.WriteLine("    - Validity   : " & ConstraintToString(cert.Validity))
13    Else
14        Console.WriteLine("    - null")
15    End If
16End Sub
1Private Function ConstraintToString(constraint As ConstraintResult) As String
2    Return ConstraintToString(constraint.Indication, constraint.SubIndication, constraint.Message)
3End Function
1Private Function ConstraintToString(indication As Indication, subIndication As SubIndication, message As String) As String
2    Return If(indication = indication.Valid, "", If(indication = indication.Indeterminate, "?", "!")) & "" &
3        subIndication.ToString() & " " &
4        message
5End Function
1' Helper function to generate a delimited SHA-1 digest string
2Private Function FormatSha1Digest(bytes As Byte(), delimiter As String) As String
3    Dim result = New StringBuilder()
4    For Each aByte In bytes
5        Dim number = CInt(aByte) And &HFF
6        Dim hex = number.ToString("X2")
7        result.Append(hex.ToUpper() & delimiter)
8    Next
9    Return result.ToString().Substring(0, result.Length - delimiter.Length)
10End Function
Download code sample

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}
Download code sample
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}
Download code sample
1
2
3# Configure the SSL client certificate to connect to the service
4http_client_handler = HttpClientHandler()
5with io.FileIO("C:/path/to/clientcert.p12", 'rb') as cert_stream:
6    http_client_handler.set_client_certificate(cert_stream, "***insert password***")
7
8    # Connect to the Swisscom Signing Service
9    with Session("https://ais.swisscom.com", http_client_handler) as session:
10        # Add a document timestamp to a PDF
11        add_timestamp(session, identity, input_path, output_path)
12
1def add_timestamp(session: Session, identity: str, input_path: str, output_path: str):
2    # Create timestamp configuration
3    timestamp = session.create_timestamp(identity)
4
5    # Open input document
6    with io.FileIO(input_path, 'rb') as input_stream:
7        with Document.open(input_stream) as input_document:
8            # Create stream for output file
9            with io.FileIO(output_path, 'wb+') as output_stream:
10                # Add the document timestamp
11                signer = Signer()
12                signer.add_timestamp(input_document, timestamp, output_stream)
Download code sample
1' Configure the SSL client certificate to connect to the service
2Dim httpClientHandler = New HttpClientHandler()
3Using sslClientCert = File.OpenRead("C:\path\to\clientcert.p12")
4    httpClientHandler.SetClientCertificate(sslClientCert, "***insert password***")
5End Using
6
7' Connect to the Swisscom Signing Service
8Using session = New SwisscomSigSrv.Session(New Uri("https://ais.swisscom.com"), httpClientHandler)
9
10    ' Add a document time-stamp to a PDF
11    AddTimestamp(session, identity, inPath, outPath)
12End Using
1Sub AddTimestamp(session As SwisscomSigSrv.Session, identity As String, inPath As String, outPath As String)
2    ' Create time-stamp configuration
3    Dim timestamp = session.CreateTimestamp(identity)
4
5    ' Open input document
6    Using inStr = File.OpenRead(inPath)
7        Using inDoc = Document.Open(inStr)
8
9            ' Create stream for output file
10            Using outStr = File.Create(outPath)
11
12                ' Add the document time-stamp
13                Using outDoc = New Signer().AddTimestamp(inDoc, timestamp, outStr)
14                End Using
15            End Using
16        End Using
17    End Using
18End Sub
Download code sample

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}
Download code sample
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    SignatureConfiguration 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}
Download code sample
1
2
3# Configure the SSL client certificate to connect to the service
4http_client_handler = HttpClientHandler()
5with io.FileIO("C:/path/to/clientcert.p12", 'rb') as cert_stream:
6    http_client_handler.set_client_certificate(cert_stream, "***insert password***")
7
8    # Connect to the Swisscom Signing Service
9    with Session("https://ais.swisscom.com", http_client_handler) as session:
10        # Sign the PDF document
11        sign(session, identity, common_name, input_path, output_path)
12
1def sign(session: Session, identity: str, common_name: str, input_path: str, output_path: str):
2    # Create a signing certificate for a static identity
3    signature = session.create_signature_for_static_identity(identity, common_name)
4
5    # Embed validation information to enable the long-term validation (LTV) of the signature (default)
6    signature.embed_validation_information = True
7
8    # Open input document
9    with io.FileIO(input_path, 'rb') as input_stream:
10        with Document.open(input_stream) as input_document:
11            # Create stream for output file
12            with io.FileIO(output_path, 'wb+') as output_stream:
13                # Sign the document
14                signer = Signer()
15                signer.sign(input_document, signature, output_stream)
Download code sample
1' Configure the SSL client certificate to connect to the service
2Dim httpClientHandler = New HttpClientHandler()
3Using sslClientCert = File.OpenRead("C:\path\to\clientcert.p12")
4    httpClientHandler.SetClientCertificate(sslClientCert, "***insert password***")
5End Using
6
7' Connect to the Swisscom Signing Service
8Using session = New SwisscomSigSrv.Session(New Uri("https://ais.swisscom.com"), httpClientHandler)
9
10    ' Sign a PDF document
11    Sign(session, identity, commonName, inPath, outPath)
12End Using
1Sub Sign(session As SwisscomSigSrv.Session, identity As String, commonName As String, inPath As String, outPath As String)
2    ' Create a signing certificate for a static identity
3    Dim signature = session.CreateSignatureForStaticIdentity(identity, commonName)
4
5    ' Embed validation information to enable the long term validation (LTV) of the signature (default)
6    signature.EmbedValidationInformation = True
7
8    ' Open input document
9    Using inStr = File.OpenRead(inPath)
10        Using inDoc = Document.Open(inStr)
11
12            ' Create stream for output file
13            Using outStr = File.Create(outPath)
14
15                ' Sign the document
16                Using outDoc = New Signer().Sign(inDoc, signature, outStr)
17                End Using
18            End Using
19        End Using
20    End Using
21End Sub
Download code sample

Sign a PDF and add a visual appearance.

1static void Sign(string certificateFile, string password, string appConfigFile, string inPath, string outPath)
2{
3    // Create a session to the built-in cryptographic provider
4    using var session = new BuiltIn.Provider();
5
6    // Open certificate file
7    using var pfxStr = File.OpenRead(certificateFile);
8
9    // Create signature configuration from PFX (or P12) file
10    BuiltIn.SignatureConfiguration signature = session.CreateSignatureFromCertificate(pfxStr, password);
11
12    // Create appearance from either an XML or a json file
13    using var appStream = File.OpenRead(appConfigFile);
14    if (Path.GetExtension(appConfigFile) == ".xml")
15        signature.Appearance = Appearance.CreateFromXml(appStream);
16    else
17        signature.Appearance = Appearance.CreateFromJson(appStream);
18
19    signature.Appearance.PageNumber = 1;
20    signature.Appearance.CustomTextVariables.Add("company", "Daily Planet");
21
22    // Open input document
23    using var inStr = File.OpenRead(inPath);
24    using var inDoc = Document.Open(inStr);
25
26    // Create stream for output file
27    using var outStr = File.Create(outPath);
28
29    // Sign the input document
30    using var outDoc = new Signer().Sign(inDoc, signature, outStr);
31}
Download code sample
1private static void sign(String certificateFile, String password, String appConfigFile, 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        try (
14           // Create appearance from either an XML or a json file
15            FileStream appConfigStr = new FileStream(appConfigFile, FileStream.Mode.READ_ONLY))
16        {
17            if (appConfigFile.toLowerCase().endsWith(".xml"))
18                signature.setAppearance(Appearance.createFromXml(appConfigStr));
19            else
20                signature.setAppearance(Appearance.createFromJson(appConfigStr));
21
22            signature.getAppearance().setPageNumber(1);
23            signature.getAppearance().getCustomTextVariables().put("company", "Daily Planet");
24
25            try(
26                // Open input document
27                FileStream inStr = new FileStream(inPath, FileStream.Mode.READ_ONLY);
28                Document inDoc = Document.open(inStr);
29
30                // Create a stream for the output file
31                FileStream outStr = new FileStream(outPath, FileStream.Mode.READ_WRITE_NEW);
32
33                // Sign the input document
34                Document outDoc = new Signer().sign(inDoc, signature, outStr))
35            {
36            }
37        }
38    }
39}
Download code sample
1
2
3# Sign a PDF document
4sign(args.certificate_file, args.password, args.app_config_file, args.input_path, args.output_path)
5
1def sign(certificate_file: str, password: str, appearance_config_file: str, input_path: str, output_path: str):
2    # Create a session with the built-in cryptographic provider
3    with Provider() as session:
4        # Open certificate file
5        with io.FileIO(certificate_file, 'rb') as pfx_stream:
6            # Create signature configuration from PFX (or P12) file
7            signature = session.create_signature_from_certificate(pfx_stream, password)
8
9            # Create appearance from either an XML or JSON file
10            with io.FileIO(appearance_config_file, 'rb') as appearance_stream:
11                if appearance_config_file.endswith(".xml"):
12                    signature.appearance = Appearance.create_from_xml(appearance_stream)
13                else:
14                    signature.appearance = Appearance.create_from_json(appearance_stream)
15
16            signature.appearance.page_number = 1
17            signature.appearance.custom_text_variables["company"] = "Daily Planet"
18
19            # Open input document
20            with io.FileIO(input_path, 'rb') as input_stream:
21                with Document.open(input_stream) as input_document:
22                    # Create stream for output file
23                    with io.FileIO(output_path, 'wb+') as output_stream:
24                        # Sign the input document
25                        signer = Signer()
26                        signer.sign(input_document, signature, output_stream)
Download code sample
1Sub Sign(certificateFile As String, password As String, appConfigFile As String, inPath As String, outPath As String)
2    ' Create a session to the built-in cryptographic provider
3    Using session As New BuiltIn.Provider()
4
5        ' Open certificate file
6        Using pfxStr = File.OpenRead(certificateFile)
7
8            ' Create signature configuration from PFX (or P12) file
9            Dim signature As BuiltIn.SignatureConfiguration = session.CreateSignatureFromCertificate(pfxStr, password)
10
11            ' Create appearance from either an XML or a JSON file
12            Using appStream = File.OpenRead(appConfigFile)
13                If Path.GetExtension(appConfigFile) = ".xml" Then
14                    signature.Appearance = Appearance.CreateFromXml(appStream)
15                Else
16                    signature.Appearance = Appearance.CreateFromJson(appStream)
17                End If
18            End Using
19
20            signature.Appearance.PageNumber = 1
21            signature.Appearance.CustomTextVariables.Add("company", "Daily Planet")
22
23            ' Open input document
24            Using inStr = File.OpenRead(inPath)
25                Using inDoc = Document.Open(inStr)
26
27                    ' Create stream for output file
28                    Using outStr = File.Create(outPath)
29
30                        ' Sign the input document
31                        Using outDoc = New Signer().Sign(inDoc, signature, outStr)
32                        End Using
33                    End Using
34                End Using
35            End Using
36        End Using
37    End Using
38End Sub
Download code sample

Validate the conformance of documents

Validate the PDF conformance

1void ErrorListener(void* pContext, const TCHAR* szDataPart, const TCHAR* szMessage,
2                   TPdfToolsPdfAValidation_ErrorCategory iCategory, const TCHAR* szContext, int iPageNo, int iObjectNo)
3{
4    if (iPageNo > 0)
5        _tprintf(_T("- %d: %s (%s on page %d)\n"), iCategory, szMessage, szContext, iPageNo);
6    else
7        _tprintf(_T("- %d: %s (%s)\n"), iCategory, szMessage, szContext);
8}
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,
14                                     szErrBuf, PdfTools_GetLastError());
15
16    // Create a validator object that writes all validation error messages to the console
17    pValidator = PdfToolsPdfAValidation_Validator_New();
18    PdfToolsPdfAValidation_Validator_AddErrorHandler(pValidator, NULL,
19                                                     (TPdfToolsPdfAValidation_Validator_Error)ErrorListener);
20
21    // Validate the standard conformance of the document
22    pResult = PdfToolsPdfAValidation_Validator_Validate(pValidator, pInDoc, NULL);
23    GOTO_CLEANUP_IF_NULL_PRINT_ERROR(pResult, _T("Failed to validate document. %s (ErrorCode: 0x%08x).\n"), szErrBuf,
24                                     PdfTools_GetLastError());
25
26    // Report validation result
27    TPdfToolsPdf_Conformance iClaimedConformance;
28    PdfToolsPdf_Document_GetConformance(pInDoc, &iClaimedConformance);
29    if (PdfToolsPdfAValidation_ValidationResult_IsConforming(pResult))
30        printf("Document conforms to %s.\n", PdfToolsPdf_Conformance_ToStringA(iClaimedConformance));
31    else
32        printf("Document does not conform to %s.\n", PdfToolsPdf_Conformance_ToStringA(iClaimedConformance));
33
34cleanup:
35    PdfTools_Release(pResult);
36    PdfTools_Release(pValidator);
37    PdfToolsPdf_Document_Close(pInDoc);
38    if (pInStream)
39        fclose(pInStream);
40}
Download code sample
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}
Download code sample
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}
Download code sample
1def error_listener(context, data_part: str, message: str, category: ErrorCategory, context_text: str, page_no: int, object_no: int):
2    if page_no > 0:
3        print(f"- {category.name}: {message.decode()} ({context_text.decode()} on page {page_no})")
4    else:
5        print(f"- {category.name}: {message.decode()} ({context_text.decode()})")
1def validate(input_file_path: str):
2    # Open the document
3    with io.FileIO(input_file_path, 'rb') as in_stream:
4        with Document.open(in_stream) as input_document:
5            # Create a validator object that writes all validation error messages to the console
6            validator = Validator()
7            validator.add_error_handler(error_listener)
8
9            # Validate the standard conformance of the document
10            return validator.validate(input_document)
Download code sample
1Private Function Validate(inPath As String) As ValidationResult
2    ' Open the document
3    Using inStr = File.OpenRead(inPath)
4        Using inDoc = Document.Open(inStr)
5
6            ' Create a validator object that writes all validation error messages to the console
7            Dim validator = New Validator()
8            AddHandler validator.Error, Sub(s, e)
9                                            Console.WriteLine("- {0}: {1} ({2}{3})", e.Category, e.Message, e.Context, If(e.PageNo > 0, " on page" & e.PageNo, ""))
10                                        End Sub
11
12            ' Validate the standard conformance of the document
13            Return validator.Validate(inDoc)
14        End Using
15    End Using
16End Function
Download code sample