Using a Template Document with the Open XML SDK for JavaScript
Return to the
Open XML SDK for JavaScript
Developer CenterWhen you write an Open XML program, you rarely (maybe never) want to create a document from scratch. Instead, you want to start with a template document and then add content to it as you need to. This applies whether you are creating word-processing documents, spreadsheets, or presentations. There are two approaches to accessing a template document when using the Open XML SDK for JavaScript.
- You can store an Open XML document as base64 encoded ASCII in a JavaScript string variable.
- You can use AJAX to retrieve the template document from your web server.
This screen-cast walks through both approaches.
In the video, I discuss two small PowerShell scripts. One is a modification that I make to my profile.ps1 that enables converting any binary file to base64 encoded ASCII. The other is a small function that takes a DOCX, XLSX, or PPTX, and generates a JavaScript literal string expression that you can paste directly into your JavaScript application.
Here are the Convert-ToB64 and Convert-FromB64 functions:
$sz8 = @" using System; using System.Collections; using System.Collections.Generic; using System.Text; using System.Linq; public class B64 { public static string ConvertToB64(string fileName) { byte[] ba = System.IO.File.ReadAllBytes(fileName); string base64String = (System.Convert.ToBase64String(ba)) .Select ( (c, i) => new { Character = c, Chunk = i / 76 } ) .GroupBy(c => c.Chunk) .Aggregate( new StringBuilder(), (s, i) => s.Append( i.Aggregate( new StringBuilder(), (seed, it) => seed.Append(it.Character), sb => sb.ToString() ) ) .Append(Environment.NewLine), s => { s.Length -= Environment.NewLine.Length; return s.ToString(); } ); return base64String; } public static void ConvertFromB64(string fileName, string b64) { string b64b = b64.Replace("\r\n", ""); byte[] ba = System.Convert.FromBase64String(b64b); System.IO.File.WriteAllBytes(fileName, ba); } } "@; Add-Type -TypeDefinition $sz8 function Convert-ToB64 { param( [string]$Path ) $f = (Resolve-Path $Path).ToString(); [B64]::ConvertToB64($f) } function Convert-FromB64 { param( [string]$Path, [string]$b64 ) $f = New-Item $Path -ItemType file [B64]::ConvertFromB64($f.FullName, $b64) }
Here is the small PowerShell function that uses the above functionality to convert a DOCX to a JavaScript string literal:
function ConvertDocxToJavaScriptLiteral { param ( $path ) $f = Resolve-Path $path $a = Convert-ToB64 $f $b = $a -split "\r\n" $count = $b.Count $c = $b | Select-Object -First $($count - 1) | % { "`"$_`" +" } $d = $b | Select-Object -Last 1 | % { "`"$_`"" } $c + $d | clip }
You use it as follows:
ConvertDocxToJavaScriptLiteral .\Test01.docx
This converts the DOCX to the JavaScript literals, and places the code on the clipboard, ready for you to paste into your JavaScript program.