python - 带有python脚本的pdf-latex,自定义python变量到latex输出
问题描述
我目前有以下代码可用于生成 PDF 输出。除了在这里完成之外,还有更好的方法来编写 PDF 的内容吗?这是一个基本的 pdf,但我希望在以后的版本中包含多个变量。我已将在 PDF 内容之前定义的变量 x 插入到乳胶 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')```
解决方案
如本视频所述,我认为更好的方法是从 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}
推荐阅读
- python - 优化功能(针对 SARIMA 模型),加速 Python
- javascript - 如何在 AmCharts4 中添加要导出的外部容器(标题)?
- azure - Azure 基础架构存档和还原
- java - Amazon SQS 队列轮询 Spring Boot
- javascript - 根据另一个数组中存在的键从 javascript 对象数组中删除重复键
- entity-framework-core - EF Core 5 列名“OwnerIdOwner”无效
- wordpress - 如何使用 AWS LightSail 分发配置 WordPress 301 重定向?
- php - php工匠队列:工作命令不起作用
- statistics - 是否有一个回归包可以自动找到自变量中的最佳领先和滞后?
- adsense - 由于恶意或不需要的外部链接,Google Ads 拒绝了我们的网站,但我们在任何地方都找不到提到的链接 (debysale.com)