Automatic Batch Printing Microsoft Word documents from PHP with COM classes
Brian Flounders wrote this on February 5th, 2007 and filed it in TechTalk.I wanted a way to programmatically print out batch documents from many different folders. I figured I could do this with simple PHP scripting. It was harder to figure out how to do it than I thought, but I believe I found a way:
Create the PHP script:
// Load the COM object
$word = new COM(“Word.Application”) or die(“Unable to instanciate Word”);// bring the document to the front.
$word->Visible = 1;// Word only prints to the default printer, so store the current printer
// and temporarily change it to the printer
// that you want to use (\\\\xxx.xxx.xxx.xxx\PrinterName)
$activePrint1 = $word->ActivePrinter;
$word->ActivePrinter = “\\\\xxx.xxx.xxx.xxx\PrinterName” or die(“Can’t change printer.”);// Open the file and Print.
$word->Documents->Open($filename);
$word->Documents[1]->PrintOut();// change printer back to old default
$word->ActivePrinter = $activePrint1;// Close Word and any processes. False does not save changes, etc.
$word->ActiveDocument->Close(false);
$word->Quit();
$word = null;
unset($word);
After writing this, I was getting many errors: “The requested member of the collection does not exist.”, printer error, etc. Many times, the script would just hang and would throw the “Fatal error: Maximum execution time of 30 seconds exceeded.” There wasn’t much help on the web that I could find. I started messing with the DCOMCFG (Start->Run->DCOMCFG). I found somewhere in there “Microsoft Word Documents” and changed the permission on the user to be “Administrator.” Set the password – and BAM! It works perfectly.


