iTextSharp-合并一批PDF字节数组

时间:2019-02-14 20:52:44

标签: c# itext

我正在使用iTextSharp来填充pdf上的几个字段。我需要能够将一系列这些pdf合并为一个批处理pdf文件。下面,我遍历一个SQL结果集,用与当前记录相对应的值填充pdf的字段,将其存储为字节数组,然后将所有这些合并到字节数组列表中。然后,我尝试将列表中的merge each byte array放入一个单字节数组中,并作为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;
}

1 个答案:

答案 0 :(得分:0)

在为字段设置值之后添加下面的行似乎已解决:

pdfFormFields.GenerateAppearances = true;