how to check my last page is empty or not ? insert Html on it if last page empty in word

フนӥăіḑ Ṁ' 20 Reputation points
2023-10-11T03:40:25.3266667+00:00

I want if my last page is empty then insert Html on it if last page is not empty then create a new page and insert my html on it. this is my code this is working some time but sometimes it is not working when I have any table on last page.

async function PartTitle(event) {
    try {
        await Word.run(async (context) => {
            const body = context.document.body;

            // Check if the last paragraph contains text
            const paragraphs = body.paragraphs;
            const lastParagraph = paragraphs.getLast();
            lastParagraph.load("text");

            await context.sync();

            if (lastParagraph.text !== "") {
                body.insertBreak(Word.BreakType.page, Word.InsertLocation.end);
            }

            // Insert the custom structure at the end of the document
            const updatedLastParagraph = paragraphs.getLast();
            const range = updatedLastParagraph.getRange();
            const contentControl = range.insertContentControl();
            contentControl.tag = "PartTitle-" + UUID();
            // Set the appearance of the content control to "hidden" or "boundingBox"
            contentControl.appearance = Word.ContentControlAppearance.hidden;
            contentControl.insertHtml(
                `<h1 style='margin-top:0in;margin-right:0in;margin-bottom:12.0pt;margin-left:0in;text-align:center;font-size:21px;font-family:"Calibri",sans-serif;color:black;'>Part Title</h1>
<h4 style='margin-top:0in;margin-right:0in;margin-bottom:12.0pt;margin-left:0in;font-size:21px;font-family:"Calibri",sans-serif;color:black;'>&nbsp;</h4><br />`,
                Word.InsertLocation.end);

            await context.sync();
        });
        event.completed();

    } catch (error) {
        console.log(error);
        ErrorMesage();
    }
};
Microsoft 365 and Office Development Office JavaScript API
Microsoft 365 and Office Development Other
Microsoft 365 and Office Install, redeem, activate For business Windows
Microsoft 365 and Office Word For business Windows
0 comments No comments
{count} votes

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.