John S
John S

Reputation: 573

Insert headers and footers office.js api

I am trying to insert header and footers into a document using the office js API in a task pane app. I cant seem to find a way to add headers and footers to the docs.

Upvotes: 3

Views: 2784

Answers (2)

Mark Chequer
Mark Chequer

Reputation: 11

A question: how can you enable the word document to use the different header types? (First and Primary)? It seems I can set the contents of the First and Primary headers and footers, but, without manually changing the document it does not seem to use them.

I am not sure how to reword this (seems clear to me) :(, trying.

A word document uses the same header type for each page unless the document is changed to use different header types. ie, how do I replicate the attached image controls? screen shot

Upvotes: 0

Gab Royer
Gab Royer

Reputation: 9846

Headers and Footers inherit the Body class and can be accessed by initializing a Section. Here is sample from the Office-JS Snippet Explorer :

// Run a batch operation against the Word object model.
Word.run(function (context) {

    // Create a proxy sectionsCollection object.
    var mySections = context.document.sections;

    // Queue a commmand to load the sections.
    context.load(mySections, 'body/style');

    // Synchronize the document state by executing the queued-up commands, 
    // and return a promise to indicate task completion.
    return context.sync().then(function () {

        // Create a proxy object the primary header of the first section. 
        // Note that the header is a body object.
        var myHeader = mySections.items[0].getHeader("primary");

        // Queue a command to insert text at the end of the header.
        myHeader.insertText("This is a header.", Word.InsertLocation.end);

        // Queue a command to wrap the header in a content control.
        myHeader.insertContentControl();

        // Synchronize the document state by executing the queued-up commands, 
        // and return a promise to indicate task completion.
        return context.sync().then(function () {
            console.log("Added a header to the first section.");
        });                    
    });  
})
.catch(function (error) {
    console.log('Error: ' + JSON.stringify(error));
    if (error instanceof OfficeExtension.Error) {
        console.log('Debug info: ' + JSON.stringify(error.debugInfo));
    }
});

Upvotes: 5

Related Questions