I have a list of strings where each element is a line of LaTex.
Using flask, how can I generate the pdf to be return on a request?
For example:
document = []
def add( toAdd ):
global document
document.append( toAdd )
def begin(item):
return "\\begin{"+str(item)+"}"
def end(item):
return "\\end{"+str(item)+"}"
@route('/pdf')
def populate_document( protocol, document ):
TITLE = "title"
AUTHOR = "author"
HEADER = "\\documentclass[12pt]{article}"
ENUMERATE = "enumerate"
DOCUMENT = "document"
STEPS = "steps"
steps = protocol[STEPS]
# KEEP AT TOP
add( HEADER )
# KEEP AT TOP
add( cmd( TITLE, protocol[TITLE] ) )
add( cmd( AUTHOR, protocol[AUTHOR] ) )
add( begin( DOCUMENT ) )
add( cmd( "section*", protocol[TITLE] ) )
add( end( ENUMERATE ) )
add( end( DOCUMENT ) )
### HOW TO COMPILE `document` and RETURN AS PDF?
I'm happy to clarify further if needed.
Thanks in advance.
The key package to making this work is latex . With it, you can do something like this (extracted from a working demo):
from flask import Flask
from jinja2 import FileSystemLoader
from latex import build_pdf
from latex.jinja2 import make_env
app = Flask(__name__)
env = make_env(loader=FileSystemLoader('templates'))
@app.route('/')
def home():
latex_template = env.get_template('example.latex')
pdf = build_pdf(template.render(text='Hello World'))
return bytes(pdf), 200, {
'Content-Type': 'application/pdf',
'Content-Disposition': 'inline; filename="example.pdf"'}
Where example.latex
is from the templates
folder. Converting this to take LaTex from a string is left as an exercise.
This works OK as a proof-of-concept on small files.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.