使用C#创建密码保护的PDF文件

17

我正在使用C#代码创建PDF文档。我需要使用一些标准密码(如“123456”或一些帐户号码)来保护文档。我需要在不使用任何类似于pdf writer的参考dll的情况下完成此操作。

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

是否有更简单的方法。

3个回答

30

我正在使用C#代码创建PDF文档。

你是否在使用某个库来创建此文档?PDF规范(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);
}

7
请注意,itextsharp在商业使用时需要许可证,除非您的代码也在相同许可证下发布。价格仅在申请后才可获得。 - Spongeboy
2
请注意,此答案是在2008年编写的,当时iTextSharp是在LGPL下发布的。在版本5.0.0发布后(2009年12月,SVN修订版108;许可证更改在修订版99),许可证已更改为AGPL,要求应用程序服务提供商发布源代码或购买商业许可证。以前的版本(4.1.6;LGPL)在此处被分叉[https://github.com/itextsharper/iTextSharp-4.1.6],并且仍具有上述功能。 - Brian Parks
1
很遗憾,这个加密方式太容易被破解了。http://www.codeproject.com/Articles/31493/PDF-Security-Remover - Diego

1

如果不使用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);
    }
}

免责声明:我是该库的供应商。


这个库是免费的还是收费的? - Akalanka Ekanayake
@AkalankaEkanayake 在某些情况下,该库可以免费使用,但在一般情况下,您需要支付许可证费用。 - Bobrovsky

0

如果有人正在寻找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
        }               
} 

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接