Printing a check document using Python and Parse

Not so long ago, I faced a task: printing a document of a certain format using a mobile device. On the phone, certain values ​​had to be entered, sent to the server (so that later this data could be used on the website) and a document was printed with that data. From the very beginning, my choice fell on Google cloud print , since it is as simple as possible to use and solve such problems. But there are several drawbacks to using this option:

  • Very slow request processing
  • It is necessary to form a PDF document somewhere and return a link to it
  • You always need to choose a printer (if you have only one printer connected to Google cloud print, you still need to choose between it and save it to Google Drive)

Therefore, I decided to write my own script for such operations.

My choice fell on the Python programming language, since it is the most flexible and suitable for these tasks. In my development, I used the Ubuntu Linux OS. So the installation of libraries will be presented for her.

From the very beginning, we need to learn how to create a PDF document. The easiest way to convert HTML markup to PDF is using the xhtml2pdf library. First, install the necessary packages:

sudo apt-get install python-cups python-pip

python-cups is a library with which Python can work with your printer, python-pip will make installing xhtml2pdf easier.

Next, install xhtml2pdf:

 sudo pip install xhtml2pdf

The following code will show how everything works:

 #!/usr/bin/env python
 # Печать файла
 import cups
 from xhtml2pdf import pisa
 def main():
       # Имя, для промежуточного файла PDF формата
       filename = "/home/pi/print.pdf"
       # Генерируем контент в виде HTML страницы
       xhtml = "

Test print

\n" xhtml += "

This is printed from within a Python application

\n" xhtml += "

Coloured red using css

\n" pdf = pisa.CreatePDF(xhtml, file(filename, "w")) if not pdf.err: # Закрываем PDF файл - в противном случае мы не сможем прочитать его pdf.dest.close() # Печатаем файл используя CUPS conn = cups.Connection() # Получаем список всех принтеров, подключенных к компьютеру printers = conn.getPrinters() for printer in printers: # Выводим имя принтера в консоль print printer, printers[printer]["device-uri"] # Получаем первый принтер со списка принтеров printer_name = printers.keys()[0] conn.printFile(printer_name, filename, "Python_Status_print", {}) else: print "Unable to create pdf file" if __name__=="__main__": main()

Everything is extremely simple and clear here. Images can be pasted in plain HTML:

But the question arises: " Where to store data and where to get it for printing? ".

To do this, we will use the Parse service . This is a good free cloud to store your data. It is convenient to use because it works on almost all platforms (Roughly speaking: you can add data to the cloud from an Android device, and get it on iOS, PHP, JavaScript and other platforms).

Especially for Python, there is a REST API with which you can send any requests in several lines. In order to get them from Pars, we use the code:

 connection = httplib.HTTPSConnection('', 443)
 connection.request('GET', '/1/classes/TestPay', '', {
       "X-Parse-Application-Id": "yourAppId",
       "X-Parse-REST-API-Key": "yourRestApiKey"
 result = json.loads(connection.getresponse().read())

Here, yourAppId is the key to your application, and yourRestApiKey is the key to the Api that you are using. Read more on the site. Then you process the result array as a JSON object and you can insert it into your HTML page, which will be immediately printed.

If you have any questions, tips or you just decide to express your opinion about the article - write in the comments. Happy New Year, everyone!

Also popular now: