需要使用 itext-dotnet :https://github.com/itext/itext-dotnet
使用Nuget:
Install-Package itext
Install-Package itext.bouncy-castle-adapter
使用密碼加密PDF:
public static bool EncryptPdf(string inputPath, string outputPath) { bool result = false; try { string pdfUserPassword = "1234"; string pdfOwnerPassword = "5678"; WriterProperties wp = new WriterProperties(); wp.SetStandardEncryption(Encoding.Default.GetBytes(pdfUserPassword), Encoding.Default.GetBytes(pdfOwnerPassword), EncryptionConstants.ALLOW_PRINTING, EncryptionConstants.ENCRYPTION_AES_256); using (FileStream pdfStream = new FileStream(outputPath, FileMode.Create)) { using (var existingPdf = new PdfReader(inputPath)) { using (PdfWriter newPdf = new PdfWriter(pdfStream, wp)) { using (PdfDocument pdfDocument = new PdfDocument(existingPdf, newPdf)) { pdfDocument.Close(); } } } } result = true; } catch (Exception e) { Console.WriteLine($"error:{e}"); } return result; }
EncryptionConstants 的值見文檔:
在控制器調用後:
public IActionResult Index() { bool result = PdfHelper.EncryptPdf("F:\\pdf\\compressed.tracemonkey-pldi-09.pdf", "F:\\pdf\\compressed.tracemonkey-pldi-15.pdf"); return Content(result.ToString()); }
打開生成的 PDF ,提示口令:
輸入用戶口令後,看下文檔的 屬性 -- 安全性
和我們設置允許用戶打印的權限一致
當我們進行其他操作時,會再次提示輸入口令
如果輸入的管理員口令,再次查看文檔的 屬性-- 安全性
可以發現功能可以使用
如果只是限制功能,設置用戶密碼爲 NULL 就可以了,權限設置爲 0,則禁止所有權限,寫法如下:
wp.SetStandardEncryption(null, Encoding.Default.GetBytes(pdfOwnerPassword), 0, EncryptionConstants.ENCRYPTION_AES_256);
看下文檔安全性:
上面可以看到,如果設置用戶密碼爲 NULL,則文檔不需要密碼即可打開,權限按照程序設置爲準
如果設置管理密碼也爲 NULL,則 iText 則會生成一個隨機密碼,iText的實現如下:
if (ownerPassword != null) { this.ownerPassword = ownerPassword; } else { this.ownerPassword = new byte[16]; EncryptionProperties.RandomBytes(this.ownerPassword); }
所以當自己也不想知道管理密碼的時候,可以直接:
wp.SetStandardEncryption(null, null, 0, EncryptionConstants.ENCRYPTION_AES_256);