0

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.

libby
  • 585
  • 4
  • 15
  • 1
    Does this answer your question? [Render Latex text with python](https://stackoverflow.com/questions/38168292/render-latex-text-with-python) – Brian61354270 Mar 10 '20 at 00:13
  • Seemingly also related: https://stackoverflow.com/questions/8085520/generating-pdf-latex-with-python-script – AMC Mar 10 '20 at 00:42

1 Answers1

0

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 O.K. as a proof-of-concept on small files.

Dave W. Smith
  • 24,318
  • 4
  • 40
  • 46