2008-12-16 47 views
14

我正在使用C#代码在我的过程中创建PDF文档。我需要使用一些标准密码(如“123456”或某个帐号)来保护文档 。我需要这样做,没有 任何参考dll像PDF编写器。使用C#密码保护PDF使用C#

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

有没有最简单的方法。

回答

21

我创造

您是否使用了一些库来创建这个文件使用C#代码 我在处理PDF文档? pdf specification(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); 
} 
+4

请注意,itextsharp需要一个用于商业用途的许可证,除非您的代码也在其使用的相同许可证下发布。价格只适用于申请。 – Spongeboy 2012-06-21 07:34:42

1

这将是非常很难做到这一点,而无需使用PDF库。基本上,你需要自己开发这样的图书馆。

在PDF库的帮助下,一切都非常简单。这里展示了如何文档可以很容易地使用Docotic.Pdf library被保护的样本:

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); 
    } 
} 

声明:我在图书馆的供应商合作。