【发布时间】:2015-03-09 23:15:02
【问题描述】:
我正在使用ITextSharp's PdfStamper 填写一个pdf表格。
这适用于未受保护和受密码保护的 Pdf,但受证书保护的 PDF 在调用 PdfStamper.Close() 时会导致 null reference exception。
以前有人遇到过这种情况吗?
失败程序示例:
using System.Security.Cryptography.X509Certificates;
using iTextSharp.text;
using iTextSharp.text.pdf;
using System.IO;
using Org.BouncyCastle.Crypto;
using X509Certificate = Org.BouncyCastle.X509.X509Certificate;
namespace ITextError
{
class Program
{
static X509Certificate2 certificate = new X509Certificate2(@"certificate.pfx","password",X509KeyStorageFlags.Exportable);
static X509Certificate bouncyCertficate = Org.BouncyCastle.Security.DotNetUtilities.FromX509Certificate(certificate);
static AsymmetricCipherKeyPair keyPair = Org.BouncyCastle.Security.DotNetUtilities.GetKeyPair(certificate.PrivateKey);
public static byte[] CreatePdf()
{
using (MemoryStream ms = new MemoryStream())
{
using (Document document = new Document())
{
var writer=PdfWriter.GetInstance(document, ms);
writer.SetEncryption(new X509Certificate[]{bouncyCertficate},
new int[]{PdfWriter.ALLOW_MODIFY_CONTENTS},
PdfWriter.STANDARD_ENCRYPTION_128
);
document.Open();
document.Add(new Paragraph("Hello World"));
}
return ms.ToArray();
}
}
public static byte[] StampPdf(byte[] src)
{
File.WriteAllBytes("tmp.pdf",src);
PdfReader reader = new PdfReader("tmp.pdf",bouncyCertficate,keyPair.Private);
using (MemoryStream ms = new MemoryStream())
{
using (PdfStamper stamper = new PdfStamper(reader, ms,reader.PdfVersion,true))
{
PdfContentByte canvas = stamper.GetOverContent(1);
ColumnText.ShowTextAligned(canvas, Element.ALIGN_LEFT, new Phrase("Hello people!"), 36, 540, 0);
stamper.Close();
}
return ms.ToArray();
}
}
static void Main(string[] args)
{
File.WriteAllBytes(@"output.pdf",StampPdf(CreatePdf()));
}
}
}
异常堆栈跟踪:
Unhandled Exception: System.NullReferenceException: Object reference not set to an instance of an object.
at iTextSharp.text.pdf.PdfEncryption.CreateInfoId(Byte[] id, Boolean modified)
at iTextSharp.text.pdf.PdfEncryption.GetFileID(Boolean modified)
at iTextSharp.text.pdf.PdfStamperImp.Close(PdfIndirectReference info, Int32 s kipInfo)
at iTextSharp.text.pdf.PdfStamperImp.Close(IDictionary`2 moreInfo)
at iTextSharp.text.pdf.PdfStamper.Close()
at ITextError.Program.StampPdf(Byte[] src) in Program.cs:line 45
at ITextError.Program.Main(String[] args) in Program.cs:line 53
只有当压模以附加模式打开时才会抛出异常。 但是不使用附加模式会删除我需要保留的原始保护。
ITextSharp 是 Nuget stable 的 5.5.4 版。
【问题讨论】:
-
请提供堆栈跟踪并指出您正在使用的库版本。
-
您是否拥有与用于保护 PDF 的公钥相对应的私钥?如果没有,那么这不是一个错误,这是一个预防措施。另外:当文件受密码保护时,如果不使用所有者密码或
unethicalreading,您将无法填写表格。如果是,则说明您使用的是过时的 iText 版本。 -
已编辑以包含失败代码和堆栈跟踪。我确实有私钥,但如果是预防措施,不应该抛出一个更友好的异常吗?
标签: c# itextsharp