The following example demonstrates how to encrypt a PDF document by adding a password. It covers both how to add a user password & an owner password.
| Encrypt a PDF document using a password |
Copy Code |
|---|---|
public static void SaveWithPassword() { Console.WriteLine( "=== SAVE WITH PASSWORD ===" ); var outputFileName = "SaveWithPassword.pdf"; var outputPath = EncryptionsSample.EncryptionsSampleOutputDirectory + outputFileName; // Creates a PdfDocument. using( var pdfoutput = PdfDocument.Create( outputPath ) ) { // Gets the first Page. var page = pdfoutput.Pages.First(); // Adds a title. var textStyle = TextStyle.WithFont( pdfoutput.Fonts.GetStandardFont( StandardFontType.Helvetica ), 15d ); page.AddParagraph( "Save Document With Password", textStyle, new ParagraphStyle( ParagraphHorizontalAlignment.Center ) ); // Defines a TextStyle that will be used to add the text. var textFont = pdfoutput.Fonts.GetStandardFont( StandardFontType.Courier ); // Adds text at a specific position with a font and size. page.AddText( "This page is encrypted with password : owner", new Point( 75, 100 ), TextStyle.WithFont( textFont, 15 ) ); // Define the password to use for encrypting this Pdf document. var encryptionOptions = new EncryptionOptions() { // User password will be necessary to open the saved document. UserPassword = "user", // Owner password will be necessary to modify the saved document. OwnerPassword = "owner", // Set the wanted Profile for encryption. Profile = EncryptionProfile.Aes128, // Set the allowed Permissions for the PDF Document. Permissions = Permissions.Print | Permissions.CopyContent | Permissions.AccessibilityCopyContent }; // Create the save options and include the new encryption options. var saveOptions = new SaveOptions() { Encryption = encryptionOptions }; // Saves the output document. pdfoutput.Save( saveOptions ); Console.WriteLine( $"Info exported to path: {outputFileName}" ); } } | |