软件编程
位置:首页>> 软件编程>> C#编程>> C# 对PDF文档加密、解密(基于Spire.Cloud.SDK for .NET)

C# 对PDF文档加密、解密(基于Spire.Cloud.SDK for .NET)

作者:E-iceblue  发布时间:2021-11-23 05:37:26 

标签:c#,pdf,加密,解密

Spire.Cloud.SDK for .NET提供了接口PdfSecurityApi可用于加密、解密PDF文档。本文将通过C#代码演示具体加密及解密方法。

使用工具:

  • Spire.Cloud.SDK for .NET

  • Visual Studio

必要步骤:

步骤一:

dll文件获取及导入。在程序中通过Nuget搜索下载,直接导入所有dll。

导入效果如下如所示:

C# 对PDF文档加密、解密(基于Spire.Cloud.SDK for .NET)

步骤二:

App ID及Key获取。在“我的应用”板块中创建应用以获得App ID及App Key。

C# 对PDF文档加密、解密(基于Spire.Cloud.SDK for .NET)

步骤三:

源文档上传。在“文档管理”板块,上传源文档。这里可以建文件夹,将文档存放在文件夹下。不建文件夹时,源文档及结果文档直接保存在根目录。本文示例中,建了两个文件夹,分别用于存放源文档及结果文档。(云平台提供免费1 万次调用次数和 2G 文档内存)

C# 对PDF文档加密、解密(基于Spire.Cloud.SDK for .NET)

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

生成的文档打开时,需要输入密码。

文档加密结果:

C# 对PDF文档加密、解密(基于Spire.Cloud.SDK for .NET)

【示例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.cnblogs.com/Yesi/p/13156354.html

0
投稿

猜你喜欢

手机版 软件编程 asp之家 www.aspxhome.com