Using Python's Django framework to generate PDF files,

Source: Internet
Author: User
Tags image processing library

Using Python's Django framework to generate PDF files,

The portable document format (PDF) is developed by Adobe and is mainly used to present printable documents, including pixel-perfect format, embedded fonts, and 2D vector images. You can think of a PDF document as the digital equivalent of a printed document; indeed, PDFs are often used in distributing parameters for the purpose of printing them.

It's easy to use Python and Django to generate PDF documentation thanks to an outstanding open source library, ReportLab (http://www.reportlab.org/rl_toolkit.html ). The advantage of dynamic PDF file generation is that different PDF files can be generated as needed under different circumstances, such as different users or different content. The advantage of generating PDF files dynamically is that you can create customized PDFs for different purposes say, for different users or different pieces of content.

The following example uses Django and ReportLab to generate a personalized and printable NCAA schedule (tournament brackets) on KUSports.com ).
Install ReportLab

Install the ReportLab library before generating a PDF file. This is usually a very simple process: Its usually simple: just download and install the library from http://www.reportlab.org/downloads.html.

Note

If you are using some new Linux releases, you can check the package management software before installation. ReportLab is added to most software package repositories.

For example, to use the (excellent) Ubuntu release, you only need a simple command line apt-get install python-reportlab to complete the installation.

The user manual (originally in PDF format only) can be downloaded from the http://www.reportlab.org/rsrc/userguide.pdf, which contains some other installation guides.

Import the software package in the Python interaction environment to check whether the installation is successful.

>>> import reportlab

If no error occurs in the command, the installation is successful.
Write View

Similar to CSV, it is easy to dynamically generate a PDF file by Django, because similar file objects can be used by the ReportLab API.

The following is an example of Hello World:

from reportlab.pdfgen import canvasfrom django.http import HttpResponsedef hello_pdf(request):  # Create the HttpResponse object with the appropriate PDF headers.  response = HttpResponse(mimetype='application/pdf')  response['Content-Disposition'] = 'attachment; filename=hello.pdf'  # Create the PDF object, using the response object as its "file."  p = canvas.Canvas(response)  # Draw things on the PDF. Here's where the PDF generation happens.  # See the ReportLab documentation for the full list of functionality.  p.drawString(100, 100, "Hello world.")  # Close the PDF object cleanly, and we're done.  p.showPage()  p.save()  return response

Note the following:

Here, the MIME type is application/pdf. This will tell the browser that this document is a PDF document, not an HTML document. If this parameter is ignored, the browser may regard this file as an HTML document, which may cause strange text in the browser window. If you leave off this information, browsers will probably interpret the response as HTML, which will result in scary gobbledygook in the browser window.

Using the ReportLab API is simple: you only need to pass the response object as the first parameter of canvas. Canvas.

All subsequent PDF generation methods need to be called by the PDF object (p in this example), rather than the response object.

Finally, you need to call the showPage () and save () methods for the PDF file (otherwise you will get a corrupted PDF file ).

Complex PDF files

If you are creating a complex PDF file (or any large data block), use the cStringIO inventory to place the generated PDF file temporarily. CStringIO provides an interface similar to a file object written in C, which can make the system more efficient.

The following is an example of Hello World rewritten using cStringIO:

from cStringIO import StringIOfrom reportlab.pdfgen import canvasfrom django.http import HttpResponsedef hello_pdf(request):  # Create the HttpResponse object with the appropriate PDF headers.  response = HttpResponse(mimetype='application/pdf')  response['Content-Disposition'] = 'attachment; filename=hello.pdf'  temp = StringIO()  # Create the PDF object, using the StringIO object as its "file."  p = canvas.Canvas(temp)  # Draw things on the PDF. Here's where the PDF generation happens.  # See the ReportLab documentation for the full list of functionality.  p.drawString(100, 100, "Hello world.")  # Close the PDF object cleanly.  p.showPage()  p.save()  # Get the value of the StringIO buffer and write it to the response.  response.write(temp.getvalue())  return response

Other possibilities

Python can generate many other types of content. The following describes some other ideas and libraries that can be used to implement them. Here are a few more ideas and some pointers to libraries you cocould use to implement them:

ZIP file: the Python standard library contains the zipfile module, which can read and write compressed ZIP files. It can be used to generate compressed packages of some files as needed or compress large files as needed. If it is a TAR file, you can use the standard library tarfile module.

Dynamic images: Python image processing Library (PIL; http://www.pythonware.com/products/pil/) is an excellent tool for generating images (PNG, JPEG, GIF, and many other formats. It can be used to automatically generate thumbnails for images, compress multiple images into a separate frame, or perform Web-based image processing.

Charts: Python has many excellent and powerful chart libraries for drawing charts, on-demand maps, tables, and so on. It is impossible to list all of them, so the following are the highlights of them.

Matplotlib (http://matplotlib.sourceforge.net/) can be used to generate high-quality charts typically generated by matlab or Mathematica.

Pygraphviz (https://networkx.lanl.gov/wiki/pygraphviz) is a Python interface for Graphviz graphical la S (http://graphviz.org/) that can be used to generate structured charts and networks.

In short, all files that can be written can be used together with Django. The possibilities are immense.

We have learned the basic knowledge of generating "non-HTML" content. Let's further summarize it. Django has many built-in tools to generate various types of "non-HTML" content.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.