I believe your goal as follows.
- You want to retrieve the page size and the orientation of Google Document.
- You want to achieve this using Google Apps Script.
Issue and workaround:
- In the current stage, when the page size is retrieved using Document service and Google Docs API, the width and height are the constant even when the orientation is changed from portrait to landscape. This has already been mentioned in your question and an answer. I think that this might be the current situation or a bug.
- But, fortunately, Google Document can be converted to DOCX data. And, DOCX data can be parsed using XmlService. Ref Because the format of DOCX data has already been published. Ref
By this, in this answer, I would like to propose the following flow as a workaround.
- Convert Google Document to DOCX data.
- Parse the DOCX data using XmlService.
- Retrieve the page size of each page.
When this flow is reflected to Google Apps Script, it becomes as follows.
Sample script:
function myFunction() {
const documentId = "###"; // Please set the Document ID.
// or you can also use const documentId = DocumentApp.getActiveDocument().getId();
const url = "https://docs.google.com/feeds/download/documents/export/Export?exportFormat=docx&id=" + documentId;
const blob = UrlFetchApp.fetch(url, {headers: {authorization: "Bearer " + ScriptApp.getOAuthToken()}}).getBlob().setContentType(MimeType.ZIP);
const documentXml = Utilities.unzip(blob).filter(b => b.getName() == "word/document.xml")[0];
const xml = XmlService.parse(documentXml.getDataAsString());
const root = xml.getRootElement();
const nsw = root.getNamespace("w");
const res = root.getChild("body", nsw).getChildren("p", nsw).reduce((ar, e) => {
const pPr = e.getChild("pPr", nsw);
if (pPr) {
const sectPr = pPr.getChild("sectPr", nsw);
if (sectPr) {
const pgSz = sectPr.getChild("pgSz", nsw);
ar.push({width: pgSz.getAttribute("w", nsw).getValue() / 20, height: pgSz.getAttribute("h", nsw).getValue() / 20, orientation: pgSz.getAttribute("orient", nsw).getValue()});
}
}
return ar;
}, [])
console.log(res)
}
Result:
When above script is run, the following result is obtained. When the orientation of the page is changed, the object is added as follows.
[
{ width: 612, height: 792, orientation: 'portrait' },
{ width: 792, height: 612, orientation: 'landscape' },
{ width: 612, height: 792, orientation: 'portrait' },
,
,
,
]
Note:
- In this case, the page size can be retrieved for
portrait and landscape pages. But, I couldn't retrieve the page number. I think that the reason of this might be due to the DOCX is managed by the paragraph.
References: