【发布时间】:2018-01-31 10:00:16
【问题描述】:
我有一个 pdf(byte) 存储在数据库表中,我还在数据库表中存储了图像(byte)。
现在我想从数据库中读取 pdf 文件并将图像(字节)插入 pdf 文件,并希望将新的 pdf(字节)保存到新表中。 它给出了“文档没有页面”的错误。 我使用了以下代码:
string fileName = "~/AuthDoc/" + Convert.ToString(consentMain.AppointmentId) +".pdf";
string newFile = System.Web.Hosting.HostingEnvironment.MapPath(fileName);
PdfReader reader = new PdfReader(consentDoc); // get pdf byte from datbase
Rectangle size = reader.GetPageSizeWithRotation(1);
Document document = new Document(size);
// open the writer
FileStream fs = new FileStream(newFile, FileMode.Create, FileAccess.Write);
PdfWriter writer = PdfWriter.GetInstance(document, fs);
document.Open();
// PdfReader reader = new PdfReader(consentDoc);
// FileStream fs = new FileStream(newFile, FileMode.Create);
var stamper = new PdfStamper(reader, fs);
var pdfContentByte = stamper.GetOverContent(1);
iTextSharp.text.Image PatientSign = iTextSharp.text.Image.GetInstance(consentMain.PatientSign); // image from database
PatientSign.SetAbsolutePosition(100, 100);
pdfContentByte.AddImage(PatientSign);
document.Close();
fs.Close();
writer.Close();
reader.Close();
byte[] bytes = System.IO.File.ReadAllBytes(newFile);
return bytes;
【问题讨论】:
-
可能无法解决您的问题,但我不会在
writer.Close()之前致电fs.Close()。如果您将一次性用品放在using块中,您会自动强制自己使用正确的顺序。 -
您的代码很旧,因为您没有使用最新版本的 iText,而且在您使用
Documentand 的意义上很尴尬PdfStamper类。这些类在您使用的 iText 版本中是互斥的。为什么不升级? -
首先删除对
Document和PdfWriter的所有引用(完全丢弃这些行),然后确保关闭PdfStamper对象:stamper.Close()。或者...扔掉你所有的代码,用 iText 7 for .NET 重新开始。 -
感谢@BrunoLowagie,现在可以正常使用了。
-
我的评论是一个答案。