Saturday, January 19, 2013

Save doc as PDF in bulk (JavaScript +Powershell)

SaveAsPDF.js


var fso = new ActiveXObject("Scripting.FileSystemObject");
var docPath = WScript.Arguments(0);
docPath = fso.GetAbsolutePathName(docPath);

var pdfPath = docPath.replace(/\.doc[^.]*$/, ".pdf");
var objWord = null;

try
{
    WScript.Echo("Saving '" + docPath + "' as '" + pdfPath + "'...");

    objWord = new ActiveXObject("Word.Application");
    objWord.Visible = false;

    var objDoc = objWord.Documents.Open(docPath);

    var wdFormatPdf = 17;
    objDoc.SaveAs(pdfPath, wdFormatPdf);
    objDoc.Close();

    WScript.Echo("Done.");
}
finally
{
    if (objWord != null)
    {
        objWord.Quit();
    }
}

Put the SaveAsPdf.js in E:\
E:\NTU\dCOMM101\session2\case study\ is where the doc or docx files are

in the Microsoft Power Shell

PS E:\NTU\dCOMM101\session2\case study> ls *doc | %{cscript.exe //nologo E:\SaveAsPdf.js $_}
PS E:\NTU\dCOMM101\session2\case study> ls *docx | %{cscript.exe //nologo E:\SaveAsPdf.js $_}
done



Running the command as script:
save the scripts as xxx.ps1
as admin: Set-ExecutionPolicy Unrestricted

The execution policies you can use are:
  • Restricted - Scripts won’t run.
  • RemoteSigned - Scripts created locally will run, but those downloaded from the Internet will not (unless they are digitally signed by a trusted publisher).
  • AllSigned - Scripts will run only if they have been signed by a trusted publisher.
  • Unrestricted - Scripts will run regardless of where they have come from and whether they are signed.
You can set PowerShell’s execution policy by using the following cmdlet:
Set-ExecutionPolicy <policy name>

No comments:

Post a Comment