Welcome, guest | Sign In | My Account | Store | Cart

This recipe shows how to serve PDF from a server written using Netius, a pure-Python library, together with xtopdf, a Python toolkit for PDF creation. It is a proof-of-concept recipe, to show the essentials needed for the task, so it hard-codes the text content that is served as PDF, but the concepts shown can easily be extended to serve dynamically generated PDF content.

Python, 32 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
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.')
    pw.close()
    pdf_fil = open('hello-from-netius.pdf', 'rb')
    pdf_str = pdf_fil.read()
    pdf_len = len(pdf_str)
    pdf_fil.close()
    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)

Netius is a pure-Python network programming library. xtopdf is a Python library for PDF generation from other input formats. The recipe shows how to use the netius and xtopdf to serve PDF content to clients.

Netius web site:

http://netius.hive.pt/

xtopdf site on Bitbucket:

https://bitbucket.org/vasudevram/xtopdf

2 comments

Vasudev Ram (author) 9 years, 3 months ago  # | flag

More detailed description of the solution in this blog post:

http://jugad2.blogspot.in/2014/10/pdf-in-net-with-netius-pure-python_31.html

Vasudev Ram (author) 9 years, 3 months ago  # | flag

The code for the client corresponding to the above Netius server, is available here:

http://jugad2.blogspot.in/2014/11/pdf-in-net-with-netius-python-client.html

Since it is so simple, I am not posting it as a separate recipe on ActiveState.