Encrypt & Decrypt PDFs - Go Sample Code

Sample code for using Apryse SDK to read encrypted (password protected) documents, secure a document with encryption, or remove encryption. Samples provided in Python, C++, C#, Java, Node.js (JavaScript), PHP, Ruby, Go and VB. Learn more about our Server SDK.

1//---------------------------------------------------------------------------------------
2// Copyright (c) 2001-2021 by PDFTron Systems Inc. All Rights Reserved.
3// Consult LICENSE.txt regarding license information.
4//---------------------------------------------------------------------------------------
5
6package main
7import (
8 "fmt"
9 "strconv"
10 . "pdftron"
11)
12
13import "pdftron/Samples/LicenseKey/GO"
14
15//---------------------------------------------------------------------------------------
16// This sample shows encryption support in PDFNet. The sample reads an encrypted document and
17// sets a new SecurityHandler. The sample also illustrates how password protection can
18// be removed from an existing PDF document.
19//---------------------------------------------------------------------------------------
20
21func main(){
22 PDFNetInitialize(PDFTronLicense.Key)
23
24 // Relative path to the folder containing the test files.
25 inputPath := "../../TestFiles/"
26 outputPath := "../../TestFiles/Output/"
27
28 // Example 1:
29 // secure a PDF document with password protection and adjust permissions
30
31 // Open the test file
32 fmt.Println("Securing an existing document...")
33
34 doc := NewPDFDoc(inputPath + "fish.pdf")
35 doc.InitSecurityHandler()
36
37 // Perform some operation on the document. In this case we use low level SDF API
38 // to replace the content stream of the first page with contents of file 'my_stream.txt'
39 if true{ // Optional
40 fmt.Println("Replacing the content stream, use Flate compression...")
41
42 // Get the page dictionary using the following path: trailer/Root/Pages/Kids/0
43 pageDict := (doc.GetTrailer().Get("Root").Value().Get("Pages").Value().Get("Kids").Value().GetAt(0))
44
45 // Embed a custom stream (file mystream.txt) using Flate compression.
46 embedFile := NewMappedFile(inputPath + "my_stream.txt")
47 mystm := NewFilterReader(embedFile)
48 pageDict.Put("Contents", doc.CreateIndirectStream(mystm, NewFilter()))
49 }
50 // encrypt the document
51
52 // Apply a new security handler with given security settings.
53 // In order to open saved PDF you will need a user password 'test'.
54 newHandler := NewSecurityHandler()
55
56 // Set a new password required to open a document
57 userPassword := "test"
58 newHandler.ChangeUserPassword(userPassword)
59
60 // Set permissions
61 newHandler.SetPermission(SecurityHandlerE_print, true)
62 newHandler.SetPermission(SecurityHandlerE_extract_content, false)
63
64 // Note: document takes the ownership of newHandler.
65 doc.SetSecurityHandler(newHandler)
66
67 // save the changes.
68 fmt.Println("Saving modified file...")
69 doc.Save(outputPath + "secured.pdf", uint(0))
70 doc.Close()
71
72 // Example 2:
73 // Opens an encrypted PDF document and removes its security.
74
75 doc = NewPDFDoc(outputPath + "secured.pdf")
76
77 // If the document is encrypted prompt for the password
78 if !doc.InitSecurityHandler(){
79 success := false
80 fmt.Println("The password is: test")
81 count := 0
82 for count < 3{
83 fmt.Println("A password required to open the document.")
84 var password string
85 fmt.Print("Please enter the password: \n")
86 fmt.Scanf("%s", &password)
87 fmt.Println(password)
88
89 if doc.InitStdSecurityHandler(password, len(password)){
90 success = true
91 fmt.Println("The password is correct.")
92 break
93 }else if count < 3{
94 fmt.Println("The password is incorrect, please try again")
95 }
96 count = count + 1
97 }
98 if !success{
99 fmt.Println("Document authentication error....")
100 return
101 }
102 hdlr := doc.GetSecurityHandler()
103 fmt.Println("Document Open Password: " + strconv.FormatBool(hdlr.IsUserPasswordRequired()))
104 fmt.Println("Permissions Password: " + strconv.FormatBool(hdlr.IsMasterPasswordRequired()))
105 fmt.Println(("Permissions: " +
106 "\n\tHas 'owner' permissions: " + strconv.FormatBool(hdlr.GetPermission(SecurityHandlerE_owner)) +
107 "\n\tOpen and decrypt the document: " + strconv.FormatBool(hdlr.GetPermission(SecurityHandlerE_doc_open)) +
108 "\n\tAllow content extraction: " + strconv.FormatBool(hdlr.GetPermission(SecurityHandlerE_extract_content)) +
109 "\n\tAllow full document editing: " + strconv.FormatBool(hdlr.GetPermission(SecurityHandlerE_doc_modify) ) +
110 "\n\tAllow printing: " + strconv.FormatBool(hdlr.GetPermission(SecurityHandlerE_print)) +
111 "\n\tAllow high resolution printing: " + strconv.FormatBool(hdlr.GetPermission(SecurityHandlerE_print_high)) +
112 "\n\tAllow annotation editing: " + strconv.FormatBool(hdlr.GetPermission(SecurityHandlerE_mod_annot)) +
113 "\n\tAllow form fill: " + strconv.FormatBool(hdlr.GetPermission(SecurityHandlerE_fill_forms)) +
114 "\n\tAllow content extraction for accessibility: " + strconv.FormatBool(hdlr.GetPermission(SecurityHandlerE_access_support)) +
115 "\n\tAllow document assembly: " + strconv.FormatBool(hdlr.GetPermission(SecurityHandlerE_assemble_doc))))
116 }
117
118 // remove all security on the document
119 doc.RemoveSecurity()
120 doc.Save(outputPath + "not_secured.pdf", uint(0))
121 doc.Close()
122
123 PDFNetTerminate()
124 fmt.Println("Test completed.")
125}

Did you find this helpful?

Trial setup questions?

Ask experts on Discord

Need other help?

Contact Support

Pricing or product questions?

Contact Sales