2012-11-14 35 views
0

我已经创建了一个模板,用于从csv输入呈现pdf文件。但是,当csv输入字段包含用户格式时,使用换行符和缩进符时,它会与rst2pdf格式引擎混淆。有没有一种方法可以一贯地处理用户输入,而不会中断文档流,同时也保持输入文本的格式?下面的示例脚本:使用mako和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

其实事实证明我是正确的轨道上,我只需要|和文本之间的空间。所以,下面的代码工作:

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') 
+0

如果你在一个单独的模板文件使用此方法,你并不需要加倍逃脱换行符,所以'\\ N'将与'\ N'所取代。 – rudivonstaden