2012-11-14 36 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