Hello Team,
I am using Aspose.Words for Node.js and I need to change the full document formatting, not just specific runs or paragraphs.
Hello Team,
I am using Aspose.Words for Node.js and I need to change the full document formatting, not just specific runs or paragraphs.
How to change the whole document’s formatting with Aspose.Words for Node.js
Create (or modify) a style that contains the formatting you need – paragraph style, font family, font size, bold, etc.
const styleDto = new asposewordscloud.StyleUpdate({
name: "MyFullDocStyle", // any name you like
font: new asposewordscloud.Font({
name: "Arial",
size: 12,
bold: true
}),
// paragraph‑level options (alignment, spacing, etc.) go here
});
const updateStyleRequest = new asposewordscloud.UpdateStyleRequest({
name: "MyFullDocStyle", // existing style name or new one
styleUpdate: styleDto,
folder: "input", // folder where the DOCX resides
fileName: "source.docx"
});
await wordsApi.updateStyle(updateStyleRequest);
Apply that style to every paragraph in the document.
The simplest way is to retrieve the list of paragraph node paths and call updateParagraphFormat for each of them.
// 1) Get all paragraphs
const getParasReq = new asposewordscloud.GetParagraphsRequest({
fileName: "source.docx",
folder: "input"
});
const parasResult = await wordsApi.getParagraphs(getParasReq);
const paragraphs = parasResult.paragraphs.paragraphLinkList; // array of links
// 2) Update each paragraph to use the new style
for (const link of paragraphs) {
const nodePath = link.href.split("/").slice(-2).join("/"); // e.g. "sections/0/paragraphs/3"
const paraFormatDto = new asposewordscloud.ParagraphFormat({
styleName: "MyFullDocStyle"
});
const updateParaReq = new asposewordscloud.UpdateParagraphFormatRequest({
name: "source.docx",
nodePath: nodePath,
paragraphFormatDto: paraFormatDto,
folder: "input"
});
await wordsApi.updateParagraphFormat(updateParaReq);
}
nodePath points to the specific paragraph node (sections/{sectionIndex}/paragraphs/{paragraphIndex}).
By setting only styleName you inherit all the font/size/bold settings defined in the style created in step 1.
(Optional) If you want the same formatting for newly added content – set the style as the document’s default style:
const defaultStyleDto = new asposewordscloud.StyleUpdate({
name: "MyFullDocStyle"
});
const setDefaultReq = new asposewordscloud.UpdateStyleRequest({
name: "MyFullDocStyle",
styleUpdate: defaultStyleDto,
folder: "input",
fileName: "source.docx",
isDefault: true // makes it the default style for the document
});
await wordsApi.updateStyle(setDefaultReq);
With those details we can confirm the API signatures and, if necessary, suggest any newer endpoint (e.g., UpdateDocumentStyle introduced in later releases).
Hello Team,
I am using the below code, but the formatting is not getting updated.
Also, I want to avoid using loops.
Please check and let me know what I am doing wrong.
const fs = require(“fs”);
const path = require(“path”);
const {
WordsApi,
UploadFileRequest,
GetParagraphsRequest,
GetRunsRequest,
UpdateRunFontRequest,
UpdateParagraphFormatRequest,
ParagraphFormat,
DownloadFileRequest
} = require(“asposewordscloud”);
const model = require(“asposewordscloud/dist/model/model”);
const ASPOSE_CLIENT_ID = “”;
const ASPOSE_CLIENT_SECRET = “”;
async function changeParagraphStyle(
fileName = “fileA.docx”,
styleName = null,
fontOptions = null,
outputFileName = null
) {
const wordsApi = new WordsApi(ASPOSE_CLIENT_ID, ASPOSE_CLIENT_SECRET);
const filePath = path.join(__dirname, fileName);
const outputPath = outputFileName
? path.join(__dirname, outputFileName)
: filePath.replace(‘.docx’, ‘_updated.docx’);
// Upload file from root
await wordsApi.uploadFile(
new UploadFileRequest({
fileContent: fs.createReadStream(filePath),
path: fileName
})
);
// Get all paragraphs
const parasResult = await wordsApi.getParagraphs(
new GetParagraphsRequest({ name: fileName, nodePath: “” })
);
const paragraphs = parasResult.body?.paragraphs?.paragraphLinkList || parasResult.paragraphs?.paragraphLinkList || [];
console.log(📝 Found ${paragraphs.length} paragraphs);
// Update each paragraph
for (let i = 0; i < paragraphs.length; i++) {
if ((i + 1) % 10 === 0) {
console.log(⏳ Processing paragraph ${i + 1}/${paragraphs.length}...);
}
const link = paragraphs[i];
let nodePath;
// Extract nodePath from href or use index
if (link.href) {
nodePath = link.href.split("/").slice(-2).join("/");
} else {
// Fallback: construct nodePath from index
nodePath = `sections/0/paragraphs/${i}`;
}
try {
// Update paragraph style if provided
if (styleName) {
await wordsApi.updateParagraphFormat(
new UpdateParagraphFormatRequest({
name: fileName,
nodePath: nodePath,
paragraphFormatDto: new ParagraphFormat({ styleName })
})
);
}
// Update font properties if provided
if (fontOptions) {
// Get all runs in this paragraph
const runsResult = await wordsApi.getRuns(
new GetRunsRequest({ name: fileName, paragraphPath: nodePath })
);
const runs = runsResult.body?.runs?.runLinkList || runsResult.runs?.runLinkList || [];
// Build font object
const fontObj = new model.Font();
if (fontOptions.size !== undefined) fontObj.size = fontOptions.size;
if (fontOptions.name) {
fontObj.name = fontOptions.name;
fontObj.nameAscii = fontOptions.name;
fontObj.nameBi = fontOptions.name;
fontObj.nameFarEast = fontOptions.name;
fontObj.nameOther = fontOptions.name;
fontObj.nameHighAnsi = fontOptions.name;
}
if (fontOptions.bold !== undefined) fontObj.bold = fontOptions.bold;
if (fontOptions.italic !== undefined) fontObj.italic = fontOptions.italic;
if (fontOptions.color) {
const hex = fontOptions.color.replace('#', '');
const r = parseInt(hex.substring(0, 2), 16);
const g = parseInt(hex.substring(2, 4), 16);
const b = parseInt(hex.substring(4, 6), 16);
const colorObj = new model.XmlColor({ r, g, b, a: 255 });
fontObj.color = colorObj;
}
// Update each run's font
for (const runLink of runs) {
if (!runLink.href) continue;
const runPath = runLink.href.split("/").slice(-3).join("/");
await wordsApi.updateRunFont(
new UpdateRunFontRequest({
name: fileName,
nodePath: runPath,
fontDto: fontObj
})
);
}
}
} catch (error) {
console.error(`⚠️ Error processing paragraph ${i + 1}: ${error.message}`);
// Continue with next paragraph
}
}
console.log(✅ Finished processing all paragraphs);
// Download updated file
const downloadResp = await wordsApi.downloadFile(
new DownloadFileRequest({ path: fileName })
);
fs.writeFileSync(outputPath, downloadResp.body);
console.log(✅ Updated file saved: ${path.basename(outputPath)});
}
// Run if called directly
if (require.main === module) {
// Example: Change font size, color, bold, italic for all paragraphs
const fontOptions = {
size: 12, // Font size in points
name: ‘Arial’, // Font name
bold: false, // Make text bold
italic: false, // Make text italic
color: ‘#000000’ // Font color in hex (black)
};
// Save to different output file
changeParagraphStyle(“fileA.docx”, null, fontOptions, “fileA_updateds.docx”).catch(console.error);
}
module.exports = changeParagraphStyle;