Set Word Document Backgrounds with JavaScript in React

Setting a page background for a Word document is one of the most common ways to polish contracts, official papers and brand materials: a soft base color, or a background image that matches the corporate visual identity, is enough to give the whole document a consistent visual tone. Spire.Doc for JavaScript performs this setting directly in the browser via WebAssembly, using a virtual file system (VFS) to manage input and output files — no backend server required.

This article covers three core features:

For installation and project setup, refer to Integrating Spire.Doc for JavaScript in a React Project. The examples below assume Spire.Doc is installed and the WebAssembly module is initialized.


Set a Solid Color Background

The solid color background involves three stages: first, load the font files and the target Word file into the WASM virtual file system via FetchFileToVFS; then instantiate a Document and load the file, set Background.Type to BackgroundType.Color, and assign a built-in color value to Background.Color; finally, save the document to the VFS with SaveToFile, read the generated docx file from it, wrap it as a Blob, and trigger a browser download.

function App() {
  const SetSolidColorBackground = async () => {
    const docModule = window.wasmModule?.spiredoc;
    if (!docModule) {
      alert('Spire.Doc is not ready yet');
      return;
    }
    // Load the sample file into the virtual file system (VFS)
    let inputFileName = "ScienceTemplate.docx";
    await window.spire.FetchFileToVFS(inputFileName, "", `${process.env.PUBLIC_URL}static/data/`);

    // Create Word document
    let doc = new docModule.Document();

    // Load the file
    doc.LoadFromFile(inputFileName);

    // Set the background type as Color
    doc.Background.Type = docModule.BackgroundType.Color;

    // Set the background color
    doc.Background.Color = docModule.Color.get_LightYellow();

    // Define the output file name
    const outputFileName = "SetSolidColorBackground_out.docx";

    // Save the document to the specified path
    doc.SaveToFile({ fileName: outputFileName, fileFormat: docModule.FileFormat.Docx2013 });

    doc.Dispose();

    const modifiedFileArray = window.dotnetRuntime.Module.FS.readFile(outputFileName);
    const blob = new Blob([modifiedFileArray], { type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = outputFileName;
    a.click();
    URL.revokeObjectURL(url);
  };

 return (
    <div style={{ textAlign: 'center', height: '300px' }}>
      <h1>Set a Solid Color Background for a Word Document</h1>
      <button onClick={SetSolidColorBackground}>Generate</button>
    </div>
  );
}
export default App;

After Background.Color has been applied, the whole page is filled with the built-in LightYellow background color.

The document after a solid color background is set via Background.Color


Set a Gradient Background

A gradient background follows the same flow as a solid color background; only the middle stage differs. Set Background.Type to BackgroundType.Gradient, retrieve the background gradient object through Background.Gradient, set the start color Color1 and the end color Color2 separately, and then use ShadingStyle and ShadingVariant to control the direction of the gradient and the way it transitions.

function App() {
  const SetGradientBackground = async () => {
    const docModule = window.wasmModule?.spiredoc;
    if (!docModule) {
      alert('Spire.Doc is not ready yet');
      return;
    }
    // Load the sample file into the virtual file system (VFS)
    let inputFileName = "ScienceTemplate.docx";
    await window.spire.FetchFileToVFS(inputFileName, "", `${process.env.PUBLIC_URL}static/data/`);

    // Create Word document
    let doc = new docModule.Document();

    // Load the file
    doc.LoadFromFile(inputFileName);

    // Set the background type as Gradient
    doc.Background.Type = docModule.BackgroundType.Gradient;
    let gradient = doc.Background.Gradient;

    // Set the start color and the end color of the gradient
    gradient.Color1 = docModule.Color.get_White();
    gradient.Color2 = docModule.Color.get_LightBlue();

    // Set the shading style and variant of the gradient
    gradient.ShadingVariant = docModule.GradientShadingVariant.ShadingDown;
    gradient.ShadingStyle = docModule.GradientShadingStyle.Horizontal;

    // Define the output file name
    const outputFileName = "SetGradientBackground_out.docx";

    // Save the document to the specified path
    doc.SaveToFile({ fileName: outputFileName, fileFormat: docModule.FileFormat.Docx2013 });

    doc.Dispose();

    const modifiedFileArray = window.dotnetRuntime.Module.FS.readFile(outputFileName);
    const blob = new Blob([modifiedFileArray], { type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = outputFileName;
    a.click();
    URL.revokeObjectURL(url);
  };

 return (
    <div style={{ textAlign: 'center', height: '300px' }}>
      <h1>Set a Gradient Background for a Word Document</h1>
      <button onClick={SetGradientBackground}>Generate</button>
    </div>
  );
}
export default App;

After Background.Gradient has been applied, the page background is filled with a white and light blue gradient.

The document after a gradient background is set via Background.Gradient


Set a Picture Background

A picture background is similar to the two backgrounds above; the difference lies in how the resources are prepared and assigned. At the loading stage the background image has to be loaded into the VFS together with the font files and the target Word file; then set Background.Type to BackgroundType.Picture and call Background.SetPicture with the path of the image inside the VFS to tile the image across the whole page as the background.

function App() {
  const SetImageBackground = async () => {
    const docModule = window.wasmModule?.spiredoc;
    if (!docModule) {
      alert('Spire.Doc is not ready yet');
      return;
    }
    // Load the sample file into the virtual file system (VFS)
    let inputFileName1 = "ScienceTemplate.docx";
    await window.spire.FetchFileToVFS(inputFileName1, "", `${process.env.PUBLIC_URL}static/data/`);

    // Load the background image into the virtual file system (VFS)
    let inputFileName2 = "Background.png";
    await window.spire.FetchFileToVFS(inputFileName2, "", `${process.env.PUBLIC_URL}static/data/`);

    // Load a Word document
    let doc = new docModule.Document();
    doc.LoadFromFile(inputFileName1);

    // Set the background type as Picture
    doc.Background.Type = docModule.BackgroundType.Picture;

    // Set the background picture
    doc.Background.SetPicture(inputFileName2);

    // Define the output file name
    const outputFileName = "SetImageBackground_out.docx";

    // Save the document to the specified path
    doc.SaveToFile({ fileName: outputFileName, fileFormat: docModule.FileFormat.Docx2013 });

    doc.Dispose();

    const modifiedFileArray = window.dotnetRuntime.Module.FS.readFile(outputFileName);
    const blob = new Blob([modifiedFileArray], { type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = outputFileName;
    a.click();
    URL.revokeObjectURL(url);
  };

 return (
    <div style={{ textAlign: 'center', height: '300px' }}>
      <h1>Set a Picture Background in a Word Document</h1>
      <button onClick={SetImageBackground}>Generate</button>
    </div>
  );
}
export default App;

After Background.SetPicture has been applied, the image is tiled across the whole page as the background.

The document after a picture background is set via Background.SetPicture


FAQ

The background does not appear in print

Cause: Word does not print page background colors or background pictures by default. This is a printing setting of the Word client, not a lost background setting in the document. The background displays normally while the document is open and is only ignored in the printed output.

Solution: To keep the background in a printed copy, select Print background colors and images under File > Options > Display in Word before printing. If the background has to be output in every environment, use a full-page shape in the header or a watermark to simulate it instead.

The picture background has no effect

Cause: Background.Type was not set to BackgroundType.Picture before SetPicture was called, or the background image was not loaded into the VFS via FetchFileToVFS, so SetPicture cannot find the image file.

Solution: Set the background type first, then pass the name of the image that has already been loaded into the VFS:

document.Background.Type = wasmModule.BackgroundType.Picture;
document.Background.SetPicture("Background.png");

Get a Free License

Spire.Doc for JavaScript offers a 30-day full-featured free trial license with no functional limitations. Apply here to evaluate before purchasing.