[英]iTextSharp - Merging a Batch of PDF Byte Arrays
我正在使用iTextSharp來填充pdf上的一些字段。 我需要能夠將一系列這些pdf合並為一個批處理pdf文件。 下面,我遍歷一個SQL結果集,用與當前記錄相對應的值填充pdf的字段,將其存儲為字節數組,然后將所有這些合並為字節數組列表。 然后,我嘗試將列表中的每個字節數組合並為一個字節數組,並將其作為pdf提供給用戶。
似乎可以正常工作,生成一個單個文件,其中包含的單個頁面大概與我的結果集中的單個頁面一樣多,但每個頁面上的所有字段均為空白。 使用FillForm()提供單個pdf時,它可以按預期工作。 我究竟做錯了什么?
byte[] pdfByteArray = new byte[0];
List<byte[]> pdfByteArrayList = new List<byte[]>();
byte[] pdfByteArrayItem = new byte[0];
foreach (DataRow row in results.Rows)
{
certNum = row[1].ToString();
certName = row[2].ToString();
certDate = row[3].ToString();
pdfByteArrayItem = FillForm(certType, certName, certNum, certDate);
pdfByteArrayList.Add(pdfByteArrayItem);
}
using (var ms = new MemoryStream()) {
using (var doc = new Document()) {
using (var copy = new PdfSmartCopy(doc, ms)) {
doc.Open();
//Loop through each byte array
foreach (var p in pdfByteArrayList) {
//Create a PdfReader bound to that byte array
using (var reader = new PdfReader(p)) {
//Add the entire document instead of page-by-page
copy.AddDocument(reader);
}
}
doc.Close();
}
}
pdfByteArray = ms.ToArray();
context.Response.ContentType = "application/pdf";
context.Response.BinaryWrite(pdfByteArray);
context.Response.Flush();
context.Response.End();
private byte[] FillForm(string certType, string certName, string certNum, string certDate)
{
string pdfTemplate = string.Format(@"\\filePath\{0}.pdf", certType);
PdfReader pdfReader = new PdfReader(pdfTemplate);
MemoryStream stream = new MemoryStream();
PdfStamper pdfStamper = new PdfStamper(pdfReader, stream);
AcroFields pdfFormFields = pdfStamper.AcroFields;
// set form pdfFormFields
pdfFormFields.SetField("CertName", certName);
pdfFormFields.SetField("CertNum", certNum);
pdfFormFields.SetField("CertDate", certDate);
// flatten the form to remove editting options, set it to false
// to leave the form open to subsequent manual edits
pdfStamper.FormFlattening = false;
// close the pdf
pdfStamper.Close();
stream.Flush();
stream.Close();
byte[] pdfByte = stream.ToArray();
return pdfByte;
}
在為字段設置值之后添加下面的行似乎已解決了該問題:
pdfFormFields.GenerateAppearances = true;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.