Friday, October 31, 2014

PDF in a Net, with Netius, a pure Python network library

By Vasudev Ram

I came across Netius, a pure Python network library, recently.

Excerpt from the Netius home page:

[ Netius is a Python network library that can be used for the rapid creation of asynchronous non-blocking servers and clients. It has no dependencies, it's cross-platform, and brings some sample netius-powered servers out of the box, namely a production-ready WSGI server. ]

Note: They mention some limitations of the async feature. Check the Netius home page for more on that.

To try out netius a little (not the async features, yet), I modified their example WSGI server program to serve a PDF of some hard-coded text, generated by xtopdf, my PDF creation library / toolkit.

The server,, running on port 8080, generates and writes to disk, a PDF of some text, and then reads back that PDF from disk, and serves it to the client.

The client,, uses the requests Python HTTP library to make a request to that server, gets the PDF file in the response, and writes it to disk.

Note: this is proof-of-concept code, without much error handling or refinement. But I did run it and it worked.

Here is the code for the server:

import time
from PDFWriter import PDFWriter
import netius.servers

def get_pdf():
    pw = PDFWriter('hello-from-netius.pdf')
    pw.setFont('Courier', 10)
    pw.setHeader('PDF generated by xtopdf, a PDF library for Python')
    pw.setFooter('Using netius Python network library, at {}'.format(time.ctime()))
    pw.writeLine('Hello world! This is a test PDF served by Netius, ')
    pw.writeLine('a Python networking library; PDF created with the help ')
    pw.writeLine('of xtopdf, a Python library for PDF creation.')
    pdf_fil = open('hello-from-netius.pdf', 'rb')
    pdf_str =
    pdf_len = len(pdf_str)
    return pdf_len, pdf_str

def app(environ, start_response):
    status = "200 OK"
    content_len, contents = get_pdf()
    headers = (
        ("Content-Length", content_len),
        ("Content-type", "application/pdf"),
        ("Connection", "keep-alive")
    start_response(status, headers)
    yield contents

server = netius.servers.WSGIServer(app = app)
server.serve(port = 8080)
In my next post, I'll show the code for the client, and the output.

You may also like to see my earlier posts on similar lines, about generating and serving PDF content using other Python web frameworks:

PDF in a Bottle , PDF in a Flask and PDF in a CherryPy.

The image at the top of this post is of Chinese fishing nets, a tourist attraction found in Kochi (formerly called Cochin), Kerala.

- Enjoy.

- Vasudev Ram - Dancing Bison Enterprises

Signup for email about new products from me.

Contact Page

No comments: