我正在使用C#代码创建PDF文档。我需要使用一些标准密码(如“123456”或一些帐户号码)来保护文档。我需要在不使用任何类似于pdf writer的参考dll的情况下完成此操作。
我正在使用SQL Reporting服务报告生成PDF文件。
是否有更简单的方法。
我正在使用C#代码创建PDF文档。我需要使用一些标准密码(如“123456”或一些帐户号码)来保护文档。我需要在不使用任何类似于pdf writer的参考dll的情况下完成此操作。
我正在使用SQL Reporting服务报告生成PDF文件。
是否有更简单的方法。
我正在使用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);
}
如果不使用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);
}
}
免责声明:我是该库的供应商。
如果有人正在寻找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
}
}