Last active
October 7, 2021 02:06
-
-
Save cyrusn/ea1bb27653a8dded7e939ab65f4da6c8 to your computer and use it in GitHub Desktop.
macOS JXA script to convert word files (docx) to pdf. Change the file to executable `chmod 777 ./convertWordFile2PDF.js` and run it by `./convertWordFile2PDF.js`.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env osascript -l JavaScript | |
/* | |
* [resource](https://github.com/JXA-Cookbook/JXA-Cookbook/wiki) | |
*/ | |
const app = Application.currentApplication(); | |
// allow to use `chooseFile` and `chooseFolder` methods | |
app.includeStandardAdditions = true; | |
const filePaths = app.chooseFile({ | |
withPrompt: "Pick docx files for converting to PDF", | |
multipleSelectionsAllowed: true, | |
}); | |
const outputFolder = app.chooseFolder({ | |
withPrompt: "Pick the location to store the PDFs", | |
}); | |
const word = Application("Microsoft Word"); | |
filePaths.forEach((filePath) => { | |
const { isWordDocument, fileName } = getFileName(filePath, outputFolder); | |
if (!isWordDocument) { | |
console.log(`${filePath} is not a word document.`); | |
return; | |
} | |
// The `open` method didn't return document, using `activeDocument` instead. | |
word.open(filePath); | |
const doc = word.activeDocument; | |
word.saveAs(doc, { | |
fileName, | |
fileFormat: "format PDF", | |
}); | |
doc.close({ saving: "no" }); | |
}); | |
function getFileName(filePath, outputFolder) { | |
const wordExtRe = /(\.docx|\.doc)$/; | |
const inputPath = filePath.toString(); | |
const found = inputPath.match(wordExtRe); | |
const filename = inputPath.split("/").pop().replace(wordExtRe, ".pdf"); | |
const fileName = `${outputFolder}/${filename}`; | |
return { | |
isWordDocument: Boolean(found), | |
fileName, | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment