title: Win32API Printing with Python & GSPrint not working
body: <p>I've been trying to print a PDF document created with Reportlab through the Win32API module and GSPrint.</p>
  
  <p>Using the command line works like a breeze but when I am using <code>Win32API.ShellExecute()</code> nothing seems to be printing.</p>
  
  <p>Here is the code I invoke on PDF creation; the <code>filename = tempfile.mktemp(".pdf")</code> is used for temp pdf creation.</p>
  
  <pre><code>hInstance = win32api.ShellExecute(
    0,
    "open",
    "gsprint.exe",
    '-printer "HP LaserJet 3055 PCL6 Class Driver" ' + filename,
    ".",
    0
  )
  print filename
  </code></pre>
  
  <p>A handleInstanceID is also return which is 42, but nothing goes to the printer.</p>
  
  <p>The setup is such that JSON data is passed using NodeJS to Python using STDIN and I have used the <code>python-shell</code> module. When the python script receives a JSON doc it creates a PDF using ReportLab in a temp file then invokes ShellExecute which in returns the hInstance code back to NodeJS.</p>
  
  <p>Some light on this would be really helpful.</p>
  
  <p><strong>NodeJS App is running as a Windows Service using node-windows</strong></p>
  
  <p>NodeJS Script</p>
  
  <pre><code>app.post('/printKot', function (req, res) {
  
      var scriptP = path.join(process.cwd(), 'myPythonScripts', 'demo.py');
  
      //res.json({path: path.join(process.cwd(), 'myPythonScripts')});
  
      var pyshell = new PythonShell('printKot.py', {scriptPath: "C:\\\\Users\\\\Sid\\\\posistFineDine\\\\myPythonScripts" });
  
      // sends a message to the Python script via stdin 
      //pyshell.send(JSON.stringify(req.body.billYoData));
      var kotData = '{"billdata":{"Tp":"Rooftop Table","TN":10,"KN":11,"BN":"12","BD":"2015-06-17T15:09:58.439Z","Name":"","Add":"","St":"","Cy":"","Sta":"","Pin":"","PNm":"","MNm":"","Waiter":"Waiter Sid Gomez","DAmt":0,"Ft":"","WU":false},"billitemsdata":[{"N":"Chilli Bites Potato","Q":1,"R":0,"W":0,"U":""},{"N":"Chicken Ninja ","Q":1,"R":0,"W":0,"U":""},{"N":"Chilli Bites Ckn","Q":1,"R":0,"W":0,"U":""}],"billtaxesdata":[{"N":null,"A":0}],"subtotal":0,"totalTax":0,"roundOff":0,"grandTotal":0,"totalQuantity":3,"iskot":true,"printername":null,"copies":2,"printertype":null}'
  
      pyshell.send(kotData);
  
      pyshell.on('message', function (message) {
          //console.log(message);
          console.log("Printed");
          res.json({msg: message});
      });
  
      pyshell.end(function (err) {
        console.log(err);
      });
  
      console.log("Printed last")
  
      //res.json({msg:true});*/
  
  });
  </code></pre>
  
  <p>Python Script</p>
  
  <pre><code>from reportlab.pdfgen import canvas
  from reportlab.lib.pagesizes import A4, cm, letter
  from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
  from reportlab.platypus import Paragraph, Table, TableStyle 
  from reportlab.lib.enums import TA_JUSTIFY, TA_LEFT, TA_CENTER, TA_RIGHT
  from reportlab.lib import colors
  
  import json
  import tempfile
  import win32api
  import win32print
  import sys
  import base64
  import os
  import subprocess
  
  
  
  #jsonData = sys.stdin
  
  
  #kotObject ='{"billdata":{"Tp":"Table","TN":14,"KN":6,"BN":"16","BD":"2015-06-12T12:57:11.844Z","Name":"","Add":"","St":"","Cy":"","Sta":"","Pin":"","PNm":"","MNm":"","Waiter":"Waiter Sid Gomez","DAmt":0,"Ft":"","WU":false},"billitemsdata":[{"N":"Chow Manchow Chicken","Q":1,"R":0,"W":0,"U":""},{"N":"Double Corn Chicken","Q":1,"R":0,"W":0,"U":""},{"N":"Double Corn Veg","Q":1,"R":0,"W":0,"U":""},{"N":"Whopping Wonton Soup Veg ","Q":1,"R":0,"W":0,"U":""}],"billtaxesdata":[{"N":null,"A":0}],"subtotal":0,"totalTax":0,"roundOff":0,"grandTotal":0,"iskot":true,"totalQuantity": 0, "printername":null,"copies":2,"printertype":null}'
  
  
  bill = json.load(sys.stdin)
  #bill = json.loads(kotObject)
  
  
  filename = tempfile.mktemp(".pdf")
  
  itemLen = len(bill['billitemsdata'])
  taxLen = len(bill['billtaxesdata'])
  
  width, height = A4
  styles = getSampleStyleSheet()
  
  styles.add(ParagraphStyle(name='HeaderFooter', fontName ='Helvetica',fontSize=10, alignment=TA_CENTER))
  
  styles.add(ParagraphStyle(name='RightAlignedValueAmount', fontName ='Helvetica',fontSize=10, alignment=TA_RIGHT))
  
  styles.add(ParagraphStyle(name='Details', fontName ='Helvetica', fontSize=10, alignment=TA_CENTER))
  
  styles.add(ParagraphStyle(name='LeftAligned', fontName='Helvetica', fontSize=10, alignment=TA_LEFT))
  
  
  def coord(x, y, unit=1):
      x, y = x * unit, height -  y * unit
      return x, y
  
  
  hItem = Paragraph('''&lt;b&gt;Items&lt;/b&gt;''', styles["LeftAligned"])
  hQty = Paragraph('''&lt;b&gt;Qty&lt;/b&gt;''', styles["RightAlignedValueAmount"])
  hRate = Paragraph('''&lt;b&gt;Qty&lt;/b&gt;''', styles["RightAlignedValueAmount"])
  
  
  data = []
  
  data.append([Paragraph('Type: &lt;b&gt;%s&lt;/b&gt;' % bill['billdata']['Tp'], styles["LeftAligned"]), '', ''])
  data.append([Paragraph('KOT Number: &lt;b&gt;%s&lt;/b&gt;' % bill['billdata']['KN'], styles["LeftAligned"]), '', ''])
  data.append([Paragraph('Bill Number: &lt;b&gt;%s&lt;/b&gt;' % bill['billdata']['BN'], styles["LeftAligned"])])
  data.append([Paragraph('Date: &lt;b&gt;%s&lt;/b&gt;' % bill['billdata']['BD'], styles["LeftAligned"])])
  data.append([hItem, '', hQty])
  
  
  for item in bill['billitemsdata']:
      data.append([Paragraph('%s' % item['N'], styles["LeftAligned"]), '', Paragraph('%s' % item['Q'], styles["RightAlignedValueAmount"])])
  
  
  data.append(['','',''])
  
  data.append([Paragraph('&lt;b&gt;Total Qty:&lt;/b&gt;', styles["LeftAligned"]), '', Paragraph('%s' % bill['totalQuantity'], styles["RightAlignedValueAmount"])])
  
  
  table = Table(data, colWidths=[5 * cm, 1 * cm, 2 * cm])
  
  table.setStyle(TableStyle([
                          ('VALIGN', (0,0), (-1,-1), 'MIDDLE'),
                          ('SPAN', (0,0),(2,0)),
                          ('SPAN',(0,1), (2,1)),
                          ('SPAN',(0,2), (2,2)),
                          ('SPAN',(0,3), (2,3)),
                          ("LINEBELOW", (0, 3), (-1, 3), 1, colors.black, None, (1,2,3)),
                          ("LINEBELOW", (0, 4), (-1, 4), 1, colors.black, None, (2,2,4)),
                          #('SPAN', (0,-1), (2,-1)),
                          #('SPAN', (0,2), (-1,2)),
                          #("LINEBELOW", (0, 3), (-1, 3), 1, colors.black, None, (1,2,3)),
                          #("LINEBELOW", (0,itemLen+3),(-1,itemLen+3),1, colors.black, None, (1,2,3))
                          #("LINEABOVE", (0, -1), (2, -1), 1, colors.black),
                          #("LINEBELOW", (0, -1), (2, -1), 1, colors.black),
                          #('INNERGRID', (0,0), (-1,-1), 0.25, colors.blue),
                          #('BOX', (0,0), (-1,-1), 0.25, colors.red)
                         ]))
  
  
  c = canvas.Canvas(filename, pagesize=A4)
  #c.line(10,0,10,height)
  #c.setFont('Helvetica', 12)
  #c.drawString(10,840-cm,"Welcome to Reportlab!")
  
  #print "Width %s" % width
  #print "Height %s" % height
  #print "CM %s" % cm
  
  w, h = table.wrap(0, 0)
  
  #print "Table Width %s" % w
  #print "Table Height %s" % h
  
  table.wrapOn(c, width, height)
  table.drawOn(c, 10, height-(h+cm+80))
  c.save()
  
  
  # if sys.version_info &gt;= (3,):
  #   raw_data = bytes ("This is a test", "utf-8")
  # else:
  #   raw_data = "This is a test"
  
  # printer_name = 'HP LaserJet 3055 PCL6 Class Driver'
  # hPrinter = win32print.OpenPrinter (printer_name)
  # try:
  #   hJob = win32print.StartDocPrinter (hPrinter, 1, ("test of raw data", None, "RAW"))
  #   try:
  #     win32print.StartPagePrinter (hPrinter)
  #     win32print.WritePrinter (hPrinter, raw_data)
  #     win32print.EndPagePrinter (hPrinter)
  #   finally:
  #     win32print.EndDocPrinter (hPrinter)
  # finally:
  #   win32print.ClosePrinter (hPrinter)
  
   hInstance = win32api.ShellExecute(
     0,
     "open",
     "gsprint",
     '-printer "HP LaserJet 3055 PCL6 Class Driver" ' + '"%s"' % filename,
     ".",
     0
   )
   print filename
  </code></pre>