When citing specific content in reference documents, legal documents or technical documentation, it is often necessary to point out both the page number and the line number. Line numbers are added automatically by Word per page or per section, so they do not have to be typed into the text by hand. The starting number, the numbering interval, the distance between the line numbers and the text and the way numbering restarts can all be adjusted in the page setup. The paper size, the paper orientation and the margins determine the area available for layout on a page, and they also need to be set consistently when a document is delivered for printing or archived in a fixed format.

This article uses Spire.Doc for JavaScript to perform the page setup described above in the browser. The document is loaded through the virtual file system (VFS), saved after the settings are applied and downloaded directly. The whole process runs on the client side with WebAssembly, requires no Office installation and depends on no backend service.

This article covers three features:

The examples read Sample.docx from public/data; put that file into the public/data directory of the project before running them.

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


Add Line Numbers to a Word Document

To add line numbers to a Word document, the numbering is controlled by the page setup of the section; four properties on PageSetup together determine the effect:

Property Purpose Example
PageSetup.LineNumberingStartValue The starting number of the line numbering 1
PageSetup.LineNumberingStep The numbering interval, that is, how many lines apart a line number appears 1
PageSetup.LineNumberingDistanceFromText The distance between the line numbers and the text, in points 40
PageSetup.LineNumberingRestartMode How the numbering restarts Continuous

The sample document is A4 portrait, with margins of 2.19 cm at the top and bottom and 3.17 cm on the left and right, and line numbering is not enabled. The following code sets the starting number to 1, numbers every 1 line, places the line numbers 40 points from the text, and numbers continuously throughout the section.

The specific steps are as follows:

  1. Get the Spire.Doc WASM module and confirm that it is ready.
  2. Load the font, read the sample document into the VFS and load it as a Document.
  3. Take the first section and set the starting number, the interval, the distance and the numbering mode of the line numbering through PageSetup.
  4. Save the result file with SaveToFile().
  5. Read the result file from the VFS and trigger a browser download.

The code for adding line numbers to a Word document is as follows:

