iTextSharp文件操作和显示到FileStreamResults
本文关键字:FileStreamResults 显示 文件 操作 iTextSharp | 更新日期: 2023-09-27 18:06:53
我正在尝试使用iTextSharp打开PDF文件,向文件添加数据集以预填充数据,然后将其保存到流中,以便我可以将其显示给用户。我不想把它保存到本地文件中。我一直得到错误"无法访问已关闭的流。"我不知道哪个流是错的。
下面是我的代码:public FileStreamResult PushDataIntoPDFStream(string filename)
{
var reader = new PdfReader(Path.Combine(Server.MapPath(path), filename));
var xml = @"<?xml version=""1.0"" encoding=""UTF-8""?>
<form1>
<firstName>test</firstName>
<lastName>user</lastName>
<driveCar>0</driveCar>
<gender>1</gender>
<birthdate>2011-08-12</birthdate>
<numPets>4</numPets>
</form1>";
using (var outstream = new MemoryStream())
{
using (var stamper = new PdfStamper(reader, outstream))
{
var bytes = System.Text.Encoding.UTF8.GetBytes(xml);
using (var ms = new MemoryStream(bytes))
{
stamper.AcroFields.Xfa.FillXfaForm(ms);
}
}
return new FileStreamResult(outstream, "application/pdf")
{
FileDownloadName = "file.pdf";
};
}
}
PdfStamper
在其内部输出流上具有.CloseStream
属性;尝试将其设置为false:
using (var stamper = new PdfStamper(reader, outstream))
{
stamper.Writer.CloseStream = false;