Create a PDF with HTML and Python

Let’s use tkinter to make an app to create pdf files just with Python. Let’s see what we need to do it.

Installation

First install pdfkt in the cmd or terminal

pip install pdfkit

The path to wkhtmltopdf.exe

You need to tell where is the path to wkhtmltopdf.exe that is installed with pdfkit, as you see in the first lines of code of the script below. In your pc the folder can be different.

You can find the path in the environmental variables of the system

This are the lines in which you tell where wkhtmltopdf.exe is. Remember that you do not have to install it, it is installed when you do pip install pdfkit.

path_wkhtmltopdf = 'C:\\Program Files\\wkhtmltopdf\\bin\\wkhtmltopdf.exe'
config = pdfkit.configuration(wkhtmltopdf=path_wkhtmltopdf)

This config object will be needed at this line:

pdfkit.from_string(content, “pdf2.pdf”, configuration=config)

when you create the pdf from a string, or a file, or a url, otherwise you will get an error.

Here is an example of the GUI.

And this is the output 📂

The entire code of html_to_pdf.py

import tkinter as tk
from tkinter import messagebox
import pdfkit
import os
import codecs

# pip install pdfkit
# this will install wkhtmltopdf
path_wkhtmltopdf = 'C:\\Program Files\\wkhtmltopdf\\bin\\wkhtmltopdf.exe'
config = pdfkit.configuration(wkhtmltopdf=path_wkhtmltopdf)
# pdfkit.from_url("http://google.com", "out.pdf", configuration=config)

class Window():
    def __init__(self):
        self.root = tk.Tk()
        self.widgets()
        self.root.mainloop()

    def widgets(self):
        self.menubar = tk.Menu(self.root)
        self.menubar.add_command(label="Save pdf", command=self.from_string)
        self.menubar.add_command(label="Open pdf", command=self.open)
        self.menubar.add_command(label="Help", command=self.help)
        self.root.config(menu=self.menubar)
        self.label = tk.Label(self.root, text="SCRIPT GENTLY OFFERED BY @PYTHONPROGRAMMI AKA GIOVANNIPYTHON")
        self.label.pack()
        self.txbx = tk.Text(self.root, height=20, insertbackground="white")
        self.txbx['font'] = "Arial 14"
        self.txbx['bg'] = "black"
        self.txbx['fg'] = "white"
        self.txbx['borderwidth'] = 2
        self.txbx.pack(fill=tk.BOTH, expand=1)
        self.txbx.focus()
        self.txbx.bind("<Control-s>", self.from_string)
        self.txbx.bind("<Control-o>", self.open)

    def open(self, event=""):
        os.startfile("pdf2.pdf")

    def help(self, event=""):
        messagebox.showinfo("HELP", "Scrivi qualcosa usando anche l'HTML\nCTRL + s per salvare il file\CTRL + o per aprirlo nel beowser")

    def from_file(self):
        with open("pdf.html", "w") as file:
            file.write(content)
        pdfkit.from_file("pdf.html", "pdf2.pdf", configuration=config)


    def from_string(self, event=""):
        content = self.txbx.get("0.0", tk.END)
        content = content.replace("\n", "<br>")
        pdfkit.from_string(content, "pdf2.pdf", configuration=config)
        print("Salvato file pdf (ctrl+o per vederlo)")
        messagebox.showinfo("File creato","CTRL + o per aprire il file")



win = Window()

In the class Window we got the GUI, with menu, text area etc. With CTRL+s you will create the file, with CTRL+o you will open it into the browser. You can use, of course html to create titles, paragraphs, change colors and load images too to include into the pdf, so you can make everything you want. You can also make a great thing: put an address of a web page and get the pdf of it.

Let’s see how bard described my code

The code you provided is a Python script that uses the pdfkit library to create a PDF file from either a string or a URL. The script first imports the necessary libraries, including tkinter, messagebox, pdfkit, os, and codecs. It then defines a class called Window, which contains the main functionality of the script. The Window class has a number of methods, including widgets(), from_string(), from_url(), open(), help(), and get_content().

The widgets() method creates the user interface for the script. It creates a menu bar with three menu items: PDF from String, PDF from URL, and Open pdf. The menu items call the from_string(), from_url(), and open() methods, respectively.

The from_string() method takes a string as input and creates a PDF file from it. The string can contain any HTML content. The from_url() method takes a URL as input and creates a PDF file from the content of the URL. The open() method opens the PDF file in the default PDF viewer.

The help() method displays a help message that explains how to use the script. The get_content() method gets the content of the text box in the user interface.

The main() method creates an instance of the Window class and starts the mainloop.

To run the script, you can save it as a Python file and then run it from the command line. For example, if you save the script as pdfkit.py, you can run it by typing the following command into the command line:

python pdfkit.py

This will create a PDF file called pdf2.pdf in the current directory. You can then open the PDF file in your default PDF viewer.

Goog job bard. BTW chatGPT wasn’t working for the same duty, some issues today. Boh?!

An example of an output

Let me show how you can use this tool that I also put in this github repository at the voice html_to_pdf.py

https://github.com/formazione/tkinter_tutorial

https://github.com/formazione/tkinter_tutorial/blob/master/html_a_pdf2.py

The code has been updated with from_url, but it does not work properly.

If you write this into the app:

You will get this pdf


Subscribe to the newsletter for updates
Tkinter templates
Avatar My youtube channel

Twitter: @pythonprogrammi - python_pygame

Videos

Speech recognition game

Pygame's Platform Game

Other Pygame's posts

Published by pythonprogramming

Started with basic on the spectrum, loved javascript in the 90ies and python in the 2000, now I am back with python, still making some javascript stuff when needed.