我一直在尝试通过Win32API模块和GSPrint打印使用Reportlab创建的PDF文档。
使用命令行就像轻而易举,但当我使用Win32API.ShellExecute()
时,似乎没有任何东西正在打印。
这是我在PDF创建时调用的代码; filename = tempfile.mktemp(".pdf")
用于临时pdf创建。
hInstance = win32api.ShellExecute(
0,
"open",
"gsprint.exe",
'-printer "HP LaserJet 3055 PCL6 Class Driver" ' + filename,
".",
0
)
print filename
还会返回一个handleInstanceID,它返回42,但没有任何东西进入打印机。
设置是使用STDIN使用NodeJS将JSON数据传递给Python,并且我使用了python-shell
模块。当python脚本收到JSON文档时,它会在临时文件中使用ReportLab创建PDF,然后调用ShellExecute,它将hInstance代码返回给NodeJS。
对此的一些启示将非常有用。
NodeJS App使用node-windows
作为Windows服务运行NodeJS脚本
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});*/
});
Python脚本
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('''<b>Items</b>''', styles["LeftAligned"])
hQty = Paragraph('''<b>Qty</b>''', styles["RightAlignedValueAmount"])
hRate = Paragraph('''<b>Qty</b>''', styles["RightAlignedValueAmount"])
data = []
data.append([Paragraph('Type: <b>%s</b>' % bill['billdata']['Tp'], styles["LeftAligned"]), '', ''])
data.append([Paragraph('KOT Number: <b>%s</b>' % bill['billdata']['KN'], styles["LeftAligned"]), '', ''])
data.append([Paragraph('Bill Number: <b>%s</b>' % bill['billdata']['BN'], styles["LeftAligned"])])
data.append([Paragraph('Date: <b>%s</b>' % 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('<b>Total Qty:</b>', 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 >= (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