function App() {
  const addLineNumbers = async () => {
    // Get the Spire.Doc WASM module
    const wasmModule = window.wasmModule?.spiredoc;

    // Check if the module is ready
    if (!wasmModule) {
      alert('Spire.Doc is not ready yet');
      return;
    }

    // Load the document to be processed
    await window.spire.FetchFileToVFS('Sample.docx', '', `${process.env.PUBLIC_URL}/data/`);

    // Create a Document instance and load the document
    const doc = new wasmModule.Document();
    doc.LoadFromFile('Sample.docx');

    // Line numbers apply per section, so take the page setup of the first section
    const pageSetup = doc.Sections.get_Item(0).PageSetup;

    // Set the starting number of the line numbering
    pageSetup.LineNumberingStartValue = 1;

    // Set the numbering interval: show one line number every 1 line
    pageSetup.LineNumberingStep = 1;

    // Set the distance between the line numbers and the text, in points
    pageSetup.LineNumberingDistanceFromText = 40;

    // Set the numbering mode to continuous throughout the section
    pageSetup.LineNumberingRestartMode = wasmModule.LineNumberingRestartMode.Continuous;

    // Save the result file
    const outputFileName = 'AddLineNumbers.docx';
    doc.SaveToFile({ fileName: outputFileName, fileFormat: wasmModule.FileFormat.Docx2013 });
    doc.Dispose();

    // Read the generated file from the VFS and trigger the download
    const fileArray = window.dotnetRuntime.Module.FS.readFile(outputFileName);
    const blob = new Blob([fileArray], { 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>Add Line Numbers to a Word Document</h1>
      <button onClick={addLineNumbers}>
        Add Line Numbers
      </button>
    </div>
  );
}

export default App;

The page after line numbers have been added to the Word document is shown below:

Page after line numbers have been added to the Word document

How the Line Numbering Restarts

LineNumberingRestartMode determines where the line numbers are counted from again. The available values are as follows:

Value Numbering behavior
LineNumberingRestartMode.Continuous Number continuously throughout the section
LineNumberingRestartMode.RestartPage Restart from the starting number on every page
LineNumberingRestartMode.RestartSection Restart from the starting number in every section
LineNumberingRestartMode.None Do not specify a restart; number continuously through the document

To restart the count from the starting number on every page, change the numbering mode to RestartPage:

// Restart from the starting number on every page
pageSetup.LineNumberingRestartMode = wasmModule.LineNumberingRestartMode.RestartPage;

Set Paper Size and Orientation for a Word Document

To set the paper size and orientation of a Word document, use the PageSize and Orientation properties in the page setup of the section. PageSize accepts a size object, and Spire.Doc for JavaScript provides a set of common predefined paper sizes that are returned as static methods in the JavaScript binding:

Method Paper size
PageSize.A4() A4, 210 × 297 mm
PageSize.Letter() Letter, 8.5 × 11 in
PageSize.A3() A3, 297 × 420 mm
PageSize.A5() A5, 148 × 210 mm

The paper orientation is specified by the PageOrientation enumeration, where Portrait is upright and Landscape is sideways. The following code sets the paper size of the sample document to Letter and changes the orientation to landscape.

The specific steps are as follows:

  1. Get the Spire.Doc WASM module and confirm that it is ready.
  2. Load the font, read the sample document into the VFS and load it as a Document.
  3. Take the first section and set the paper size and the paper orientation through PageSetup.
  4. Save the result file with SaveToFile().
  5. Read the result file from the VFS and trigger a browser download.

The code for setting the paper size and orientation of a Word document is as follows:

function App() {
  const setPaperSize = async () => {
    // Get the Spire.Doc WASM module
    const wasmModule = window.wasmModule?.spiredoc;

    // Check if the module is ready
    if (!wasmModule) {
      alert('Spire.Doc is not ready yet');
      return;
    }

    // Load the document to be processed
    await window.spire.FetchFileToVFS('Sample.docx', '', `${process.env.PUBLIC_URL}/data/`);

    // Create a Document instance and load the document
    const doc = new wasmModule.Document();
    doc.LoadFromFile('Sample.docx');

    // The paper size also applies per section, so take the page setup of the first section
    const pageSetup = doc.Sections.get_Item(0).PageSetup;

    // Set the paper size to Letter; in the JavaScript binding the size object is obtained by calling the method
    pageSetup.PageSize = wasmModule.PageSize.Letter();

    // Set the page orientation to landscape
    pageSetup.Orientation = wasmModule.PageOrientation.Landscape;

    // Save the result file
    const outputFileName = 'SetPaperSize.docx';
    doc.SaveToFile({ fileName: outputFileName, fileFormat: wasmModule.FileFormat.Docx2013 });
    doc.Dispose();

    // Read the generated file from the VFS and trigger the download
    const fileArray = window.dotnetRuntime.Module.FS.readFile(outputFileName);
    const blob = new Blob([fileArray], { 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 Paper Size and Orientation for a Word Document</h1>
      <button onClick={setPaperSize}>
        Set Paper Size
      </button>
    </div>
  );
}

export default App;

The page after it has been set to Letter size and landscape orientation is shown below:

Page after it has been set to Letter size and landscape orientation


Set Page Margins for a Word Document

To set the page margins of a Word document, specify the values for the top, bottom, left and right sides through PageSetup.Margins. These values are all in points, and 1 cm is approximately 28.35 points; the common conversions are as follows:

Side Property Example value (points) Equivalent
Top PageSetup.Margins.Top 85 3 cm
Bottom PageSetup.Margins.Bottom 85 3 cm
Left PageSetup.Margins.Left 127.5 4.5 cm
Right PageSetup.Margins.Right 127.5 4.5 cm

The original margins of the sample document are 2.19 cm at the top and bottom and 3.17 cm on the left and right. The following code changes the top and bottom margins to 3 cm and the left and right margins to 4.5 cm, and the area available for layout on the page narrows accordingly.

The specific steps are as follows:

  1. Get the Spire.Doc WASM module and confirm that it is ready.
  2. Load the font, read the sample document into the VFS and load it as a Document.
  3. Take the first section and set the margins of the four sides through PageSetup.Margins.
  4. Save the result file with SaveToFile().
  5. Read the result file from the VFS and trigger a browser download.

The code for setting the page margins of a Word document is as follows:

function App() {
  const setPageMargins = async () => {
    // Get the Spire.Doc WASM module
    const wasmModule = window.wasmModule?.spiredoc;

    // Check if the module is ready
    if (!wasmModule) {
      alert('Spire.Doc is not ready yet');
      return;
    }

    // Load the document to be processed
    await window.spire.FetchFileToVFS('Sample.docx', '', `${process.env.PUBLIC_URL}/data/`);

    // Create a Document instance and load the document
    const doc = new wasmModule.Document();
    doc.LoadFromFile('Sample.docx');

    // Margins also apply per section, so take the page setup of the first section
    const pageSetup = doc.Sections.get_Item(0).PageSetup;

    // Set the margins of the four sides, in points
    pageSetup.Margins.Top = 85;      // about 3 cm
    pageSetup.Margins.Bottom = 85;   // about 3 cm
    pageSetup.Margins.Left = 127.5;  // about 4.5 cm
    pageSetup.Margins.Right = 127.5; // about 4.5 cm

    // Save the result file
    const outputFileName = 'SetPageMargins.docx';
    doc.SaveToFile({ fileName: outputFileName, fileFormat: wasmModule.FileFormat.Docx2013 });
    doc.Dispose();

    // Read the generated file from the VFS and trigger the download
    const fileArray = window.dotnetRuntime.Module.FS.readFile(outputFileName);
    const blob = new Blob([fileArray], { 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 Page Margins for a Word Document</h1>
      <button onClick={setPageMargins}>
        Set Page Margins
      </button>
    </div>
  );
}

export default App;

The page after the margins of the four sides have been adjusted is shown below:

Page after the margins of the four sides have been adjusted


FAQ

Why are the line numbers not visible in the document after they have been added

Line numbers belong to the page setup of the section and are normally shown in Word's page view (print layout); the reading view and the web layout may not display them. If they are still missing after switching to page view, check whether the code changed the section that holds the body text: line numbers are stored per section, so in a document with several sections, setting only the first section leaves the other sections without line numbers.

Why do the line numbers still start from 1 after the starting number has been set

Line numbers are stored per section, and the starting number only takes effect in the section it is assigned to. The examples take the first section, so if the body text sits in another section, that section has to be used instead. The default value of LineNumberingStartValue is 1, which is why numbering naturally begins at 1 when no value is assigned; after it is set to 5, the first line of that section shows 5 and the following lines are numbered from there.

What unit do the margins use, and why is a value of 2.54 not 2.54 cm

The values of PageSetup.Margins are in points, while Word's interface displays centimeters or inches. One centimeter is approximately 28.35 points, so 2.54 cm is approximately 72 points; when laying out in centimeters, convert the value before assigning it.

Why does the layout of the existing content change after the paper size or orientation is modified

Once the paper size changes, the width and height available on the page change with it, the body text is rewrapped to the new width, and tables and pictures may be compressed or shifted. When the orientation is switched to landscape, width and height are exchanged, and tables laid out for a portrait page are more likely to run across pages. To preserve the original layout, first confirm which sections are affected, then decide whether to adjust the font size or the table column widths.

Why is it written as PageSize.Letter() in JavaScript instead of using PageSize.Letter directly

The JavaScript binding exposes the predefined paper sizes as static methods, and only a call returns the size object that can be assigned to PageSetup.PageSize. PageSize.Letter itself is a function, so assigning it directly does not produce a paper size, and the parentheses are required.


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.

Published in Page

Inserting a page break in a Word document is the most common way to control where a chapter begins and to keep a heading from being split from its body text across a page boundary; cleaning up the redundant page breaks in a document, on the other hand, is the key step in dealing with the blank pages left behind after content is copied from another document. Spire.Doc for JavaScript carries out these operations 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 two 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.


Insert a Page Break

Inserting a page break involves three steps: first, load the font files and the target Word document into the WASM virtual file system via FetchFileToVFS; then instantiate a Document, load the document, locate the target paragraph and call AppendBreak with BreakType.PageBreak, which appends the page break to the end of that paragraph as one of its child objects; finally, read the saved file from VFS, wrap it as a Blob and trigger a browser download.

function App() {
  const InsertPageBreak = async () => {
    const docModule = window.wasmModule?.spiredoc;
    if (!docModule) {
      alert('Spire.Doc is not ready yet');
      return;
    }

    // Load the target Word document into VFS
    const inputFileName = "Template_Docx_1.docx";
    await window.spire.FetchFileToVFS(inputFileName, "", `${process.env.PUBLIC_URL}static/data/`);

    // Create a Document instance and load the document
    const doc = new docModule.Document();
    doc.LoadFromFile(inputFileName);

    // Locate the fourth paragraph of the first section and append a page break to its end
    doc.Sections.get_Item(0).Paragraphs.get_Item(3).AppendBreak(docModule.BreakType.PageBreak);

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

    // Save the document to VFS
    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>Insert a Page Break into a Word Document</h1>
      <button onClick={InsertPageBreak}>Generate</button>
    </div>
  );
}
export default App;

The document after a page break is appended to the end of the fourth paragraph

The document after a page break is appended to the end of the fourth paragraph


Remove Page Breaks

Removing page breaks also involves three steps: first, load the font files and the Word document that contains the page breaks into the WASM virtual file system via FetchFileToVFS; then instantiate a Document, load the document, walk through the child objects of every paragraph in each section, test with DocumentObjectType whether an object is a page break, and remove it with ChildObjects.Remove; finally, read the saved file from VFS, wrap it as a Blob and trigger a browser download.

function App() {
  const RemovePageBreaks = async () => {
    const docModule = window.wasmModule?.spiredoc;
    if (!docModule) {
      alert('Spire.Doc is not ready yet');
      return;
    }

    // Load the target Word document into VFS
    const inputFileName = "Template_Docx_4.docx";
    await window.spire.FetchFileToVFS(inputFileName, "", `${process.env.PUBLIC_URL}static/data/`);

    // Create a Document instance and load the document
    const doc = new docModule.Document();
    doc.LoadFromFile(inputFileName);

    // Get the first section
    const section = doc.Sections.get_Item(0);

    // Walk through every paragraph in the section
    for (let j = 0; j < section.Paragraphs.Count; j++) {
        const p = section.Paragraphs.get_Item(j);

        // Walk the paragraph's child objects backwards, so that removing an element does not shift the indices still to come
        for (let i = p.ChildObjects.Count - 1; i >= 0; i--) {
            const obj = p.ChildObjects.get_Item(i);

            // Test whether the object is a page break
            if (obj.DocumentObjectType == docModule.DocumentObjectType.Break
                && obj.BreakType == docModule.BreakType.PageBreak) {
                // Remove the page break from the paragraph
                p.ChildObjects.Remove(obj);
            }
        }
    }

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

    // Save the document to VFS
    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>Remove Page Breaks from a Word Document</h1>
      <button onClick={RemovePageBreaks}>Generate</button>
    </div>
  );
}
export default App;

The document after every page break has been removed

The document after every page break has been removed


FAQ

An extra blank line appears at the top of the new page after inserting a page break

Cause: AppendBreak appends the page break to the end of the target paragraph, so that paragraph's own spacing after it is carried over to the start of the new page along with the page break, which shows up as a strip of white space at the top of the new page. If the paragraph has automatic spacing enabled, the height of that strip also changes with the font size.

Solution: Clear the spacing after the target paragraph before inserting the page break:

const para = document.Sections.get_Item(0).Paragraphs.get_Item(3);

// Turn off automatic spacing after the paragraph and set the space after it to 0
para.Format.AfterAutoSpacing = false;
para.Format.AfterSpacing = 0;

// Then insert the page break
para.AppendBreak(wasmModule.BreakType.PageBreak);

The document is still paginated after the page breaks are removed

Cause: Not every page break in a document comes from a page break object. If a paragraph itself has the page-break-before property set, that paragraph will still start on a new page even after the page break objects have been removed; walking ChildObjects and deleting DocumentObjectType.Break objects alone cannot take that kind of pagination out.

Solution: Reset the paragraph's page-break-before property at the same time as the page break objects are removed:

const section = document.Sections.get_Item(0);

for (let j = 0; j < section.Paragraphs.Count; j++) {
  const p = section.Paragraphs.get_Item(j);

  // Clear the page-break-before property set on the paragraph
  if (p.Format.PageBreakBefore) {
    p.Format.PageBreakBefore = false;
  }
}

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.

Published in Page

A gutter is the extra white space a page sets aside for binding, so that the body text is not hidden by the staples or the glued spine once the document is printed and bound. Because it is part of the page setup, it has to be fixed when the document is generated and cannot be added later at the printing stage. Spire.Doc for JavaScript performs page setup 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 two 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.


Add a Gutter

Adding a gutter involves three steps: first, load the font files and the target Word document into the WASM virtual file system via FetchFileToVFS; then instantiate a Document, load the document, get the target section and set the gutter width through PageSetup.Gutter — the value is in points and applies to the left side of the page by default; finally, read the saved file from VFS, wrap it as a Blob and trigger a browser download.

function App() {
  const AddGutter = async () => {
    const docModule = window.wasmModule?.spiredoc;
    if (!docModule) {
      alert('Spire.Doc is not ready yet');
      return;
    }

    // Load the target Word document into VFS
    const inputFileName = "GutterSample.docx";
    await window.spire.FetchFileToVFS(inputFileName, "", `${process.env.PUBLIC_URL}static/data/`);

    // Create a Document instance and load the document
    const doc = new docModule.Document();
    doc.LoadFromFile(inputFileName);

    // Get the first section
    const section = doc.Sections.get_Item(0);

    // Set the gutter width in points; it applies to the left side of the page by default
    section.PageSetup.Gutter = 100;

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

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

    // Release resources
    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>Add a Gutter to a Word Document</h1>
      <button onClick={AddGutter}>Generate</button>
    </div>
  );
}
export default App;

The document after a gutter has been added

The document after a gutter has been added


Set the Gutter Position

The gutter position decides which side of the page the strip of white space is added to: PageSetup.IsTopGutter set to true means a top gutter, and false (the default) means a left gutter. The steps are the same three as before: first, load the font files and the target Word document into the WASM virtual file system via FetchFileToVFS; then instantiate a Document, load the document, get the target section and set PageSetup.IsTopGutter to true to turn on the top gutter, then set the gutter width through PageSetup.Gutter; finally, read the saved file from VFS, wrap it as a Blob and trigger a browser download.

function App() {
  const SetGutterPosition = async () => {
    const docModule = window.wasmModule?.spiredoc;
    if (!docModule) {
      alert('Spire.Doc is not ready yet');
      return;
    }

    // Load the target Word document into VFS
    const inputFileName = "GutterSample.docx";
    await window.spire.FetchFileToVFS(inputFileName, "", `${process.env.PUBLIC_URL}static/data/`);

    // Create a Document instance and load the document
    const doc = new docModule.Document();
    doc.LoadFromFile(inputFileName);

    // Get the first section
    const section = doc.Sections.get_Item(0);

    // Set the gutter position to the top
    section.PageSetup.IsTopGutter = true;

    // Set the gutter width in points
    section.PageSetup.Gutter = 100;

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

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

    // Release resources
    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 the Gutter Position in a Word Document</h1>
      <button onClick={SetGutterPosition}>Generate</button>
    </div>
  );
}
export default App;

The document after the top gutter has been set

The document after the top gutter has been set


FAQ

The gutter width does not match the value shown in the Word interface

Cause: PageSetup.Gutter is measured in points, while the Word Page Setup dialog box displays centimeters or inches by default. Passing 100 directly, as the examples do, means 100 points — about 3.53 centimeters — which is noticeably wide on an A4 page.

Solution: Convert the unit before passing the value in. One point is 1/72 inch and one inch is 2.54 centimeters, so the formula for converting centimeters to points is points = centimeters ÷ 2.54 × 72:

// Convert a 1.5-centimeter gutter width to points
const gutterInPoints = (1.5 / 2.54) * 72;
section.PageSetup.Gutter = gutterInPoints;

The text area becomes too narrow after a gutter is set

Cause: The gutter claims space in addition to the margins; it does not enlarge the page but squeezes the text area inwards. If the existing margins were already generous, adding a gutter narrows the usable width further, leaving too few characters per line and making paragraphs wrap far more often.

Solution: Reduce the margin on the same side at the same time as the gutter is set, so that the usable text width is preserved:

const pageSetup = section.PageSetup;

// Set a 1.5-centimeter gutter (centimeters converted to points)
pageSetup.Gutter = (1.5 / 2.54) * 72;

// The gutter takes up space on the left, so reduce the left margin accordingly
pageSetup.Margins.Left = 60;

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.

Published in Page

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.

Published in Page