Php – How to Open and Print a Word Document Using a VBScript Called From the Web

apache-2.2permissionsPHPvbscriptwindows-server-2003

The university I work for allows students to register their bikes for indoor storage during the winter. This is done through a website. At the end of the process, a DYMO label printer connected to the network is supposed to print out a label that will be stuck to the bike.

Here is the process:

  1. User and bike data is entered into a web form by a staff member. (this works)
  2. User and bike data is stored in an Oracle database. (this works)
  3. PHP running on the web server saves the user and bike data into a CSV file. (this works)
  4. PHP running on the web server calls a VBScript. (this works)
  5. The VBScript opens a Word document that loads the CSV data and prints a label. (problem)

Now, the VBScript works correctly. If I manually run the VBScript, it will open Word, load the CSV data, print a label, and close Word.

Likewise, if I add a bit of code to the end of the VBScript to write a .txt file (for testing purposes) the text file gets written whether I run the script manually or allow it to be run by the website.

As such, I suspect there is a permissions problem preventing the VBScript from accessing Word and/or the printer when run from the web. Any suggestions on how to solve this problem?

The web server is Windows Server 2003 running XAMPP.

If it helps, here is the line in PHP that calls the VBScript:

exec('wscript "D:\CSWebHousing\wwwroot\portal2\bikes\testcode.vbs"');

Here is the relevant portion of the VBScript:

Sub TestCode
Set ws = WScript.CreateObject("WScript.Shell")

OFFICE_PATH = "C:\path_to\Office12"

    file_to_open = CHR(34) & "D:\path_to\Label.doc" & CHR(34)

ws.Run CHR(34)& OFFICE_PATH & "\winword.exe" & CHR(34) & file_to_open, 0, false 


'These lines tab and enter past a dialog box
intTime = 3000
Wscript.Sleep(intTime)
ws.Sendkeys "{TAB}"
intTime = 500
Wscript.Sleep(intTime)
ws.Sendkeys "{TAB}"
intTime = 500
Wscript.Sleep(intTime)
ws.Sendkeys "{ENTER}"
intTime = 4000
Wscript.Sleep(intTime)
ws.Sendkeys "%fx"
End Sub

I think it is a permissions problem, but any ideas would be appreciated.

Thank you.

Best Answer

Having done a large number of scripted installs with vbscript...

I think the issue is SendKey.

SendKey is great if you're launching a vbscript as a person. The focus sometimes gets lost when you're launching the script as some kind of automated process.

It so happens that there's a handy Stack Overflow question on maintaining your window focus with SendKey here: https://stackoverflow.com/questions/16173315/windows-batch-file-not-working-consistently

I hope that helps.