Not so long ago, I was faced with 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 web site) and a document was printed with this 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 when using this option there are several drawbacks:
- Very slow request processing
- It is necessary to form a PDF document somewhere and return a link to it.
- Constantly you need to choose a printer (if you have only one printer connected to Google cloud print, you still need to choose between it and saving 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 Ubuntu Linux. 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 with the xhtml2pdf library. First, install the necessary packages:
')
sudo apt-get install python-cups python-pip python-dev
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 shows how everything works:
It's all very simple and clear. Images can be inserted with normal HTML code:
<p><img src='/home/usr/image.jpg'/>
But the question arises: "
Where to store the data and where to get it for printing? ".
For this we will use the
Parse service. This is a good free cloud for storing your data. It is convenient to use it in that 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. To get them from Pars we use the code:
connection = httplib.HTTPSConnection('api.parse.com', 443) connection.connect() connection.request('GET', '/1/classes/TestPay', '', { "X-Parse-Application-Id": "<b>yourAppId</b>", "X-Parse-REST-API-Key": "<b>yourRestApiKey</b>" }) result = json.loads(connection.getresponse().read())
Here
yourAppId is the key to your application, and
yourRestApiKey is the key to Api that you use. Read more on the site. Next, you process the result array as a JSON object and can insert it into your HTML page, which will immediately go to print.
If you have any questions, tips, or you just decide to express your opinion on the article - write in the comments. Happy New Year, everyone!