Pdf-latex with python script, custom python variables into latex output

Pdf-latex with python script, custom python variables into latex output

我目前有以下代码可以生成 PDF 输出。除了在此处完成之外,是否有更好的方式来编写 PDF 的内容?这是一个基本的 pdf,但我希望在以后的版本中包含多个变量。我已将在 PDF 内容之前定义的变量 x 插入到乳胶 pdf 中。非常感谢您提供的任何建议。

PDF Output - image

import os
import subprocess

x = 7

content = \
r'''\documentclass{article}
\usepackage[utf8]{inputenc}
\usepackage[margin=1cm,landscape]{geometry}
\title{Spreadsheet}
\author{}
\date{}
\begin{document}''' + \
r'This is document version: ' + str(x) +\
r'\end{document}'


parser = argparse.ArgumentParser()
parser.add_argument('-c', '--course')
parser.add_argument('-t', '--title')
parser.add_argument('-n', '--name',)
parser.add_argument('-s', '--school', default='My U')

args = parser.parse_args()

with open('doc.tex','w') as f:
    f.write(content%args.__dict__)

cmd = ['pdflatex', '-interaction', 'nonstopmode', 'doc.tex']
proc = subprocess.Popen(cmd)
proc.communicate()

retcode = proc.returncode
if not retcode == 0:
    os.unlink('doc.pdf')
    raise ValueError('Error {} executing command: {}'.format(retcode, ' '.join(cmd)))

os.unlink('doc.tex')
os.unlink('doc.log')```

this video 中所述,我认为更好的方法是从 Python 导出变量并使用以下函数将它们保存到 .dat 文件中。

def save_var_latex(key, value):
    import csv
    import os

    dict_var = {}

    file_path = os.path.join(os.getcwd(), "mydata.dat")

    try:
        with open(file_path, newline="") as file:
            reader = csv.reader(file)
            for row in reader:
                dict_var[row[0]] = row[1]
    except FileNotFoundError:
        pass

    dict_var[key] = value

    with open(file_path, "w") as f:
        for key in dict_var.keys():
            f.write(f"{key},{dict_var[key]}\n")

然后就可以调用上面的函数,将所有的变量保存到mydata.dat中。例如,在 Python 中,您可以使用以下代码行保存一个变量并调用它 document_versionsave_var_latex("document_version", 21)

在 LaTeX 中(在主文件的序言中),您只需导入以下包:

% package to open file containing variables
\usepackage{datatool, filecontents}
\DTLsetseparator{,}% Set the separator between the columns.

% import data
\DTLloaddb[noheader, keys={thekey,thevalue}]{mydata}{../mydata.dat}
% Loads mydata.dat with column headers 'thekey' and 'thevalue'
\newcommand{\var}[1]{\DTLfetch{mydata}{thekey}{#1}{thevalue}}

然后在文档正文中使用\var{}命令导入变量,如下:

This is document version: \var{document_version}