我创建了一个从csv输入呈现pdf文件的模板。但是,当csv输入字段包含用户格式,包含换行符和缩进时,它会与rst2pdf格式引擎混淆。有没有办法以不破坏文档流的方式一致地处理用户输入,还保持输入文本的格式?下面的示例脚本:
from mako.template import Template
from rst2pdf.createpdf import RstToPdf
mytext = """This is the first line
Then there is a second
Then a third
This one could be indented
I'd like it to maintain the formatting."""
template = """
My PDF Document
===============
It starts with a paragraph, but after this I'd like to insert `mytext`.
It should keep the formatting intact, though I don't know what formatting to expect.
${mytext}
"""
mytemplate = Template(template)
pdf = RstToPdf()
pdf.createPdf(text=mytemplate.render(mytext=mytext),output='foo.pdf')
我尝试在模板中添加以下函数,以便在每行的开头插入|
,但这似乎也不起作用。
<%!
def wrap(text):
return text.replace("\\n", "\\n|")
%>
然后${mytext}
将成为|${mytext | wrap}
。这会引发错误:
<string>:10: (WARNING/2) Inline substitution_reference start-string without end-string.
答案 0 :(得分:0)
实际上事实证明我在正确的轨道上,我只需要|
和文本之间的空格。所以下面的代码可以工作:
from mako.template import Template
from rst2pdf.createpdf import RstToPdf
mytext = """This is the first line
Then there is a second
Then a third
How about an indent?
I'd like it to maintain the formatting."""
template = """
<%!
def wrap(text):
return text.replace("\\n", "\\n| ")
%>
My PDF Document
===============
It starts with a paragraph, but after this I'd like to insert `mytext`.
It should keep the formatting intact.
| ${mytext | wrap}
"""
mytemplate = Template(template)
pdf = RstToPdf()
#print mytemplate.render(mytext=mytext)
pdf.createPdf(text=mytemplate.render(mytext=mytext),output='foo.pdf')