I have a Blazor application in which I'm trying to download a PDF I have edited using ITextSharp. All resources I search tend to use the Response class which I don't have (I believe because I am using .NET 6). I found some solutions that that send the byte array to a javascript function but I'm having no such luck. I get the error
System.ArgumentNullException: 'Value cannot be null.' When I Envoke the JS function.
I've posted my code below. Though I'm not passing any null objects, I do see some potential errors in my memory stream and I'm not sure why (See Image). Any information on where I'm going wrong or any easy approach would be appreciated. Thanks.
MemoryStream output = new MemoryStream();
PdfReader pdfReader = new PdfReader("MY_SOURCE_PATH_CHANGED_FOR_POST");
PdfStamper pdfStamper = new PdfStamper(pdfReader, output);
// Make Edits
//editPdf(ref pdfStamper.AcroFields);
pdfStamper.FormFlattening = false;
pdfStamper.Close();
await JSRuntime.InvokeVoidAsync("saveAsFile", "test.pdf", output.ToArray());
And the JS
function saveAsFile(filename, bytesBase64)
{
if (navigator.msSaveBlob) {
var data = window.atob(bytesBase64);
var bytes = new Unit8Array(data.length);
for (var i = 0; i < data.length; i++) {
bytes[i] = data.charCodeAt(i);
}
var blob = new Blob([bytes.buffer], { type: "application/octet-stream" });
navigator.msSaveBlob(blob, filename);
}
else
{
var link = document.createElement("a");
link.download = filename;
link.href = "data:application/octet-stream;base64," + bytesBase64;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
}
*Note for the sake of the post I changed the source path but I have verified the path does return a PDF, from a direct URL from azure blob storage.
For anyone who needs it, I solved this issue by creating a controller.
[HttpGet("{appId}/{formCode}")]
public FileContentResult DownloadForm(int appId, int formCode)
{
byte[] PdfData = Repo.GetFormBytes(appId, (Enums.FormType)formCode);
if (PdfData != null)
{
FileContentResult file = new FileContentResult(PdfData, "application/pdf");
file.FileDownloadName = Repo.MostRecentFileName;
return file;
}
else
return null;
}
Where GetFormBytes returns byte array output.ToArray()
after it was edited. (See question).