2008-12-16 48 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); 
    } 
} 

聲明:我在圖書館的供應商合作。