Search code examples
windows-7-x64jscript

How to print a file with Jscript


Goal

I want to print a file via a PDF printer which isn't the default printer. I was able to temporary change the normal printer to the PDF printer.

Problem

But I don't know how to print a .doc, .txt or .xls via Jscript. Also, I can't find a way to save the default printer name so I can switch back after I've printed the file.

Jscript code

var objShell = new ActiveXObject("Shell.Application");
var objFSO = new ActiveXObject("Scripting.FileSystemObject");    

try {
  var PDFCreatorQueue = new ActiveXObject("PDFCreatorBeta.JobQueue");
  PDFCreatorQueue.Initialize();

  var sourceFile   = WScript.Arguments(0)
  var sourceFolder = objFSO.GetParentFolderName(sourceFile)
  var sourceName   = objFSO.GetBaseName(sourceFile)
  var targetFile   = sourceFolder + "\\" + sourceName + ".pdf"  

  //HERE GOES THE COMMAND TO SAVE THE CURRENT DEFAULT PRINTER NAME TO A TEMP VARIABLE
  objNet.SetDefaultPrinter("PDFCreator");
  //HERE GOES THE PRINT COMMAND WHICH I DON'T KNOW
 // HERE GOES THE COMMAND TO CHANGE BACK TO THE OLD DEFAULT PRINTER

  if(!PDFCreatorQueue.WaitForJob(3)) {
    WScript.Echo("The print job did not reach the queue within " + 3 + " seconds"); 
  }
  else {
    var job = PDFCreatorQueue.NextJob;  
    job.SetProfileByGUID("DefaultGuid");
    job.ConvertTo(targetFile);

    if(!job.IsFinished || !job.IsSuccessful) {
        WScript.Echo("Could not convert the file: " + targetFile);
    }
  }  
  PDFCreatorQueue.ReleaseCom();
}
catch(e) {
  WScript.Echo(e.message);
  PDFCreatorQueue.ReleaseCom();
}

Solution

  • Use the ShellFolderItem.InvokeVerbEx() function. The JScript example code in the MSDN article shows how to use it. Make the first argument "print" and the second argument the name of the printer. So you can remove the code that tinkers with the default printer.