天天看點

C#, VB.NET如何加密PDF文檔

在日常工作中,人們通常通過加密PDF文檔的方式來保護PDF文檔。不管是公司還是個人,使用PDF加密術來設定一些權限是必不可少的。為了使PDF文檔既可讀又不能被未授權的使用者所更改,一份PDF文檔往往需要兩個密碼:所有者密碼和使用者密碼。本文我将給大家分享如何使用一個免費版PDF元件—Free Spire.PDF,以C#/VB.NET程式設計的方式來快速地加密PDF文檔。

這個免費版的PDF元件是由E-iceblue公司開發的,它可以通過設定所有者密碼和使用者密碼來加密PDF文檔。所有者密碼可以完全通路PDF文檔,例如重置密碼和權限;使用者密碼雖然可以允許使用者打開對應的PDF文檔,但也會受制于所有者設定的一些權限。

在加密方案中,命名空間Spire.PDFDocument.Security下的PDFSecurity類的執行個體對象用來設定所有者密碼和使用者密碼。

如果您對該元件感興趣,可以從官網下載下傳,元件下載下傳安裝後,再加載您的PDF文檔,然後就可以保護它了。

接下來我将介紹如何以C#/VB.NET程式設計的方式來加密PDF文檔:

步驟1:建立一個PDF文檔對象(因為我沒有現有的PDF文檔,是以就建立了一個)

[C#]

      PdfDocument doc = new PdfDocument();      

步驟2:通過“Spire.Pdf.Security.PdfEncryptionKeySize”的枚舉值來設定密鑰長度。密鑰長度有3種可用的類型:Key128Bit, Key256Bit 和 Key40Bit,您可以使用其中的任意一種。

[C#]

       doc.Security.KeySize = PdfEncryptionKeySize.Key256Bit;      

步驟3:通過設定所有者密碼和使用者密碼來加密PDF文檔。注意:您所設定的密鑰長度不能超過可用的密鑰長度。

[C#]

       doc.Security.OwnerPassword = "e-iceblue";
       doc.Security.UserPassword = "pdfcomponent";

       

步驟4:指定使用者密碼的通路權限。在此方案中,有9種可用的權限,請檢視下圖:

C#, VB.NET如何加密PDF文檔
[C#]

       doc.Security.Permissions = PdfPermissionsFlags.Print | PdfPermissionsFlags.CopyContent;      

步驟5:儲存文檔

[C#]

      doc.SaveToFile("result.pdf",FileFormat.PDF);      

項目運作後,當你打開這個加密的PDF文檔時就需要輸入密碼了。請看下面的效果截圖:

C#, VB.NET如何加密PDF文檔

C#完整代碼:

using Spire.Pdf;
using Spire.Pdf.Security;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace __encryption
{
    class Program
    {
        static void Main(string[] args)
        {
           PdfDocument doc = new PdfDocument();
           doc.Security.KeySize = PdfEncryptionKeySize.Key256Bit;
           doc.Security.OwnerPassword = "e-iceblue";
           doc.Security.UserPassword = "pdfcomponent";
           doc.Security.Permissions = PdfPermissionsFlags.Print | PdfPermissionsFlags.CopyContent;
           doc.SaveToFile("result.pdf", FileFormat.PDF);
        }
    }
}      

VB.NET完整代碼:

Imports Spire.Pdf
Imports Spire.Pdf.Security
Imports System.Collections.Generic
Imports System.Linq
Imports System.Text

Namespace __encryption
    Class Program
        Private Shared Sub Main(args As String())
            Dim doc As New PdfDocument()
            doc.Security.KeySize = PdfEncryptionKeySize.Key256Bit
            doc.Security.OwnerPassword = "e-iceblue"
            doc.Security.UserPassword = "pdfcomponent"
            doc.Security.Permissions = PdfPermissionsFlags.Print Or PdfPermissionsFlags.CopyContent
            doc.SaveToFile("result.pdf", FileFormat.PDF)
        End Sub
    End Class
End Namespace

      

希望這篇文章能給您帶來一定的幫助。感謝您的浏覽。

關于C# 加密、解密PDF的視訊教程,可點選連結位址檢視:

http://v.youku.com/v_show/id_XNDAyNzg3MTk5Ng==.html?spm=a2hzp.8244740.0.0