0
這是我的代碼。我的第一個功能是基於/Lib/site-packages/reportlab/lib/styles.py
源代碼,以創建style
數組:鴨嘴獸「猜」大膽和斜體樣式如何?
def create_styles(p_tuples):
retour = StyleSheet1()
parent = None
for p_name, font_name, font in p_tuples:
# (!) change path if Linux:
ttf_file = "C:/Windows/Fonts/{}.ttf".format(font)
pdfmetrics.registerFont(TTFont(font_name, ttf_file))
if parent is None:
p = ParagraphStyle(name=p_name,
fontName=font_name,
fontSize=10,
leading=12)
retour.add(p)
parent = p
else:
retour.add(ParagraphStyle(name=p_name,
parent=parent,
fontName=font_name,
fontSize=10,
leading=12))
return retour
於是我建立自己的陣列,我安裝的字體:
def render_to_response(self, context, **response_kwargs):
# this is a response for Django, but the question is about styles
response = HttpResponse(content_type='application/pdf; charset=utf-8')
# ! Hint : no filename -> the browser extracts it from the URL!
# -> create URLs like http://pdfreportlab.com/extract/myfilename.pdf
# this is the way to go to have 100% working UTF-8 filenames!
response['Content-Disposition'] = 'attachment; filename=""'
my_styles = self.create_styles([
('ms-regular', 'montserrat-regular',
'Montserrat-Regular'),
('ms-black', 'montserrat-black',
'Montserrat-Black'),
('ms-black-italic', 'montserrat-black-italic',
'Montserrat-BlackItalic'),
('ms-bold', 'montserrat-bold',
'Montserrat-Bold'),
('ms-bold-italic', 'montserrat-bold-italic',
'Montserrat-BoldItalic'),
])
doc = SimpleDocTemplate(response)
elements = []
c = canvas.Canvas(response, pagesize=A4,)
for idx in my_styles.byName:
p = Paragraph("Hello World <i>italic</i> <b>bold</b>",
style=my_styles[idx])
width, height = p.wrapOn(c, A4[0], A4[1])
elements.append(p)
doc.build(elements)
return response
一切工作除了(很煩人)事實,即<i></i>
和<b></b>
標籤被忽略!它只使用樣式中的當前字體。
你怎麼能修改我的代碼,以便它考慮到標籤,並最終獲得文本本身的標籤樣式?
'(「normal」,「bold」,「italic」,「boldItalic」):#識別的字體變體在所有系統中都是硬編碼的?這是一個事實上的標準? –
@OlivierPons - 這些是'reportlab.pdfbase.pdfmetrics.registerFontFamily()'函數的'硬編碼'參數(簽名是:'registerFontFamily(family,normal = None,bold = None,italic = None,boldItalic = None)'' ) - 在上面的代碼中,它是一種簡寫形式,所以您不必將一個參數集的名稱轉換/傳遞給另一個參數集。 – zwer
如果我在這裏嘗試這個硬編碼的解決方案:http://two.pairlist.net/pipermail/reportlab-users/2010-October/009795.html那麼它的工作原理。我發現你的解決方案不起作用,因爲(我猜這是一個錯誤)。 (1)從你的循環中移除'normal'並且(2)在你的循環之前加上這一行:'registerFont(TTFont(font_family,ttf_path.format(kwargs ['normal']) )))'(推斷'正常'總是以kwargs傳遞)。 3個小時。 –