Skip to content

Instantly share code, notes, and snippets.

@leetking
Created December 15, 2019 09:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save leetking/6835a089714fefe85b3279320feebbda to your computer and use it in GitHub Desktop.
Save leetking/6835a089714fefe85b3279320feebbda to your computer and use it in GitHub Desktop.
a script to convert docx to pdf by word application running in WScript.exe or CScript.exe
/* Batch convert *.docx to *.pdf file using Word application */
function args() {
var ret = [];
for (var i = 0; i < WScript.Arguments.length; i++)
ret[i] = WScript.Arguments(i);
return ret;
}
function print() {
function format(obj) {
switch(typeof(obj)) {
case "undefined":
return "<undefined>";
break;
case "string":
case "number":
case "boolean":
return String(obj);
case "function":
return "<function>";
case "object":
if (null == obj)
return "<null>";
if (obj instanceof Array) {
var arr = [];
for (var k = 0; k < obj.length; k++)
arr.push(format(obj[k]));
return "["+arr.join(", ")+"]";
}
//var arr = [];
//var keys = Object.keys(obj);
//for (var k = 0; k < keys.length; k++) {
// WScript.Echo(keys[i]);
// arr.push(keys[k]+": "+format(obj[keys[k]]));
//}
//return "{"+arr.join(",\n")+"}";
return "<object>";
default:
return "<Unkown Type>";
}
}
var args = print.arguments;
var len = args.length;
var arr = [];
for (var i = 0; i < len; i++)
arr.push(format(args[i]));
WScript.Echo(arr.join(""));
}
function convert(word, from, to)
{
var doc = word.Documents.Open(from);
var format_pdf = 17;
doc.SaveAs(to, format_pdf);
doc.close();
}
function main()
{
var files = args();
var fso = new ActiveXObject("Scripting.FileSystemObject");
try {
var word = new ActiveXObject("Word.Application");
word.Visible = false;
for (var i = 0; i < files.length; i++) {
var from = fso.GetAbsolutePathName(files[i]);
var to = from.replace(/\.docx?$/, ".pdf");
if (!fso.FileExists(from)) {
print("File ", from, " don't exist, ignore it.");
} else {
if (fso.FileExists(to)) {
print("File ", to, " exists, overwrite it!");
}
convert(word, from, to);
print("Convert ", from, " to ", to, " Success!");
}
}
} catch(e) {
print("Please Install Word Application!");
} finally {
word.Quit();
}
}
main();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment