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

标签 c# asp.net pdf aspose

我有一个由 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);

最佳答案

objectdata 属性标签应包含指向将提供 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";

关于c# - 如何在 HTML 对象标记中呈现 PDF 字节数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30677233/

相关文章:

iOS - 检查 webView 是否加载了非 -'pdf' 文件扩展名的 PDF 内容

c# - 为默认构造函数添加断点

javascript - 显示一个 asp :ModalPopupExtender using jQuery

java - 如何使用 iText 获取连字的宽度

asp.net - 在.NET 4.5 Azure部署中找不到编译器可执行文件csc.exe

asp.net - 在 ajax 调用中处理过期的 .NET Forms 身份验证 cookie 的最佳方法?

swift - 同一 PDF 的多页 View

c# - 如何按动态项对 linq 查询进行分组

c# - 自定义字符串格式

c# - 如何通过 StartsWith 或包含搜索值查找列表中的第一个或最后一个字符串而不添加到另一个列表