Hi hmoaiery,
Refer below example.
First read the QueryString value from the Url. Then make ajax call and read the Word file based on the file path and convert to Byte Array.
For more details on reading QueryString from url refer the article Read QueryString parameters in jQuery.
Finally, pass the Byte Array to ajax success function for preview.
For more details on preview Word file refer the article Retrieve and display Word Files from database in browser in ASP.Net.
HTML
<div id="word-container" class=""></div>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript" src="https://unpkg.com/jszip/dist/jszip.min.js"></script>
<script type="text/javascript" src="Scripts/docx-preview.js"></script>
<script type="text/javascript">
$(function () {
// Get the Id from QueryString.
var fileId = 1;
$.ajax({
type: "POST",
url: "Default.aspx/GetWordDocument",
data: "{fileId: " + fileId + "}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (r) {
//Convert BLOB to File object.
var doc = new File([new Uint8Array(r.d.Data)], r.d.ContentType);
//If Document not NULL, render it.
if (doc != null) {
//Set the Document options.
var docxOptions = Object.assign(docx.defaultOptions, {
useMathMLPolyfill: true
});
//Reference the Container DIV.
var container = document.querySelector("#word-container");
//Render the Word Document.
docx.renderAsync(doc, container, null, docxOptions);
}
}
});
});
</script>
Code
C#
[System.Web.Services.WebMethod]
public static object GetWordDocument(int fileId)
{
//Fetch the file details from database based on the Id.
byte[] bytes = System.IO.File.ReadAllBytes(HttpContext.Current.Server.MapPath("~/Files/Sample.docx"));
string contentType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
string fileName = "Sample.docx";
return new { FileName = fileName, ContentType = contentType, Data = bytes };
}
VB.Net
<System.Web.Services.WebMethod>
Public Shared Function GetWordDocument(ByVal fileId As Integer) As Object
'Fetch the file details from database based on the Id.
Dim bytes As Byte() = System.IO.File.ReadAllBytes(HttpContext.Current.Server.MapPath("~/Files/Sample.docx"))
Dim contentType As String = "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
Dim fileName As String = "Sample.docx"
Return New With {
.FileName = fileName,
.ContentType = contentType,
.Data = bytes
}
End Function