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

Joe*_*Joe 1 c# pdf asp.net aspose

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

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

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

       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);
Run Code Online (Sandbox Code Playgroud)

Joh*_* Wu 5

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

为了使该页面正常工作,您需要添加一个提供字节流的附加处理程序,例如 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();
}
Run Code Online (Sandbox Code Playgroud)

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

objTag.Attributes["data"] = "GetPdf.ashx";
Run Code Online (Sandbox Code Playgroud)