Skip to content

Instantly share code, notes, and snippets.

@Cartman0
Last active January 4, 2016 18:51
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 Cartman0/5bd4eccc4df96e16a03f to your computer and use it in GitHub Desktop.
Save Cartman0/5bd4eccc4df96e16a03f to your computer and use it in GitHub Desktop.
WSH(JScript)でディレクトリにあるWrodファイルをpdf またはtxtファイルに変換する。
/*
* Wordファイルをpdf に変換
* @cartman
*/
(function () {
var wdFormats = {
pdf: 17,
txt: 2
};
// args
var args = WScript.Arguments;
if (!args.Count()) {
WScript.stdErr.WriteLine('Error: args is null. add a argument "pdf" or "txt".');
WScript.Quit();
}
var format = args.item(0);
if ((format != 'pdf') && (format != 'txt')) {
WScript.stdErr.WriteLine('Error: select a argument "pdf" or "txt".');
WScript.Quit();
}
// create shell object and get current directory.
var shell = new ActiveXObject('WScript.Shell');
var current_dir = shell.CurrentDirectory;
// WScript.Echo(current_dir);
/*
FileSystemObject
- http:\\kujirahand.com/blog/index.php?JScript%E3%81%A7%E3%83%95%E3%82%A1%E3%82%A4%E3%83%AB%E4%B8%80%E8%A6%A7%E3%81%AE%E5%8F%96%E5%BE%97
- https:\\msdn.microsoft.com/ja-jp/library/cc428071.aspx
*/
var fs_obj = new ActiveXObject('Scripting.FileSystemObject');
//指定パスのファイル一覧を得る
var files = fs_obj.GetFolder(current_dir)
.Files;
// create Word Object
var word_obj = new ActiveXObject('Word.Application');
word_obj.Visible = true;
// convert word file to format file
// pdf
var convertToPDF = convertToFileFormatsFuctory('pdf', wdFormats.pdf);
// txt
var convertToTXT = convertToFileFormatsFuctory('txt', wdFormats.txt);
// conrt ONE file.
var e = new Enumerator(files);
for (; !e.atEnd(); e.moveNext()) {
var file = e.item();
var full_file_name = current_dir + '/' + file.Name;
// pdf
if (full_file_name.match(/\.docx?$/g) && format == 'pdf') {
convertToPDF(word_obj, full_file_name);
// txt
} else if (full_file_name.match(/\.docx?$/g) && format == 'txt') {
convertToTXT(word_obj, full_file_name);
}
}
// release & quit
close();
// FunctionFuctory
function convertToFileFormatsFuctory(file_format, wdformat) {
return function (word_obj, fname) {
var fname_out = fname + '.' + file_format;
var doc;
try {
doc = word_obj.Documents.Open(fname);
doc.SaveAs(fname_out, wdformat);
WScript.stdOut.WriteLine('saved as' + file_format + ' ' + fname_out + '.');
} catch (e) {
WScript.stdErr.WriteLine('Error: can not save as ' + file_format + ' ' + fname_out + '.');
doc.Close();
WScript.Quit();
} finally {
doc.Close();
}
};
}
function close() {
shell = null;
fs_obj = null;
e = null;
word_obj.Quit();
WScript.Quit();
}
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment