Skip to content

Instantly share code, notes, and snippets.

@mlienau
Created April 1, 2022 02:35
Show Gist options
  • Save mlienau/eb892852a84d8bb7aa7d1ca80aadedc8 to your computer and use it in GitHub Desktop.
Save mlienau/eb892852a84d8bb7aa7d1ca80aadedc8 to your computer and use it in GitHub Desktop.
Blazor: View PDF in new tab from byte array
@inject IJSRuntime JSRuntime
@implements IAsyncDisposable
@code {
string? localFileUrl;
async Task ViewThePdf()
{
var response = await Api.GetPdfResponse("/route/to/pdf");
var pdfBytes = await response.Content.ReadAsByteArrayAsync(); // using Refit
var unmarshalledRuntime = (IJSUnmarshalledRuntime)JSRuntime;
localFileUrl = unmarshalledRuntime.InvokeUnmarshalled<byte[], string>("openPdfFromBytes", pdfBytes);
}
async ValueTask IAsyncDisposable.DisposeAsync()
{
if (localFileUrl != null)
{
// Need to clean this up so we don't leak memory
await JSRuntime.InvokeVoidAsync("URL.revokeObjectURL", localFileUrl);
}
}
}
function openPdfFromBytes(bytes) {
// taken from SO: https://stackoverflow.com/a/66544057/1042263
const dataPtr = Blazor.platform.getArrayEntryPtr(bytes, 0, 4);
const length = Blazor.platform.getArrayLength(bytes);
const shorts = new Int16Array(Module.HEAPU8.buffer, dataPtr, length);
var blob = new Blob([shorts], { type: "application/pdf" });
var link = document.createElement('a');
const url = window.URL.createObjectURL(blob); // this url will need to be cleaned up later
link.href = url;
link.target = "_blank";
//link.download = "<FILENAME_TO_SAVE_WITH_EXTENSION>"; // if you want to download the file
link.click();
// return the url, so we can revoke it when we're done
return BINDING.js_string_to_mono_string(url); // how to return a string back to Blazor
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment