async function addLetterHeadToDocx(docPath, letterHeadpath, outDir, logger) {
const headDoc = new aw.Document(letterHeadpath);
const contentDoc = new aw.Document(docPath);
const headDocParagraphs = headDoc.sections.toArray()[0].body.paragraphs;
const placeholder = "#*Content Starts Here*#";
const srcSection = contentDoc.sections.toArray()[0];
const targetSection = headDoc.sections.toArray()[0];
targetSection.pageSetup.leftMargin = srcSection.pageSetup.leftMargin;
targetSection.pageSetup.rightMargin = srcSection.pageSetup.rightMargin;
targetSection.pageSetup.topMargin = srcSection.pageSetup.topMargin;
targetSection.pageSetup.bottomMargin = srcSection.pageSetup.bottomMargin;
const fontSettings = getFontSettings();
fontSettings.substitutionSettings.defaultFontSubstitution.defaultFontName = "Arial";
headDoc.fontSettings = fontSettings;
contentDoc.fontSettings = fontSettings;
const warnings = new aw.WarningInfoCollection();
headDoc.warningCallback = warnings;
for (let para of headDocParagraphs.toArray()) {
if (para.getText().includes(placeholder)) {
const builder = new aw.DocumentBuilder(headDoc);
builder.moveTo(para);
let insertAfterNode = para;
const body = headDoc.sections.toArray()[0].body;
const contentNodes = contentDoc.sections
.toArray()[0]
.body.getChildNodes(aw.NodeType.Any, false);
for (let node of contentNodes) {
const importedNode = headDoc.importNode(
node,
true,
aw.ImportFormatMode.KeepSourceFormatting,
);
if (importedNode.nodeType === aw.NodeType.Table) {
const tbl = importedNode.asTable();
if (tbl) {
tbl.autoFit(aw.Tables.AutoFitBehavior.FixedColumnWidths);
tbl.allowAutoFit = false;
}
}
insertAfterNode = body.insertAfter(importedNode, insertAfterNode);
}
// Remove the placeholder paragraph
para.remove();
}
}
const options = new aw.Saving.PdfSaveOptions();
// options.preserveTablesLayout = true;
options.embedFullFonts = true;
options.useCoreFonts = false;
const outputPath = path.resolve(outDir, "final_output.pdf");
fixTableDimentions(headDoc);
removeTrailingEmptyParagraphs(headDoc);
headDoc.updatePageLayout();
enableFontSubstitutionLogging(warnings, logger);
await headDoc.save(outputPath);
await headDoc.save(path.resolve(outDir, "final_doc.docx"))
logger.info("Letter head addition done and saved to :", outputPath);
return outputPath;
}
I using above code to add the content from one docx(content.docx) into a letter head docx(letter_head.docx) to change the header and footer for that content.
But in my output pdf , the content is not showing as expected, the tables in the last page are colliding, also for reference, I saved the output as a docx(final_doc.docx) too.
I am attaching the mentioned files.
please help on what can be done for this.
content.docx (92.0 KB)
final_output.pdf (162.2 KB)
final_doc.docx (136.5 KB)
letter_head.docx (127.8 KB)