Add Password Protection To Word Or PDF Files In C#
Things are going digital. There are outstanding products/tools to pull you into the paperless era. We share information across the companies or anywhere in the form of different file formats. It could be a Spreadsheet, PDF, or any of the MS Office formats. But the biggest threat is security. Let’s understand this with a use-case.
You want to secure a Word or PDF file on a machine where MS Office or Adobe PDF is not installed, in that case, you need a tool or API that can secure such documents programmatically without any dependency.
There are a few APIs/tools that provide the facility to secure a lot of file formats. Have a look at the GroupDocs.Merger for .NET code below.
string password = "iamironman";
Stream openFile = new FileStream(sourceFile, FileMode.Open);
DocumentResult result = new DocumentHandler().AddPassword(openFile, password);
Stream documentStream = result.Stream;
One interesting thing about this API is that it gives you two options,
- Pass a source file and specify its extension as well and save output/protected file with the same extension (source: “test.pdf”, output: “test.pdf”)
- Secondly, you can pass the source file and for the output you just have to specify the file name and API will detect file extension on its own based on the source file (source: “test.pdf”, output: “test.”+result.FileFormat)
Download and explore open-source example project.