Skip to content

Instantly share code, notes, and snippets.

@cyrusn
Last active October 7, 2021 02:06
Show Gist options
  • Save cyrusn/ea1bb27653a8dded7e939ab65f4da6c8 to your computer and use it in GitHub Desktop.
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`.
#!/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