首页 > 解决方案 > 带有python脚本的pdf-latex,自定义python变量到latex输出

问题描述

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

PDF 输出 - 图片

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')```

标签: pythonvariableslatexpythonanywhere

解决方案


本视频所述,我认为更好的方法是从 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_version使用以下代码行调用它: save_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}

推荐阅读