![](/img/trans.png)
[英]How to search for key value pairs in a complex tree-like nested dict based on string values which contains a Jinja-like separators in Python
[英]Jinja-like for Pdf in Python
我正在尋找用於Python的最精確的PDF工具,就像Jinja對HTML一樣。
你有什么建議?
正如jbochi所回答的,ReportLab是幾乎所有生成PDF的Python項目的基礎。
但是根據您的需要,您可能需要查看Pisa / xhtml2pdf 。 您將使用Jinja模板生成HTML,然后使用Pisa將HTML轉換為PDF。 比薩建立在ReportLab之上。
編輯:我忘記的另一個選項是wkhtmltopdf
但是,您只能使用商業版本的模板。
現在有一個名叫WeasyPrint的新孩子。
使用rst2pdf或pandoc對python / jinja到rst / html和html / rst到pdf 怎么 樣 ?
這兩個對我來說都很好。 就像plaes一樣,我可能會在未來嘗試Weasyprint 。
什么更准確的Python工具,像Jinja一樣工作,而不是Jinja本身?
您只需確保Jinja
塊,變量和注釋標識字符串不與LaTeX
命令沖突。 一旦你改變Jinja
環境來模仿LaTeX
環境,你就可以開始了!
這是一個開箱即用的片段:
Python來源: ./create_pdf.py
import os, jinja2
from jinja2 import Template
latex_jinja_env = jinja2.Environment(
block_start_string = '\BLOCK{',
block_end_string = '}',
variable_start_string = '\VAR{',
variable_end_string = '}',
comment_start_string = '\#{',
comment_end_string = '}',
line_statement_prefix = '%%',
line_comment_prefix = '%#',
trim_blocks = True,
autoescape = False,
loader = jinja2.FileSystemLoader(os.path.abspath('./latex/'))
)
template = latex_jinja_env.get_template('latex_template.tex')
# populate a dictionary with the variables of interest
template_vars = {}
template_vars['section_1'] = 'The Section 1 Title'
template_vars['section_2'] = 'The Section 2 Title'
# create a file and save the latex
output_file = open('./generated_latex.tex', 'w')
# pass the dictionary with variable names to the renderer
output_file.write( template.render( template_vars ) )
output_file.close()
乳膠模板: ./latex/latex_template.tex
latex / ./latex/latex_template.tex
\documentclass{article}
\begin{document}
\section{Example}
An example document using \LaTeX, Python, and Jinja.
% This is a regular LaTeX comment
\section{\VAR{section_1}}
\begin{itemize}
\BLOCK{ for x in range(0,3) }
\item Counting: \VAR{x}
\BLOCK{ endfor }
\end{itemize}
\#{This is a long-form Jinja comment}
\BLOCK{ if subsection_1_1 }
\subsection{ The subsection }
This appears only if subsection_1_1 variable is passed to renderer.
\BLOCK{ endif }
%# This is a short-form Jinja comment
\section{\VAR{section_2}}
\begin{itemize}
%% for x in range(0,3)
\item Counting: \VAR{x}
%% endfor
\end{itemize}
\end{document}
現在只需調用: $> python ./create_pdf.py
產生的Latex來源: ./generated_latex.tex
\documentclass{article}
\begin{document}
\section{Example}
An example document using \LaTeX, Python, and Jinja.
% This is a regular LaTeX comment
\section{The Section 1 Title}
\begin{itemize}
\item Counting: 0
\item Counting: 1
\item Counting: 2
\end{itemize}
\section{The Section 2 Title}
\begin{itemize}
\item Counting: 0
\item Counting: 1
\item Counting: 2
\end{itemize}
\end{document}
生成的Pdf:
參考文獻:
如果要將現有PDF用作模板,而不更改原始文檔,則可以使用Dhek模板編輯器,該編輯器允許在單獨的模板文件中定義區域(邊界,名稱,類型)。
模板以JSON格式保存,以便可以在Python中解析,填充PDF區域並生成最終文檔(例如,使用Web表單中的值)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.