Skip to main content
 首页 » 编程设计

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

2024年02月06日14Free-Thinker

我有一个由 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 属性标签应包含指向将提供 PDF 字节流的端点的 URL。它不应包含字节流本身内联。

要使此页面正常工作,您需要添加一个额外的 handler提供字节流,例如GetPdf.ashx。处理程序的 ProcessRequest 方法将准备 PDF 字节流并在响应中内联返回它,前面是适当的 header ,表明它是一个 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";