2014-02-20 2 views
0

Я смог успешно создать pdf-файл с простым примером, найденным here, и он работал безупречно. Я также понимаю, что ссылку можно создать с помощью команды write, просто добавив несколько параметров. Однако я не уверен, как (наиболее эффективно/правильно) добавить его в шаблон. В идеале я хотел бы добавить его в словарь элементов.PyFPDF создать ссылку в шаблоне

EDIT: На самом деле я даже не думаю, что объект шаблона позволяет с помощью Write() варианта, так что, может быть, нет способа сделать ссылку в шаблоне выглядит как я буду иметь, чтобы написать свои собственные объект, если я хочу иметь URL-адрес.

from pyfpdf import Template 

#this will define the ELEMENTS that will compose the template. 
elements = [ 
    { 'name': 'company_logo', 'type': 'I', 'x1': 20.0, 'y1': 17.0, 'x2': 78.0, 'y2': 30.0, 'font': None, 'size': 0.0, 'bold': 0, 'italic': 0, 'underline': 0, 'foreground': 0, 'background': 0, 'align': 'I', 'text': 'logo', 'priority': 2, }, 
    { 'name': 'company_name', 'type': 'T', 'x1': 17.0, 'y1': 32.5, 'x2': 115.0, 'y2': 37.5, 'font': 'Arial', 'size': 12.0, 'bold': 1, 'italic': 0, 'underline': 0, 'foreground': 0, 'background': 0, 'align': 'I', 'text': '', 'priority': 2, }, 
    { 'name': 'box', 'type': 'B', 'x1': 15.0, 'y1': 15.0, 'x2': 185.0, 'y2': 260.0, 'font': 'Arial', 'size': 0.0, 'bold': 0, 'italic': 0, 'underline': 0, 'foreground': 0, 'background': 0, 'align': 'I', 'text': None, 'priority': 0, }, 
    { 'name': 'box_x', 'type': 'B', 'x1': 95.0, 'y1': 15.0, 'x2': 105.0, 'y2': 25.0, 'font': 'Arial', 'size': 0.0, 'bold': 1, 'italic': 0, 'underline': 0, 'foreground': 0, 'background': 0, 'align': 'I', 'text': None, 'priority': 2, }, 
    { 'name': 'line1', 'type': 'L', 'x1': 100.0, 'y1': 25.0, 'x2': 100.0, 'y2': 57.0, 'font': 'Arial', 'size': 0, 'bold': 0, 'italic': 0, 'underline': 0, 'foreground': 0, 'background': 0, 'align': 'I', 'text': None, 'priority': 3, }, 
    { 'name': 'barcode', 'type': 'BC', 'x1': 20.0, 'y1': 246.5, 'x2': 140.0, 'y2': 254.0, 'font': 'Interleaved 2of5 NT', 'size': 0.75, 'bold': 0, 'italic': 0, 'underline': 0, 'foreground': 0, 'background': 0, 'align': 'I', 'text': '200000000001000159053338016581200810081', 'priority': 3, }, 
] 

#here we instantiate the template and define the HEADER 
f = Template(format="A4",elements=elements, 
      title="Sample Invoice") 
f.add_page() 

#we FILL some of the fields of the template with the information we want 
#note we access the elements treating the template instance as a "dict" 
f["company_name"] = "Sample Company" 
f["company_logo"] = "pyfpdf/tutorial/logo.png" 

#and now we render the page 
f.render("./template.pdf") 

Код выше, является пример, приведенный в link.

ответ

0

Итак, я проверил источник, и, похоже, в шаблонах не было ссылки. Я добавил следующий код:

def write(self, pdf, x1=0, y1=0, x2=0, y2=0, text='', font="arial", size=1, 
      bold=False, italic=False, underline=False, align="", link='http://example.com', 
     foreground=0, *args, **kwargs): 
    if pdf.text_color!=rgb(foreground): 
     pdf.set_text_color(*rgb(foreground)) 
    font = font.strip().lower() 
    if font == 'arial black': 
     font = 'arial' 
    style = "" 
    for tag in 'B', 'I', 'U': 
     if (text.startswith("<%s>" % tag) and text.endswith("</%s>" %tag)): 
      text = text[3:-4] 
      style += tag 
    if bold: style += "B" 
    if italic: style += "I" 
    if underline: style += "U" 
    align = {'L':'L','R':'R','I':'L','D':'R','C':'C','':''}.get(align) # D/I in spanish 
    pdf.set_font(font,style,size) 
    ##m_k = 72/2.54 
    ##h = (size/m_k) 
    pdf.set_xy(x1,y1) 
    pdf.write(5,text,link) 

в templates.py и изменил линию

-       'B': self.rect, 'BC': self.barcode, } 
+       'B': self.rect, 'BC': self.barcode, 'W' self.write, } 

в обработчике элементы самостоятельно. С этим вы можете использовать аналогичный синтаксис для написания текстовой строки в элементе dict. Просто измените тип: 'T', чтобы набрать: 'W' и добавить ссылку: 'http://code.google.com/p/pyfpdf/' к ней или любой другой ссылке, которую вы хотите. Я представил это как патч, и он должен быть доступен в следующей версии. Я оставил x2 y2 в параметрах, потому что не уверен, нужны ли они для синтаксического анализа или нет, но я считаю, что метод Write() использует только x1 y1, если это что-то похожее на версию PHP. K thx bye

Смежные вопросы