Generating pdf-latex with python script

后端 未结 4 1698
庸人自扰
庸人自扰 2020-11-29 17:29

I\'m a college guy, and in my college, to present any kind of homework, it has to have a standard coverpage (with the college logo, course name, professor\'s name, my name a

4条回答
  •  旧时难觅i
    2020-11-29 18:18

    There are of course templating systems like Jinja, but they're probably overkill for what you're asking. You can also format the page using RST and use that to generate LaTeX, but again that's probably overkill. Heck, auto-generating the page is probably overkill for the number of fields you've got to define, but since when did overkill stop us! :)

    I've done something similar with Python's string formatting. Take your LaTeX document above and "tokenize" the file by placing %(placeholder_name1)s tokens into the document. For example, where you want your class name to go, use %(course_name)s

    \textbf{\Large "%(homework_title)s" \\}
    \vspace{1cm}
    \textbf{\Large "%(course_name)s" \\}
    

    Then, from Python, you can load in that template and format it as:

    template = file('template.tex', 'r').read()
    page = template % {'course_name' : 'Computer Science 500', 
                       'homework_title' : 'NP-Complete'}
    file('result.tex', 'w').write(page)
    

    If you want to find those tokens automatically, the following should do pretty well:

    import sys
    import re
    import subprocess
    
    template = file('template.tex', 'r').read()
    pattern = re.compile('%\(([^}]+)\)[bcdeEfFgGnosxX%]')
    tokens = pattern.findall(template)
    
    token_values = dict()
    for token in tokens:
        sys.stdout.write('Enter value for ' + token + ': ')
        token_values[token] = sys.stdin.readline().strip()
    
    page = template % token_values
    file('result.tex', 'w').write(page)
    
    subprocess.call('pdflatex result.tex')
    

    The code will iterate across the tokens and print a prompt to the console asking you for an input for each token. In the above example, you'll get two prompts (with example answers):

    Enter value for homework_title: NP-Complete
    Enter value for course_name: Computer Science 500
    

    The final line calls pdflatex on the resulting file and generates a PDF from it. If you want to go further, you could also ask the user for an output file name or take it as an command line option.

提交回复
热议问题