溫馨提示×

itext c#如何處理加密PDF

c#
小樊
131
2024-12-12 22:46:07
欄目: 編程語言

iText 是一個用于處理 PDF 文件的庫,它提供了許多功能,包括創建、編輯、加密和解密 PDF 文件。要在 C# 中使用 iText 處理加密的 PDF 文件,你需要使用 iText 7。以下是一個簡單的示例,說明如何使用 iText 7 對 PDF 文件進行加密和解密:

首先,確保已安裝 iText 7 庫。你可以通過 NuGet 包管理器安裝 iText 7:

Install-Package iText.Kernel
Install-Package iText.Layout
Install-Package iText.Crypto

接下來,創建一個 C# 控制臺應用程序并添加以下代碼:

using System;
using System.IO;
using iText.Kernel.Pdf;
using iText.Kernel.Pdf.Encryption;
using iText.Layout;

namespace EncryptAndDecryptPDF
{
    class Program
    {
        static void Main(string[] args)
        {
            string inputPath = "input.pdf"; // 輸入 PDF 文件路徑
            string outputPath = "output.pdf"; // 輸出 PDF 文件路徑
            string password = "your_password"; // 密碼

            // 加密 PDF 文件
            EncryptPdf(inputPath, outputPath, password);

            // 解密 PDF 文件
            DecryptPdf(outputPath, password);
        }

        static void EncryptPdf(string inputPath, string outputPath, string password)
        {
            using (PdfReader reader = new PdfReader(inputPath))
            {
                using (PdfWriter writer = new PdfWriter(outputPath, new WriterProperties().SetStandardEncryption(password.GetBytes(), password.Length, EncryptionConstants.ALLOW_PRINTING | EncryptionConstants.ALLOW_COPY)))
                {
                    writer.Write(reader);
                }
            }
        }

        static void DecryptPdf(string inputPath, string password)
        {
            using (PdfReader reader = new PdfReader(inputPath, password.GetBytes()))
            {
                using (PdfWriter writer = new PdfWriter(new OutputStreamWriter(Console.OpenStandardOutput())))
                {
                    writer.Write(reader);
                }
            }
        }
    }
}

在這個示例中,我們首先定義了輸入 PDF 文件的路徑(inputPath)、輸出 PDF 文件的路徑(outputPath)和密碼(password)。然后,我們使用 EncryptPdf 方法對 PDF 文件進行加密,并將加密后的文件保存到 outputPath。最后,我們使用 DecryptPdf 方法對加密后的 PDF 文件進行解密,并將解密后的文件輸出到控制臺。

請注意,這個示例僅用于演示目的。在實際應用中,你可能需要根據需求對代碼進行調整。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女