如何在 HTML 对象标签中呈现 PDF 字节数组

How to render PDF byte array in an HTML Object tag

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

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

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

       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);

object 标签的 data 属性应包含一个 URL,它指向将提供 PDF 字节流的端点。它不应该包含字节流本身内联。

要使此页面正常工作,您需要添加一个额外的 handler 来提供字节流,例如GetPdf.ashx。处理程序的 ProcessRequest 方法将准备 PDF 字节流和 return 它在响应中内联,前面是适当的 headers 表明它是一个 PDF object。

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();
}

与此同时,您的主页会填充 data 属性,其中 URL 指向处理程序,例如

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