How To Convert HTML Page Into PDF File Using Python

About this Post

In this post I will be sharing a simple python script to create a flask application where we can upload html file and script will convert it into PDF file.

Prerequisite

  • Python 2 / Python 3

Python Packages Required

  • Flask (To run the application)
  • Xhtml2Pdf (Package used to convert html to pdf)

HTML Links That Can Be Chosen As Sample File

from flask import Flask, flash, request, redirect, url_for, make_response
from io import BytesIO, StringIO
from xhtml2pdf import pisa

#only html file is allowed to upload
ALLOWED_EXTENSIONS = set(['html'])

#flask app
app = Flask(__name__)

#function to check allowed file
def allowed_file(filename):
    return '.' in filename and \
           filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS

#function to convert html into pdf
def create_pdf(sourceHtml):
    output = BytesIO()
    pisa.pisaDocument(sourceHtml, dest=output)
    return output.getvalue()

#flask app route
@app.route("/", methods=['GET', 'POST'])
def index():
    if request.method == 'POST':
        file = request.files['file']
        if file and allowed_file(file.filename):
            pdf_contents = create_pdf(file)
            pdf_contents = pdf_contents.decode("UTF-8", 'ignore')
            response = make_response(pdf_contents)
            response.headers.set('Content-Type', 'application/pdf')
            response.headers.set('Content-Disposition', 'inline;', filename="filename.pdf")
            return response


        else:
            return """
                        <!doctype html>
                        <title>Upload new File</title>
                        <h1>Kindly upload only .html file</h1>
                        <form action="" method=post enctype=multipart/form-data>
                          <p><input type=file name=file>
                             <input type=submit value=Generate Pdf>
                        </form>
                        """

    return """
    <!doctype html>
    <title>Upload new File</title>
    <h1>Upload new File</h1>
    <form action="" method=post enctype=multipart/form-data>
      <p><input type=file name=file>
         <input type=submit value=GetPdf>
    </form>
    """


if __name__ == "__main__":
    app.run(host='0.0.0.0', port=5001, debug=True)


Screenshots


HTML File

Flask App (localhost:5001)

Generated PDF



Comments

Post a Comment

Popular posts from this blog

Highlight Text In PDF With Different Colors Using Python

Basic of Python - Variable and Memory Address