2

我想编辑现有的pdf并将结果发送到浏览器这是我的方法:

        public static byte[] Generate()
        {
        var templatePath = HttpContext.Current.Server.MapPath("~/my_template.pdf");
        // Based on:
        // http://www.johnnycode.com/blog/2010/03/05/using-a-template-to-programmatically-create-pdfs-with-c-and-itextsharp/
        var reader = new PdfReader(templatePath);
        var outStream = new MemoryStream();
        var stamper = new PdfStamper(reader, outStream);

        var form = stamper.AcroFields;
        var fieldKeys = form.Fields.Keys;

        foreach (string fieldKey in fieldKeys)
        {
         if (form.GetField(fieldKey) == "MyTemplatesOriginalTextFieldA")
           form.SetField(fieldKey, "1234");
         if (form.GetField(fieldKey) == "MyTemplatesOriginalTextFieldB")
           form.SetField(fieldKey, "5678");
         }

          // "Flatten" the form so it wont be editable/usable anymore  
        stamper.FormFlattening = true;  

        stamper.Close();
        reader.Close();

        return outStream.ToArray();
        }

和方法调用

        byte[] buffer = Generate();
        Response.ContentType = "application/pdf";
        Response.AddHeader("content-length", buffer.Length.ToString());
        Response.BinaryWrite(buffer); 

在这种情况下有人可以帮助我吗?

4

1 回答 1

2

添加这一行

  byte[] buffer = Generate();
  Response.ContentType = "application/pdf";
  Response.AddHeader("content-length", buffer.Length.ToString());
  Response.AppendHeader("Content-Disposition", "attachment; filename=youPDFName.pdf"); 
  Response.BinaryWrite(buffer);
  Response.End();

我在代码中添加了 Content-Disposition 和 response.end。

测试上面的代码,工作正常。让我知道它是否对你有用。

于 2013-01-07T11:41:26.953 回答