从服务器下载pdf文件并不能使用itextSharp工作

时间:2016-04-20 09:52:58

标签: pdf download itextsharp

我创建了一个创建pdf文件并将其插入doc文件的函数,问题是我无法从该目录下载它,这是我的代码:

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

        var pdfTemplate = HttpContext.Current.Server.MapPath("~/ress/NOUVELLE_VERSION_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完成的。我接受了您的代码,复制/粘贴并对其进行了调整,以便将FileStream替换为MemoryStream

我无法测试你的代码,所以你可能需要在这里和那里进行调整,但你会明白你应该尝试实现的目标:

var pdfTemplate = HttpContext.Current.Server.MapPath("...");
var pdfReader = new PdfReader(System.IO.File.ReadAllBytes(pdfTemplate));
var output = new MemoryStream();
var pdfStamper = new PdfStamper(pdfReader, output);
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;
pdfStamper.Close();
pdfReader.Close();
Response.Clear();
Response.ContentType = "application/pdf";
Response.AddHeader("Content-Disposition", "attachment;filename=fiche abonnement_" + _gNewFile + ".pdf");
Response.BinaryWrite(output.ToArray()); 
Response.Flush();
Response.End();