实现PDF文档加密,访问需要密码

01. 背景

今天下午老板神秘兮兮的来问我,能不能做个文档加密功能,就是那种用户下载打开需要密码才能打开的那种效果。boss都发话了,那必须可以。

  • 需求 :将pdf文档经过加密处理,客户下载pdf文档,打开文档需要密码验证。
  • 实现:.net8 + itext7 + 控制台,当然可以做成服务或者webapi接口。
  • 加密 :共有两个密码,一个是发行密码,通过这个密码可以解锁所有已发行pdf,还一个是用户密码,特定用户只能打开该用户的pdf文档。

02. 创建控制台

1、创建一个控制台应用程序。

03. 添加NeGet包

cs 复制代码
dotnet add package itext7
cs 复制代码
dotnet add itext7.bouncy-castle-adapte

04. 核心代码

cs 复制代码
 using iText.Kernel.Pdf;

// 获取当前工作目录
string currentDirectory = Environment.CurrentDirectory;
Console.WriteLine("Current Directory: " + currentDirectory);

// 构建文件路径
string filePath = System.IO.Path.Combine(currentDirectory, "test.pdf");
Console.WriteLine("File Path: " + filePath);

// 检查文件是否存在
if (File.Exists(filePath))
{

    #region pdf 加密
    string outputencryptedwordfile = "encrypted_test.pdf";
    string inputwordfile = "test.pdf";
    try
    {
        // 用户密码和所有者密码
        byte[] userPassword = System.Text.Encoding.UTF8.GetBytes("123456");
        byte[] ownerPassword = System.Text.Encoding.UTF8.GetBytes("123456");

        // 调用加密方法
        EncryptPdfFile(inputwordfile, outputencryptedwordfile, userPassword, ownerPassword);
    }
    catch (Exception ex)
    {
        Console.WriteLine("加密过程中发生错误: " + ex.Message);
    }
    #endregion
}
else
{
    Console.WriteLine("文件不存在");
}
static void EncryptPdfFile(string inputFile, string outputFile, byte[] userPassword, byte[] ownerPassword)
{
    // 定义加密权限
    int permissions = EncryptionConstants.ALLOW_PRINTING | EncryptionConstants.ALLOW_COPY;

    // 创建 PdfWriter 并设置加密参数
    WriterProperties writerProperties = new WriterProperties();
    writerProperties.SetStandardEncryption(
        userPassword,
        ownerPassword,
        permissions,
        EncryptionConstants.ENCRYPTION_AES_128
    );
    // 打开输入 PDF 文件
    using (PdfReader reader = new PdfReader(inputFile))
    using (PdfWriter writer = new PdfWriter(outputFile, writerProperties))
    using (PdfDocument pdfDoc = new PdfDocument(reader, writer))
    {
        // 复制页面(如果需要)
        // for (int i = 1; i <= pdfDoc.GetNumberOfPages(); i++)
        // {
        //     pdfDoc.CopyPagesTo(i, i, new PdfDocument(new PdfWriter(new MemoryStream())));
        // }
    }
}

05. 运行效果

06. 缺点关注,互粉

相关推荐
zhangfeng11334 小时前
R 导出 PDF 时中文不显示 不依赖 showtext** 的最简方案(用 extrafont 把系统 TTF 真正灌进 PDF 内核)
开发语言·r语言·pdf·生物信息
pc大老10 小时前
PDF文件翻译新方法:轻松多语言转换!
pdf·pdf文件·#pdf设置·pdf转换多国语言
SEO-狼术1 天前
Use Sticky Notes for Easier PDF Collaboration
pdf
私人珍藏库3 天前
[Windows] PDF 专业电子签章工具 v3.3
windows·pdf
广都--编程每日问4 天前
deepseek 的对话json导出成word和pdf
pdf·json·word·deepseek·exprot
livingbody4 天前
【2025年9月版 亲测可用】《人民日报》PDF文件下载
开发语言·爬虫·python·pdf
私人珍藏库4 天前
[Windows] 发票识别工具。支持xml、pdf、ofd文件
xml·pdf
超人在良家-阿启4 天前
PDF中表格的处理 (OCR)
pdf·ocr
reasonsummer4 天前
【办公类-115-01】20250920职称资料上传01——多个jpg转同名PDF(如:荣誉证书)并自动生成单一文件夹
pdf
孤客网络科技工作室6 天前
Python - 100天从新手到大师:第二十七天Python操作PDF文件
开发语言·python·pdf