c#-4.0 - 使用 iText 7 打开带有非 ASCII 字符的受密码保护的 PDF 文件
问题描述
我在我的 Dot Net 4 / C# 项目中使用 iText 7(版本 7.1.7)并处理具有用户密码的 PDF 文档。
密码已提供,一切工作正常,除了在密码中使用非 ASCII 字符(如 £ 符号)时。
有谁知道让 iText 7 理解像“hello£1234”这样的密码的方法?
我已经尝试通过将我的字符串视为 UTF8 或 Unicode 来提取密码字节,但似乎没有什么对我有用。
在我尝试加载 PdfDocument 时,我只是得到一个“错误的用户密码”异常
这是我的代码:
string password = "hello£1234";
byte[] passwordBytes = new System.Text.ASCIIEncoding().GetBytes(password);
PdfReader reader = new PdfReader(tempInFile, new ReaderProperties().SetPassword(passwordBytes));
PdfDocument pdfDoc = new PdfDocument(reader);
// Do my stuff with the document here
pdfDoc.Close();
解决方案
我以为我在使用系统的默认代码页时找到了答案,但结果并不是 100% 有效
普通 ASCII 不能表示像 £ 这样的字符,但扩展 ASCII(或代码页 437)可以。UTF8 也可以,但不同类型的编码似乎适用于不同的环境。
目前,我的解决方案只是尝试一些。这是一种攻城略地的方法,所以如果有人有更优雅的解决方案,那么我很想看看它。
这是我现在的代码:
Encoding cp437 = Encoding.GetEncoding(437);
List<byte[]> passwordByteList = new List<byte[]>()
{
Encoding.Default.GetBytes(password), //Default codepage
Encoding.UTF8.GetBytes(password), //UTF8 encoding
cp437.GetBytes(password), //Code page 437 (extended ASCII) encoding
};
foreach(byte[] passwordBytes in passwordByteList)
{
PdfReader reader = new PdfReader(tempInFile, new ReaderProperties().SetPassword(passwordBytes));
try
{
//Try to open the PDF with the password
PdfDocument pdfDoc = new PdfDocument(reader);
//Do something with the document
pdfDoc.Close();
reader.Close();
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex.ToString());
//Exception thrown by PDF reader. We need to try the next password.
reader.Close();
}
}
推荐阅读
- javascript - 如何禁用故事书的键盘快捷键
- mongodb - 使用两个匹配的文件查询 DynamoDB
- python - 如何有效地处理两个python数据帧?
- laravel - 如何将 Laravel 更新到 6?
- r - 使用 dplyr 滚动逐步回归
- reactjs - 如何在 this.state Reactjs 中存储 map() 函数返回的组件数组
- angular - 为什么 {descendants: true} 在 ContentChildren 中不起作用?
- node.js - net.createserver 上的节点 JS 事件发射器
- haskell - 在 Haskell 中有条件地折叠列表的简洁语法
- python - 将整数值从 RPi 串行发送到 Arduino