从源代码下载PDF文件的问题

时间:2016-06-20 10:36:10

标签: c# pdf pdf-generation itext

iv'e创建了一个从表单生成pdf文件的方法,使用itexsharp将其保存到正确的路径,但问题是我无法下载它。

这是我的代码:

private void FillForm(Dictionary<string, string> dic)
{

    var pdfTemplate = HttpContext.Current.Server.MapPath("~/ress/GENE_15_04_2014.pdf"); //_pdfTemplet;

    var newFile = _newFileName + "_" + Guid.NewGuid() + ".pdf";

    _gNewFile = newFile.ToString();

    var pdfReader = new PdfReader(System.IO.File.ReadAllBytes(pdfTemplate));

    var pfileStream = new FileStream(string.Format(HttpContext.Current.Server.MapPath("~/ress/") + "{0}", newFile), FileMode.Create);

    var pdfStamper = new PdfStamper(pdfReader, pfileStream);
    var pdfFormFields = pdfStamper.AcroFields;

    foreach (var entry in dic)
    {
        pdfFormFields.SetField(entry.Key, entry.Value);
    }
    pdfStamper.FormFlattening = true;
    pdfStamper.JavaScript = "this.print(true);\r";
    pdfStamper.Writer.CloseStream = false;
    pdfReader.Close();
    pdfStamper.Close();
    UPContract.Update();
    pfileStream.Close();
    pdf.FilePath = string.Format("../Ress/{0}", Path.GetFileName(_gNewFile));

    Response.Clear();
    byte[] bytes = System.IO.File.ReadAllBytes(string.Format(HttpContext.Current.Server.MapPath("~/ress/") + "{0}", _gNewFile));
    Response.ContentType = "application/pdf";
    MemoryStream ms = new MemoryStream(bytes);
    Response.AddHeader("content-disposition", "attachment;filename=" + "fiche abonnement_" + _gNewFile + ".pdf");
    Response.Buffer = true;
    ms.WriteTo(Response.OutputStream);
    Response.Flush();
    Response.End();
}

1 个答案:

答案 0 :(得分:0)

如果要传递文件,可以跳过字节数组MemoryStream并使用Response.WriteFile(string)