我有一个 pdf 模板,我想为数据库中的每条记录生成。我找到了这个,但它只适用于物理文件。如何使这项工作仅在内存中起作用?我尝试使用 memorystream,但我无法使用 PdfReader 阅读此内容
using iTextSharp.text.pdf;
using System;
using System.IO;
public partial class Default2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
string uniqueidstr = Guid.NewGuid().ToString();
string file = Server.MapPath("~/Reports/PrimaVisita.pdf");
string MasterPdfFile = Server.MapPath("./MstrCopyFile" + uniqueidstr + ".pdf").ToString();
PdfCopyFields copy = new PdfCopyFields(new FileStream(MasterPdfFile, FileMode.CreateNew));
for (int i = 0; i < 10; i++)
{
PdfReader tmpReader = new PdfReader(file);
string tmpfilepath = Server.MapPath("./tmpFile" + uniqueidstr + i.ToString() + ".pdf").ToString();
FileStream tmpOutFileStream = new FileStream(tmpfilepath, FileMode.CreateNew);
PdfStamper tmpOutStamper = new PdfStamper(tmpReader, tmpOutFileStream);
AcroFields fields = tmpOutStamper.AcroFields;
fields.SetField("Cognome", "pippo" + i.ToString());
fields.SetField("Nome", "pluto" + i.ToString());
fields.SetField("DatiNascita", "paperino" + i.ToString());
fields.SetField("Residenza", "topolino" + i.ToString());
tmpOutStamper.Writer.CloseStream = false;
tmpOutStamper.FormFlattening = true;
tmpOutStamper.Close();
tmpOutFileStream.Close();
PdfReader nwPgReader = new PdfReader(tmpfilepath);
copy.AddDocument(nwPgReader);
}
copy.Close();
}
}
错误是“找不到 PDF 标头签名”。这是代码
protected void Button1_Click(object sender, EventArgs e)
{
string uniqueidstr = Guid.NewGuid().ToString();
string file = Server.MapPath("~/Reports/PrimaVisita.pdf");
MemoryStream masterStream = new MemoryStream();
//string MasterPdfFile = Server.MapPath("./MstrCopyFile" + uniqueidstr + ".pdf").ToString();
PdfCopyFields copy = new PdfCopyFields(masterStream);
for (int i = 0; i < 10; i++)
{
PdfReader tmpReader = new PdfReader(file);
string tmpfilepath = Server.MapPath("./tmpFile" + uniqueidstr + i.ToString() + ".pdf").ToString();
MemoryStream tmpStream = new MemoryStream();
//FileStream tmpOutFileStream = new FileStream(tmpfilepath, FileMode.CreateNew);
PdfStamper tmpOutStamper = new PdfStamper(tmpReader, tmpStream);
AcroFields fields = tmpOutStamper.AcroFields;
fields.SetField("Cognome", "pippo" + i.ToString());
fields.SetField("Nome", "pluto" + i.ToString());
fields.SetField("DatiNascita", "paperino" + i.ToString());
fields.SetField("Residenza", "topolino" + i.ToString());
tmpOutStamper.Writer.CloseStream = false;
tmpOutStamper.FormFlattening = true;
tmpOutStamper.Close();
//tmpOutFileStream.Close();
PdfReader nwPgReader = new PdfReader(tmpStream);
copy.AddDocument(nwPgReader);
}
copy.Close();
}