Search code examples
google-apps-scriptgoogle-docsgoogle-docs-api

How to set the Google Doc page layout from App Script


Is there a way to set the Google Doc page layout to landscape using App Script.

I have a script that copies the Google Spreadsheet table to Google Doc but its too wide to display properly. If I could change the layout to landscape it will display properly.

It also seems as though the page width is the same number regardless of whether the page is oriented portrait or landscape.

Another problem is if I body.setPageWidth(792).setPageHeight(612) for letter, it changes the page width and height but does not change to landscape.


Solution

  • I believe your goal is as follows.

    • You want to change the page layout between landscape and portrait using Google Apps Script.

    Unfortunately, it seems that in the current stage, the Document service (DocumentApp) cannot achieve this. But, fortunately, when Google Docs API is used, this can be achieved. In this case, how about the following sample script?

    Sample script:

    Before you use this script, please enable Google Docs API at Advanced Google services.

    function myFunction() {
      const docId = DocumentApp.create("sampleFilename").getId(); // or please manually set the document ID.
      Docs.Documents.batchUpdate({ requests: [{ updateDocumentStyle: { documentStyle: { flipPageOrientation: true }, fields: "flipPageOrientation" } }] }, docId);
    }
    
    • When this script is run, the Google Document is created with the page layout of landscape.
    • If you want to set the page layout to "landscape", please use flipPageOrientation: true.
    • If you want to set the page layout to "portrait", please use flipPageOrientation: false.

    References: