如何使用iTextSharp下载编辑的PDF

时间:2018-12-04 09:22:08

标签: c# itext

我有pdf字节,我正在阅读

byte[] pdfContent =[];

PdfReader pdfReader = new PdfReader(pdfContent); 

using (MemoryStream outputStream = new MemoryStream())
{
    using (var pdfStamper = new PdfStamper(pdfReader, outputStream))
    {
        AcroFields pdfFormFields = pdfStamper.AcroFields;
        pdfFormFields .SetField("txtForename", "Test"));
        pdfStamper.Close();
        array = outputStream.ToArray();
    }
}

如何使用memorystream下载此编辑pdf

1 个答案:

答案 0 :(得分:0)

首先,您的代码似乎是错误的。您有空的PdfContent,并且您正在尝试打开包含空内容的pdf。此外,您不需要MemoryStream,因为您的意图是将文件写入磁盘(文件流将是您的最佳选择)

此示例可以帮助您编辑pdf。

private void fillPDFForm()
{
    string formFile = Server.MapPath(P_InputStream);
    string newFile = Server.MapPath(P_OutputStream);
    PdfReader reader = new PdfReader(formFile);
    using (PdfStamper stamper = new PdfStamper(reader, new FileStream(newFile, FileMode.Create)))
    {
        AcroFields fields = stamper.AcroFields;

        // set form fields
        fields.SetField("name", "John Doe");
        fields.SetField("address", "xxxxx, yyyy");
        fields.SetField("postal_code", "12345");
        fields.SetField("email", "johndoe@xxx.com");

        // flatten form fields and close document
        stamper.FormFlattening = true;
        stamper.Close();
    }
}

更多参考文献:https://simpledotnetsolutions.wordpress.com/2012/04/08/itextsharp-few-c-examples/