0

我创建了一个从 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.
4

1 回答 1

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')
于 2012-11-15T06:45:37.120 回答