locked
Render PDF from blob storage in browser RRS feed

  • Question

  • User1314407993 posted

    I had this working just fine by converting a PDF to a Base64 string, but Chrome's PDF browser saved downloaded files with the title "download.pdf", and nothing I found could change that. So instead of sending it in as a Base64 string, I thought I could point to the URL of the PDF file and thereby work around the issue with Chrome's default title - if a filename was at the end of the URL, the file downloaded with the correct filename. But I haven't been able to get it to work - at all. Researching it online, I thought I'd be able to handle it via FileStreamResult. Here's that code:

    // I don't actually use the filename - it's there only to make
    // Chrome use the correct filename. 
    public IActionResult GetPdf(Guid guid, string filename)
    {
        var blockBlob = BlobStorageMgmt.GetBlobItem(guid);
        blockBlob.FetchAttributes();
    
        using (MemoryStream ms = new MemoryStream())
        {
            blockBlob.DownloadToStream(ms);
    
            return new FileStreamResult(ms, "application/pdf");
        }
    }

    In the view, I have this:

    <embed src="@Url.Action("GetPdf", "Home", new { guid = Model.Guid, filename = Model.Filename })" width="100%" height="800" type="application/pdf"></embed>

    But all I get is an error message saying "Failed to load PDF document." Please help. 

    Wednesday, June 26, 2019 10:20 PM

Answers

  • User1314407993 posted

    I finally worked it out. There were a few missing pieces. I didn't need a "filename" param for the method - I was passing it in only to be at the end of the URL, but that didn't work, even after I got the PDF to render in the browser. Here's my revised controller method:

    public IActionResult GetPdf(Guid guid)
    {
        var blockBlob = BlobStorageMgmt.GetBlobItem(guid);
        blockBlob.FetchAttributes();
    
        var ms = new MemoryStream();
    
        blockBlob.DownloadToStream(ms);
        ms.Position = 0;
    
        return new FileStreamResult(ms, "application/pdf");
    }

    And here's the hack to make Google Chrome's PDF viewer save the file with the correct filename:

    <embed src="/Home/GetPdf/@Model.Filename?guid=@Model.Guid" width="100%" height="800" type="application/pdf"></embed>

    Appending the filename to the end of the URL preceding the querystring did the trick. 

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, June 26, 2019 11:08 PM