You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用iText7批量填充PDF表单:循环仅返回首个文件的解决方法

批量填充PDF表单并返回打包文件的解决方案

你的代码问题出在循环内部直接执行return,导致处理完第一个PDF后就终止了循环,无法继续处理后续文件。由于单个HTTP请求只能返回一个响应结果,合理的做法是把所有填充好的PDF打包成ZIP文件返回。

以下是修改后的实现代码:

[HttpPost]
public IActionResult Create(Job newJob)
{
    string path = MyServer.MapPath(@"\Files\");
    DirectoryInfo d = new DirectoryInfo(path);
    var pdfFiles = d.GetFiles("*.pdf");

    // 创建内存流存储ZIP文件
    using var zipStream = new MemoryStream();
    using (var archive = new ZipArchive(zipStream, ZipArchiveMode.Create, true))
    {
        foreach (var file in pdfFiles)
        {
            if (!System.IO.File.Exists(file.FullName))
                continue;

            using var sourceFileStream = System.IO.File.OpenRead(file.FullName);
            using var outputStream = new MemoryStream();
            
            // 处理PDF表单填充
            using var pdf = new PdfDocument(new PdfReader(sourceFileStream), new PdfWriter(outputStream));
            PdfAcroForm form = PdfAcroForm.GetAcroForm(pdf, false);
            if (form != null)
            {
                IDictionary<string, PdfFormField> fields = form.GetAllFormFields();
                if (fields.TryGetValue("CustomerName", out var customerNameField))
                {
                    customerNameField.SetValue(newJob.CustomerName);
                }
                if (fields.TryGetValue("PropertyAddress", out var addressField))
                {
                    addressField.SetValue(newJob.PropertyAddress);
                }
            }

            // 将处理后的PDF添加到ZIP中
            outputStream.Position = 0;
            var zipEntry = archive.CreateEntry(file.Name);
            using var entryStream = zipEntry.Open();
            outputStream.CopyTo(entryStream);
        }
    }

    zipStream.Position = 0;
    // 返回ZIP文件
    return File(zipStream, "application/zip", "filled_forms.zip");
}

关键修改点说明

  • 移除循环内的return语句,改用ZIP打包所有处理后的文件,保证循环能执行完所有PDF
  • 使用using语句自动释放流和PDF资源,避免内存泄漏
  • 调整字段获取逻辑,增加空值判断,规避空引用异常
  • 最终返回打包后的ZIP文件,用户可一次性下载所有填充完成的PDF

内容的提问来源于stack exchange,提问作者Xs_

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.01 16:32:25