【问题标题】:Password protected PDF using C#使用 C# 受密码保护的 PDF
【发布时间】:2026-02-18 22:20:02
【问题描述】:

我在我的过程中使用 C# 代码创建一个 pdf 文档。我需要保护文件 使用一些标准密码,如“123456”或一些帐号。我需要这样做 任何参考 dll,例如 pdf writer。

我正在使用 SQL Reporting Services 报告生成 PDF 文件。

有没有最简单的方法。

【问题讨论】:

    标签: c# pdf-generation


    【解决方案1】:

    我正在使用 C# 创建一个 pdf 文档 我的进程中的代码

    您是否正在使用某个库来创建此文档? pdf specification (8.6MB) 非常大,如果不使用第三方库,所有涉及 pdf 操作的任务都可能很困难。使用免费和开源的itextsharp 库对您的 pdf 文件进行密码保护和加密非常简单:

    using (Stream input = new FileStream("test.pdf", FileMode.Open, FileAccess.Read, FileShare.Read))
    using (Stream output = new FileStream("test_encrypted.pdf", FileMode.Create, FileAccess.Write, FileShare.None))
    {
        PdfReader reader = new PdfReader(input);
        PdfEncryptor.Encrypt(reader, output, true, "secret", "secret", PdfWriter.ALLOW_PRINTING);
    }
    

    【讨论】:

    • 请注意,itextsharp 需要用于商业用途的许可证,除非您的代码也在其使用的相同许可证下发布。价格仅在申请时提供。
    • 进一步注意,这个答案写于 2008 年,当时 iTextSharp 是在 LGPL 下发布的。在 5.0.0 版(2009 年 12 月,SVN 修订版 108;许可证更改为修订版 99)发布后,许可证更改为 AGPL,要求应用程序服务提供商发布源代码或购买商业许可证。以前的版本(4.1.6;LGPL)是 fork here 并且仍然具有上述功能。
    • 可惜这种加密太容易破解了。 codeproject.com/Articles/31493/PDF-Security-Remover
    【解决方案2】:

    如果不使用 PDF 库,将很难做到这一点。基本上,你需要自己开发这样的库。

    借助 PDF 库,一切都变得简单多了。以下示例展示了如何使用Docotic.Pdf library 轻松保护文档:

    public static void protectWithPassword(string input, string output)
    {
        using (PdfDocument doc = new PdfDocument(input))
        {
            // set owner password (a password required to change permissions)
            doc.OwnerPassword = "pass";
    
            // set empty user password (this will allow anyone to
            // view document without need to enter password)
            doc.UserPassword = "";
    
            // setup encryption algorithm
            doc.Encryption = PdfEncryptionAlgorithm.Aes128Bit;
    
            // [optionally] setup permissions
            doc.Permissions.CopyContents = false;
            doc.Permissions.ExtractContents = false;
    
            doc.Save(output);
        }
    }
    

    免责声明:我为图书馆的供应商工作。

    【讨论】:

      【解决方案3】:

      如果有人正在寻找 IText7 参考。

          private string password = "@d45235fewf";
          private const string pdfFile = @"C:\Temp\Old.pdf";
          private const string pdfFileOut = @"C:\Temp\New.pdf";
      
      public void DecryptPdf()
      {
              //Set reader properties and password
              ReaderProperties rp = new ReaderProperties();
              rp.SetPassword(new System.Text.UTF8Encoding().GetBytes(password));
      
              //Read the PDF and write to new pdf
              using (PdfReader reader = new PdfReader(pdfFile, rp))
              {
                  reader.SetUnethicalReading(true);
                  PdfDocument pdf = new PdfDocument(reader, new PdfWriter(pdfFileOut));
                  pdf.GetFirstPage(); // Get at the very least the first page
              }               
      } 
      

      【讨论】: