使用 iText7 和内存流在 C# 中提取 PDF 表单字段/值

Pulling PDF form fields/values in C# using iText7 and memory streams

提问人:Irish Redneck 提问时间:11/14/2023 最后编辑:Svyatoslav DanylivIrish Redneck 更新时间:11/14/2023 访问量:36

问:

当我尝试使用 iText7 时,我收到“找不到 PDF 标题”错误,但纯粹通过内存流加载 pdf,而不是保存在服务器上的文件路径。这不可能吗?我只是想获取表单字段及其相关值,因为这些pdf表单已经填写完毕。我从OneDrive将它们下载为内存流,我想我需要先转换为流以用作PDFReader中的参数,但这就是我出错的地方。我的代码如下:

using (var memoryStream = await oneDrive.DriveItemDownloadAsync(SharedDriveID, Path.Combine(fileDirectory, "testPDFForm.pdf"), "path"))
{
    byte[] buffer = new byte[memoryStream.Length];
    await memoryStream.ReadAsync(buffer, 0, (int)memoryStream.Length);
    document.Base64 = Convert.ToBase64String(buffer);
    document.DownloadLink = driveItem.AdditionalData["@microsoft.graph.downloadUrl"].ToString();

    try
    {
        Stream testStream = memoryStream;
        PdfReader reader = new PdfReader(testStream);
        PdfDocument pdfDocument = new PdfDocument(reader);
        PdfAcroForm acroForm = PdfAcroForm.GetAcroForm(pdfDocument, false);
        IDictionary<string, PdfFormField> Map = new Dictionary<string, PdfFormField>();

        var test = acroForm.GetAllFormFieldsAndAnnotations();
    }
    catch (Exception ex)
    {
        Ok(ex);
    }

}
C# ASP.NET 核心 itext itext7 memorystream

评论

2赞 pcalkins 11/14/2023
您可以尝试使用 memoryStream.Position = 0;在尝试再次阅读之前。(readasync 将提升位置...
0赞 Irish Redneck 11/22/2023
你是对的!但是,我认为我的代码仍然不正确,因为我不确定如何获取所有表单字段和值。任何想法 ?
0赞 pcalkins 11/22/2023
不熟悉 PdfAcroForm...但看起来像是一本字典......你可以从 getKeys() 开始。(你可能应该为此开始一个新问题......

答: 暂无答案