Search code examples
ms-worddownloadblazoropenxml

Create and download Word file in Blazor


I am trying to create a Word file and download the created file in clients browser.

The creation part seems to work fine and I can open the file manually from its Folder. But the downloaded file in browser does not open correctly and produces an error "The file is corrupt and cannot be opened"

I am using the code from here Microsoft instructions for downloading a file in Blazor

My code seems like this

 private async Task CreateAndDownloadWordFile()
{
    var destination = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
    var fileName = destination + "\\test12.docx";
    //SpreadsheetDocument spreadsheetDocument = SpreadsheetDocument.Create(destination, SpreadsheetDocumentType.Workbook);
    using (WordprocessingDocument doc = WordprocessingDocument.Create
(fileName, DocumentFormat.OpenXml.WordprocessingDocumentType.Document))
    {
        // Add a main document part.
        MainDocumentPart mainPart = doc.AddMainDocumentPart();

        // Create the document structure and add some text.
        mainPart.Document = new Document();
        Body body = mainPart.Document.AppendChild(new Body());
        Paragraph para = body.AppendChild(new Paragraph());
        Run run = para.AppendChild(new Run());

        // String msg contains the text, "Hello, Word!"
        run.AppendChild(new Text("New text in document"));

    }
    var fileStream = GetFileStream();
    using var streamRef = new DotNetStreamReference(stream: fileStream);
    await JS.InvokeVoidAsync("downloadFileFromStream", fileName, streamRef);

}



private Stream GetFileStream()
{
    var randomBinaryData = new byte[50 * 1024];
    var fileStream = new MemoryStream(randomBinaryData);

    return fileStream;
}

And I use this Javascript code

async function downloadFileFromStream(fileName, contentStreamReference) {
const arrayBuffer = await contentStreamReference.arrayBuffer();
const blob = new Blob([arrayBuffer]);
const url = URL.createObjectURL(blob);

triggerFileDownload(fileName, url);

URL.revokeObjectURL(url);
}

function triggerFileDownload(fileName, url) {
const anchorElement = document.createElement('a');
anchorElement.href = url;
anchorElement.download = fileName ?? '';
anchorElement.click();
anchorElement.remove();
}

Any ideas?


Solution

  • But the downloaded file in browser does not open correctly

    That is probably because you

    1. First create a Word document
    2. And then download var randomBinaryData = new byte[50 * 1024];

    the downloaded file in browser

    Check those. Are they exactly 50 * 1024 bytes ?

    --

    Also, you shouldn't pass the full C:\... path to the download funtion.

      var fileStream = File.OpenRead(filename);
      using var streamRef = new DotNetStreamReference(stream: fileStream);
    //await JS.InvokeVoidAsync("downloadFileFromStream", fileName, streamRef);
      await JS.InvokeVoidAsync("downloadFileFromStream", "suggestedName", streamRef);