实现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. 缺点关注,互粉

相关推荐
wsxqaz41 分钟前
浏览器原生控件上传PDF导致hash值不同
算法·pdf·哈希算法
工业3D_大熊10 天前
3D模式格式转换工具HOOPS Exchange如何将3D PDF转换为STEP格式?
3d·pdf·3d格式转换·3d模型格式转换·cad格式转换·cad数据格式转换·3d模型可视化
IDRSolutions_CN10 天前
在 Java 中生成 PDF 缩略图(教程)
java·经验分享·pdf·软件工程·团队开发
IDRSolutions_CN10 天前
用Java将PDF转换成GIF
java·经验分享·pdf·软件工程·团队开发
贤和兄10 天前
使用docx4j 实现word转pdf(linux乱码处理)
linux·pdf·word
Eiceblue11 天前
高效打印 PDF 文档:基础操作与自动打印(含C# .NET方案)
pdf·c#·.net
沉到海底去吧Go11 天前
【工具教程】PDF指定区域OCR识别重命名工具使用教程和注意事项
pdf·ocr·图片区域识别改名·仓储物流单据识别·物流单据识别改名·pdf区域识别改名·pdf区域识别重命名
KWMax11 天前
RSA加密原理及推导
加密·rsa
开开心心就好11 天前
高效批量转换Word到PDF的方法
javascript·安全·智能手机·pdf·word·objective-c·lisp
response_L11 天前
麒麟v10、uos系统在线批量生成pdf文件
java·pdf·word·pageoffice·在线编辑