Tables colliding on docx to pdf conversion

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)

@sumithnooti21

It appears that the tables in your output PDF are colliding, which can occur due to various factors such as incorrect table dimensions, margins, or page layout settings. Here are some suggestions to help resolve this issue:

  1. Check Table Dimensions: Ensure that the tables do not exceed the page width. You can set the tables to auto-fit to the page width or manually adjust the column widths.

  2. Adjust Page Layout: Verify that the margins of the sections in both the letterhead and content documents are set correctly. Although you are copying the margins, double-check that they are appropriate for the content.

  3. Update Page Layout: After making changes to the document, ensure that the layout is recalculated based on the current content. If your environment supports it, you may need to call a method to refresh the layout.

  4. Remove Empty Paragraphs: Trailing empty paragraphs can affect the layout. If you are already using a function to remove trailing empty paragraphs, ensure that it is implemented correctly.

  5. PDF Save Options: Consider experimenting with the PDF save options. For instance, if available, setting an option to preserve the table layout during conversion can help maintain the intended structure.

Here’s a snippet to ensure the tables are set to auto-fit:

if (tbl) {
    tbl.autoFit(aw.Tables.AutoFitBehavior.AutoFitToWindow);
}

After making these adjustments, try saving the document again and check if the issue persists. If it does, review the content of the tables for any specific formatting that might be causing the collision.

Tried by following the mentioned steps, but the issue still persists,
Please help if there is anything else to be done here.

@sumithnooti21 The problem arises due to a change in margins, which causes the document content to shift. MS Word produces the same results. To avoid this, do not change the margins, as the size of the header/footer remains the same or larger.

Simple code gives the correct result:

const headDoc = new aw.Document("letter_head.docx");
const contentDoc = new aw.Document("content.docx");

// Get paragraphs from header document
const headDocParagraphs = headDoc.firstSection.body.paragraphs;
const placeholder = "#*Content Starts Here*#";

// Process paragraphs to find placeholder
for (let para of headDocParagraphs.toArray()) {
  if (para.getText().includes(placeholder)) {
    const builder = new aw.DocumentBuilder(headDoc);
    builder.moveTo(para);
    builder.insertParagraph();

    // Insert document inline with formatting options
    builder.insertDocumentInline(contentDoc, aw.ImportFormatMode.KeepSourceFormatting, new aw.ImportFormatOptions());

    para.remove();
    break; // Exit loop after finding and processing the placeholder
  }
}

// Save the merged document
headDoc.save("output.pdf");