字节[]到临时PDF文件显示在ASP.NET </object>中的<object> html标记中

时间:2015-02-05 11:59:20

标签: c# asp.net asp.net-mvc

如何在ASP.NET应用程序中生成临时PDF,以便从字节数组中获取生成的PDF的临时URL?

我使用这个,但我认为它可以变得简单:

//bytes[] arrayPDF exists before
string fileName = System.IO.Path.GetTempPath() + Guid.NewGuid().ToString() + ".pdf";
File.WriteAllBytes(fileName, arrayPDF);

HtmlGenericControl obj = new HtmlGenericControl("embed");
obj.Attributes.Add("src", fileName);
obj.Attributes.Add("style","border-radius: 10px;position: relative;top:0;right:0;left:0;bottom:0;width:100%;height:620px;");
obj.Attributes.Add("height","600");
obj.Attributes.Add("type", "application/pdf");
form1.Controls.Add(obj);

我的主要问题是如何生成临时文件,我确信它不会在服务器中停留超过请求/显示时间

1 个答案:

答案 0 :(得分:1)

使用ASP.NET ASHX Handler

public class Handler : IHttpHandler 
{
    public void ProcessRequest (HttpContext context) 
    {
        // relevant context.Response lines
    }

    public bool IsReusable 
    {
        get { return false; }
    }
}

同时检查this answer

context.Response.Clear(); 
context.Response.ClearContent(); 
context.Response.ClearHeaders(); 
context.Response.ContentType = "application/pdf";

Stream fileStream = publishBookManager.GetFile(documentId);
byte[] buffer = new byte[16 * 1024];
using (MemoryStream ms = new MemoryStream())
{
  int read;
  while ((read = fileStream.Read(buffer, 0, buffer.Length)) > 0)
  {
    ms.Write(buffer, 0, read);
  }
}

context.Response.BinaryWrite(data); 
context.Response.Flush();