使用C#密码保护PDF

我正在使用C#代码创建一个pdf文档。 我需要用一些标准密码来保护docuemnt,比如“123456”或某个帐号。 我需要这样做,没有像pdf writer这样的参考dll。

我正在使用SQL Reporting Services报告生成PDF文件。

有最简单的方法吗?

我正在使用C#代码创建一个pdf文档

您是否使用某些库来创建此文档? pdf规范 (8.6MB)非常大,如果不使用第三方库,所有涉及pdf操作的任务都很困难。 使用免费和开源的itextsharp库密码保护和加密您的pdf文件非常简单:

using (Stream input = new FileStream("test.pdf", FileMode.Open, FileAccess.Read, FileShare.Read)) using (Stream output = new FileStream("test_encrypted.pdf", FileMode.Create, FileAccess.Write, FileShare.None)) { PdfReader reader = new PdfReader(input); PdfEncryptor.Encrypt(reader, output, true, "secret", "secret", PdfWriter.ALLOW_PRINTING); } 

如果不使用PDF库,这将是非常困难的。 基本上,你需要自己开发这样的库。

借助PDF库,一切都变得更加简单。 以下示例显示了如何使用Docotic.Pdf库轻松保护文档:

 public static void protectWithPassword(string input, string output) { using (PdfDocument doc = new PdfDocument(input)) { // set owner password (a password required to change permissions) doc.OwnerPassword = "pass"; // set empty user password (this will allow anyone to // view document without need to enter password) doc.UserPassword = ""; // setup encryption algorithm doc.Encryption = PdfEncryptionAlgorithm.Aes128Bit; // [optionally] setup permissions doc.Permissions.CopyContents = false; doc.Permissions.ExtractContents = false; doc.Save(output); } } 

免责声明:我为图书馆的供应商工作。

如果有人正在寻找IText7参考。

  private string password = "@d45235fewf"; private const string pdfFile = @"C:\Temp\Old.pdf"; private const string pdfFileOut = @"C:\Temp\New.pdf"; public void DecryptPdf() { //Set reader properties and password ReaderProperties rp = new ReaderProperties(); rp.SetPassword(new System.Text.UTF8Encoding().GetBytes(password)); //Read the PDF and write to new pdf using (PdfReader reader = new PdfReader(pdfFile, rp)) { reader.SetUnethicalReading(true); PdfDocument pdf = new PdfDocument(reader, new PdfWriter(pdfFileOut)); pdf.GetFirstPage(); // Get at the very least the first page } }