C# 加密、解密PDF文檔(基於Spire.Cloud.PDF.SDK)

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 = "//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 = "//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);
        }     
    }
}

生成的文檔將不再有密碼保護。

 

(完)