Script file
All .js script files follow a simple structure. They consist of three main parts, each using the appropriate CDocBuilder class methods:
-
Creating or opening a document using CreateFile or OpenFile. Optionally set a temporary folder with SetTmpFolder.
builderJS.SetTmpFolder("DocBuilderTemp");
builderJS.CreateFile("docx"); -
Building the document contents using the Office API.
const oDocument = Api.GetDocument();
const oParagraph = Api.CreateParagraph();
oParagraph.SetJc("center");
oParagraph.AddText("Center");
oDocument.Push(oParagraph); -
Saving and closing the document using SaveFile and CloseFile.
builderJS.SaveFile("pdf", "output.pdf");
builderJS.CloseFile();
tip
Use builderJS for working with JavaScript variables directly. If you use builder, variables must be wrapped with jsValue(). See builder vs builderJS for details.
Rules
- The file encoding must be UTF-8.
- Comments are supported using
//or#at the start of a line. - Empty lines are ignored.
- All CDocBuilder methods (except ExecuteCommand) are called via builder or builderJS.
- The ExecuteCommand method is not used explicitly in scripts—write the commands directly instead.
- The following methods are not available in .js files: RunTextA, RunTextW, Initialize, Dispose.
Rules for builder object
When using the builder object:
- Commands containing
builder.must be on separate lines. - All JavaScript code must be placed between
builder.CreateFile()andbuilder.SaveFile()calls. - JavaScript variables passed to builder methods must be wrapped:
"jsValue(myVar)".
Rules for builderJS object
When using the builderJS object:
- JavaScript variables can be used directly without wrapping.
- Provides the additional OpenTmpFile method for working with temporary files.
Example
const outputPath = "output.pdf";
const text = "Hello, Document Builder!";
const currentDate = new Date().toLocaleDateString();
builderJS.CreateFile("docx");
const oDocument = Api.GetDocument();
const oParagraph = oDocument.GetElement(0);
oParagraph.SetJc("center");
oParagraph.AddText(text);
oParagraph.AddLineBreak();
oParagraph.AddText("Generated on: " + currentDate);
builderJS.SaveFile("pdf", outputPath);
builderJS.CloseFile();