如何在HTML Object标记中呈现PDF字节数组

时间:2015-06-05 23:24:16

标签: c# asp.net pdf aspose

我有一个由ASPose生成的PDF作为字节数组,我想在网页上的组件内呈现该PDF。

        using (MemoryStream docStream = new MemoryStream())
        {
            doc.Save(docStream, Aspose.Words.SaveFormat.Pdf);
            documentStream = docStream.ToArray();
        }

我认为将字节数组分配给后面代码中的data属性只是一个简单的变体。下面是设置,以及我尝试过的一些变体。我该怎么做才能将该字节数组渲染为我的网页的可见子组件?

       HtmlGenericControl pTag = new HtmlGenericControl("p");
        pTag.InnerText = "No Letter was Generated.";
        pTag.ID = "errorMsg";
        HtmlGenericControl objTag = new HtmlGenericControl("object");
        objTag.Attributes["id"] = "pdf_content";
        objTag.Attributes["height"] = "400";
        objTag.Attributes["width"] = "500";
        String base64EncodedPdf = System.Convert.ToBase64String(pdfBytes);

        //1-- Brings up the "No Letter was Generated" message
         objTag.Attributes["data"] = "data:application/pdf;base64," + base64EncodedPdf.ToString(); 

        //2-- Brings up the gray PDF background and NO initialization bar.
        objTag.Attributes["type"] = "application/pdf";
        objTag.Attributes["data"] = "data:application/pdf;base64," + base64EncodedPdf.ToString();

        //3-- Brings up the gray PDF background and the initialization bar, then stops.
        objTag.Attributes["type"] = "application/pdf";
        objTag.Attributes["data"] = pdfBytes.ToString();  

        //4-- Brings up a white square of the correct size, containing a circle with a slash in the top left corner.
        objTag.Attributes["data"] = "application/pdf" + pdfBytes.ToString();


        objTag.Controls.Add(pTag);
        pdf.Controls.Add(objTag);

1 个答案:

答案 0 :(得分:4)

object标记的data属性应包含指向将提供PDF字节流的端点的URL。它不应该包含内联的字节流。

要使此页面正常工作,您需要添加一个提供字节流的附加handler,例如GetPdf.ashx。处理程序的ProcessRequest方法将准备PDF字节流并在响应中内联返回,前面有相应的标头,表明它是PDF对象。

protected void ProcessRequest(HttpContext context)
{
    byte[] pdfBytes = GetPdfBytes(); //This is where you should be calling the appropriate APIs to get the PDF as a stream of bytes
    var response = context.Response;
    response.ClearContent();
    response.ContentType = "application/pdf";
    response.AddHeader("Content-Disposition", "inline");
    response.AddHeader("Content-Length", pdfBytes.Length.ToString());
    response.BinaryWrite(pdfBytes); 
    response.End();
}

同时,您的主页将使用指向处理程序的URL填充data属性,例如

objTag.Attributes["data"] = "GetPdf.ashx";