2013-10-31 149 views
2

Python Reportlab的Python ReportLab的 - 無法打印的特殊字符

我而在我pdf"&"

# -*- coding: utf-8 -*- 
from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer 
from reportlab.lib.styles import getSampleStyleSheet 
from reportlab.rl_config import defaultPageSize 
from reportlab.lib.units import inch 

styles = getSampleStyleSheet() 

def myFirstPage(canvas, doc): 
    canvas.saveState() 

def go(): 
    doc = SimpleDocTemplate("phello.pdf") 
    Story = [Spacer(1,2*inch)] 
    Story.append(Paragraph("Some text", styles["Normal"])) 
    Story.append(Paragraph("Some other text with &", styles["Normal"])) 
    doc.build(Story, onFirstPage=myFirstPage) 

go() 

我預期以下輸出

Some text 
Some other text with & 

但打印的特殊字符面臨的問題我得到的輸出是

Some text 
Some other text with 

哪兒了 '&' 獲得消失了。

找遍了一些論壇這不能不說我需要將其編碼爲&但有沒有好辦了這對編碼每個特殊字符的方式?

我在我的腳本的頂部添加"# -*- coding: utf-8 -*-"但這並不解決我的問題

+2

歡迎堆棧溢出!看起來你希望我們爲你寫一些代碼。 儘管許多用戶願意爲遇險的編碼人員編寫代碼,但他們通常僅在海報已嘗試自行解決問題時才提供幫助。 證明這一努力的一個好方法是包含迄今爲止編寫的代碼, 示例輸入(如果有的話),期望的輸出和實際獲得的輸出(控制檯輸出,堆棧跟蹤,編譯器錯誤 - 無論什麼適用)。 您提供的細節越多,您可能收到的答案越多。檢查[常見問題]和[問] –

+0

可能的重複[報告實驗室無法處理希伯來語(unicode)](http://stackoverflow.com/questions/10958904/report-lab-cant-handle-hebrew-unicode) – sdasdadas

+0

沒有sdasdadas。該線程給出的解決方案不能解決我的問題 –

回答

3

此時應更換&,<和>與&amp;&lt;&gt;。一個簡單的方法來做到這一點是Python逃生功能:

from cgi import escape 
Story.append(Paragraph(escape("Some other text with &"), styles["Normal"])) 

然而,HTML標記都需要有真正的<和>這樣一個典型的使用會更喜歡:

text = "Some other text with &" 
Story.append(Paragraph(escape("<b>" + text + "</b>"), styles["Normal"]))