Spire.Cloud.SDK for .NET提供了介面PdfSecurityApi可用于加密、解密PDF檔案,本文將通過C#代碼演示具體加密及解密方法,
使用工具:
- Spire.Cloud.SDK for .NET
- Visual Studio
必要步驟:
步驟一:dll檔案獲取及匯入,在程式中通過Nuget搜索下載,直接匯入所有dll,
匯入效果如下如所示:

步驟二:App ID及Key獲取,在“我的應用”板塊中創建應用以獲得App ID及App Key,

步驟三:源檔案上傳,在“檔案管理”板塊,上傳源檔案,這里可以建檔案夾,將檔案存放在檔案夾下,不建檔案夾時,源檔案及結果檔案直接保存在根目錄,本文示例中,建了兩個檔案夾,分別用于存放源檔案及結果檔案,(云平臺提供免費1 萬次呼叫次數和 2G 檔案記憶體)

C# 代碼示例
【示例1】加密PDF檔案
using System; using Spire.Cloud.Pdf.Sdk.Client; using Spire.Cloud.Pdf.Sdk.Api; using System.IO; using System.Collections.Generic; namespace Encryt { class Program { //配置賬號資訊 static String appId = "App ID"; static String appKey = "App Key"; static String baseUrl = "https://api.e-iceblue.cn"; static Configuration PdfConfiguration = new Configuration(appId, appKey, baseUrl); static PdfSecurityApi PdfSecurityApi = new PdfSecurityApi(PdfConfiguration); static void Main(string[] args) { string name = "sample.pdf";//源檔案 string destFilePath = "pdfsecurity/Encrypt.pdf";//結果檔案路徑(將結果檔案存放在pdfsecurity檔案夾下) string userPassword = "123";//設定用戶密碼 string ownerPassword = "321";//設定所有者密碼 string keySize = "Key40Bit";//設定keySize(如果不需要設定,可設定為null) List<string> permissionsFlags = new List<string>();//設定permissionsFlags(如果不需要設定,可設定為null) permissionsFlags.Add("Print"); string folder = "input";//源檔案所在檔案夾 string password = null;//源檔案密碼 string storage = null; //呼叫方法加密檔案 PdfSecurityApi.EncryptDocumentInStorage(name,destFilePath,userPassword,ownerPassword,keySize,permissionsFlags,folder,storage,password); } } }
生成的檔案打開時,需要輸入密碼,
檔案加密結果:

【示例2】解密PDF檔案
這里以上文中生成的加密PDF為測驗檔案,
using System; using Spire.Cloud.Pdf.Sdk.Client; using Spire.Cloud.Pdf.Sdk.Api; namespace Decrypt { class Program { //配置賬號資訊 static String appId = "App ID"; static String appKey = "App Key"; static String baseUrl = "https://api.e-iceblue.cn"; static Configuration PdfConfiguration = new Configuration(appId, appKey, baseUrl); static PdfSecurityApi PdfSecurityApi = new PdfSecurityApi(PdfConfiguration); static void Main(string[] args) { string name = "Encrypt.pdf";//源檔案 string destFilePath = "pdfsecurity/Decrypt.pdf";//結果檔案路徑(pdfsecurity為結果檔案所在檔案夾) string password = "321";//檔案密碼(這里需要使用的是ownerpassword) string folder = "pdfsecurity";//源檔案所在檔案夾 string storage = null; //呼叫方法解密檔案 PdfSecurityApi.DecryptDocumentInStorage(name,destFilePath,password,folder,storage); } } }
生成的檔案將不再有密碼保護,
(完)
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/17078.html
標籤:C#
上一篇:【asp.net core 系列】10 實戰之ActionFilter
下一篇:C#委托
