Search code examples
phpprintingwampexec

Printing Word document from PHP in WAMP


So, I have this printer that doesn't have drivers for any OS other than Windows, so, I wanted to run a server on a Windows PC that is attached to the printer, so that I can upload a file from any device in the local network and have a PHP script invoke MS Word on the file to print it. The command I have to invoke Word to print a document works when I give it from the command line and the file upload works, but when the command is run from the PHP script with system() or exec(), it does not work. I see WINWORD.exe running from the Task Manager, but with no GUI showing and no printing happening. I am running the latest WAMP on Windows 8 and I have tried going into services.msc and changing the logon for wampapache to my user which is an administrator or enabling the checkbox to allow the service to interact with the desktop, but none of that worked. This is the actual command I am using: "C:\Program Files\Microsoft Office\Office14\WINWORD.EXE" C:\path\file.txt /q /n /mFilePrintDefault /mFileExit. It's in a batch file that I run using exec()

EDIT: I am not trying to print to a network printer, this is a printer that is connected to the server computer and I am using the newest version of WAMP, so I can't use the PHP functions in the linked question. Also, I am trying to print Word documents not raw text. This is specifically about PHP's exec() not working for this case.


Solution

  • I honestly think this is your best bet:

    Since you seem to be having problems with the .bat file approach, I'd suggest trying a PowerShell script instead. For example:

    print_doc.ps1 =>

    Param([string] $filePath)
    # This should handle any file type, including an MS-Word .doc/.docx
    Start-Process -FilePath $filePath -Verb print  
    

    In PHP, you can exec() the script something like this:

    'powershell.exe -noprofile -executionpolicy bypass -file \path\to\script\print_doc.ps1 "' . $path . '"'
    

    Suggestions:

    1. Make sure the path is valid inside of PHP.

      You can use file_exists() and/or realpath() to verify this.

    2. Enable verbose error logging. In PowerShell, I like to use try/catch blocks and the $error object.