Python PDF xhtml2pdf
# main.py | |
# import section .... | |
from xhtml2pdf import pisa # import python module | |
import sys | |
# Constants section .... | |
# Content to write in our PDF file. | |
SOURCE = "<html><body><p>PDF from string</p></body></html>" | |
# Filename for our PDF file. | |
OUTPUT_FILENAME = "test.pdf" | |
# Template file name | |
TEMPLATE_FILE = "template.html" | |
# Methods section .... | |
def html_to_pdf(content, output): | |
""" | |
Generate a pdf using a string content | |
Parameters | |
---------- | |
content : str | |
content to write in the pdf file | |
output : str | |
name of the file to create | |
""" | |
# Open file to write | |
result_file = open(output, "w+b") # w+b to write in binary mode. | |
# convert HTML to PDF | |
pisa_status = pisa.CreatePDF( | |
content, # the HTML to convert | |
dest=result_file # file handle to recieve result | |
) | |
# close output file | |
result_file.close() | |
result = pisa_status.err | |
if not result: | |
print("Successfully created PDF") | |
else: | |
print("Error: unable to create the PDF") | |
# return False on success and True on errors | |
return result | |
def from_text(source, output): | |
""" | |
Generate a pdf from a plain string | |
Parameters | |
---------- | |
source : str | |
content to write in the pdf file | |
output : str | |
name of the file to create | |
""" | |
html_to_pdf(source, output) | |
def from_template(template, output): | |
""" | |
Generate a pdf from a html file | |
Parameters | |
---------- | |
source : str | |
content to write in the pdf file | |
output : str | |
name of the file to create | |
""" | |
# Reading our template | |
source_html = open(template, "r") | |
content = source_html.read() # the HTML to convert | |
source_html.close() # close template file | |
html_to_pdf(content, output) | |
# Main section ... | |
if __name__ == "__main__": | |
if len(sys.argv)> 1 : | |
if sys.argv[1] == '--help': | |
print('Info: ') | |
print('--help List the options to send an email') | |
print('--text Create a PDF file from a string') | |
print('--template Create a PDF file from a template') | |
elif sys.argv[1] == '--text': | |
print("Creating a PDF file from a string") | |
from_text(SOURCE, OUTPUT_FILENAME) | |
elif sys.argv[1] == '--template': | |
print("Creating a PDF file from a template") | |
from_template(TEMPLATE_FILE, OUTPUT_FILENAME) | |
else: | |
print("Please give the type of message to send.") | |
print("For help execute `python main.py --help`") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment