Wednesday, January 28, 2015

HTML text to PDF with Beautiful Soup and xtopdf

By Vasudev Ram

Recently, I thought of getting the text from HTML documents and putting that text to PDF. So I did it :)

Here's how:

A demo program to show how to convert the text extracted from HTML 
content, to PDF. It uses the Beautiful Soup library, v4, to 
parse the HTML, and the xtopdf library to generate the PDF output.
Beautiful Soup is at:
xtopdf is at:
Guide to using and installing xtopdf:
Author: Vasudev Ram -
Copyright 2015 Vasudev Ram

import sys
from bs4 import BeautifulSoup
from PDFWriter import PDFWriter

def usage():
    sys.stderr.write("Usage: python " + sys.argv[0] + " html_file pdf_file\n")
    sys.stderr.write("which will extract only the text from html_file and\n")
    sys.stderr.write("write it to pdf_file\n")

def main():

    # Create some HTML for testing conversion of its text to PDF.
    html_doc = """
            Test file for HTMLTextToPDF
        This is text within the body element but outside any paragraph.
        This is a paragraph of text. Hey there, how do you do?
        The quick red fox jumped over the slow blue cow.
        This is another paragraph of text.
        Don't mind what it contains.
        What is mind? Not matter.
        What is matter? Never mind.
        This is also text within the body element but not within any paragraph.

    pw = PDFWriter("HTMLTextTo.pdf")
    pw.setFont("Courier", 10)
    pw.setHeader("Conversion of HTML text to PDF")
    pw.setFooter("Generated by xtopdf:")
    # Use method chaining this time.
    for line in BeautifulSoup(html_doc).get_text().split("\n"):

if __name__ == '__main__':

The program uses the Beautiful Soup library for parsing and extracting information from HTML, and xtopdf, my Python library for PDF generation.
Run it with:
and the output will be in the file HTMLTextTo.pdf.
Screenshot below:

- Vasudev Ram - Python training and programming - Dancing Bison Enterprises

Read more of my posts about Python or read posts about xtopdf (latter is subset of former)

Signup to hear about my new software products or services.

Contact Page

1 comment:

Vasudev Ram said...

My apologies to anyone who sees this post twice via Planet Python or other aggregators / feed readers. I made a last minute edit to the post, adding links to relevant libraries, due to which duplicate posts may be seen.