Logo Search packages:      
Sourcecode: jppy version File versions  Download package

printers.py

from reportlab.platypus import Frame, Paragraph, Preformatted, Spacer, Table, PageBreak
from reportlab.platypus import BaseDocTemplate, NextPageTemplate, PageTemplate
from reportlab.platypus import TableStyle

from reportlab.rl_config import defaultPageSize
from reportlab.lib.units import inch
from reportlab.lib.styles import getSampleStyleSheet
from reportlab.lib import colors

import jppy
import os
import pwd
import re
import string

import mx.DateTime
import types
import tempfile
import shutil


class contact_printer:
    def headers_and_footers(self,canvas,doc):
        self.header(canvas, doc)
        self.foot(canvas, doc)

    def header(self,canvas,doc):
        canvas.saveState()
        canvas.setFont('Times-Roman',20)
        canvas.drawString(doc.rightMargin, self.PAGE_HEIGHT - (0.75 * inch), "%s %s %s" % (
            self.contact['firstname'], self.contact['lastname'], self.contact['company']))
        canvas.setFont('Times-Roman',10)
        cats = jppy.addressBook().getCategories()
        canvas.drawRightString(self.PAGE_WIDTH - doc.leftMargin,
                               self.PAGE_HEIGHT - (0.75 * inch),
                               "Contact %s - Class %s" % (self.contact.unique_id,
                                                          cats[self.contact.category]))
        p = canvas.beginPath()
        p.moveTo(doc.leftMargin, self.PAGE_HEIGHT - (0.80 * inch))    
        p.lineTo(self.PAGE_WIDTH - doc.leftMargin, self.PAGE_HEIGHT - (0.80 * inch))
        p.close()
        canvas.drawPath(p)
        canvas.restoreState()    

    def foot(self,canvas,doc):
        canvas.saveState()
        p = canvas.beginPath()
        p.moveTo(doc.leftMargin, (0.9 * inch))    
        p.lineTo(self.PAGE_WIDTH - doc.leftMargin, (0.9 * inch))
        p.close()
        canvas.drawPath(p)        
        canvas.setFont('Times-Roman',10)
        canvas.drawString(inch, 0.75 * inch, "Page %d" % doc.page)
        canvas.drawRightString(self.PAGE_WIDTH - inch, 0.75 * inch,
                               "Rendered by '%s' on %s" % (
                                   pwd.getpwuid(os.getuid())[0],
                                   mx.DateTime.now().strftime("%c")))
        canvas.restoreState()

    def label_cell_style(self,style,x,y):
        style.add('ALIGN', (x,y), (x,y), 'RIGHT')
        style.add('BACKGROUND', (x,y), (x,y), colors.lightgrey)
        style.add('FACE', (x,y), (x,y), 'Helvetica')
        style.add('SIZE', (x,y), (x,y), 9)

    def normalize_table(self,table):
        table_style = TableStyle([
            ('GRID', (0,0), (-1,-1), 0.25, colors.white),
            ('VALIGN', (0,0), (-1,-1), 'TOP'),    
            ])

        new_table = []
        table, split_at = self.remove_blanks(table,8)
        per_column = max(len(table)/2,split_at)
        n = 0
        for n in range(per_column):
            if len(table) > (n+per_column):
                new_table.append(table[n]+table[n+per_column])
                self.label_cell_style(table_style,0,n)
                self.label_cell_style(table_style,2,n)
            else:
                new_table.append(table[n]+["",""])
                self.label_cell_style(table_style,0,n)            
        return new_table, table_style

    def remove_blanks(self,table,whereDidRowGo=None):
        newtable = []
        whereRowWent = None
        n = 0
        for row,i in zip(table,range(len(table))):
            row[1] = str(row[1])
            if len(row[1]) != 0:
                n = n + 1
                row[1] == Preformatted(row[1],self.styles['Normal'])
                newtable.append(row)
            if whereDidRowGo and i >= whereDidRowGo and not whereRowWent:
                whereRowWent = n
        if len(newtable) == 0:
            return [["No Data Available"]]
        if whereDidRowGo:
            return (newtable, whereRowWent)
        else:
            return newtable

    def __init__(self,addressbook,contact,log=None):
        self.addressbook = addressbook
        self.contact = contact

        self.PAGE_HEIGHT=defaultPageSize[1]
        self.PAGE_WIDTH=defaultPageSize[0]
        
        self.styles=getSampleStyleSheet()
        Elements=[]

        self.filename = tempfile.mktemp("contact.pdf")

        doc = BaseDocTemplate(self.filename,showBoundary=0)

        frame = Frame(doc.leftMargin, doc.bottomMargin, doc.width, doc.height, id='normal')


        contact_data = []
        ab = jppy.addressBook()

        for key, value in contact.items():
            phones = ["phone%d" % x for x in range(0,10)]
            avoid = ['currentphone','note'] + phones
            if key not in avoid:
                if isinstance(value,types.UnicodeType):
                    contact_data.append(["%s:" % key, value])

        phone_labels = ab.getPhoneLabels()
        for phone, ptype in contact['phones_with_labels']:
            contact_data.append(["%s:" % phone_labels[ptype], phone])

        table, style = self.normalize_table(contact_data)
        contact_details = Table(table)
        contact_details.setStyle(style)
        Elements.append(contact_details)

        ## phone_data = []
        ## phone_labels = jpilot.ContactsMetaData()['phonelabels']
        ## for phone,type in contact.phones_with_labels:
        ##     phone_data.append(["%s:" % phone_labels[type], phone])
        ## phone_details = Table(remove_blanks(phone_data))
        ## phone_details.setStyle(table_style)
        ## Elements.append(phone_details)


        #head_style = styles['Heading2']
        #Elements.append(Paragraph("Notes\n",head_style))

        Elements.append(Spacer(10,10))        

        para_style = self.styles['Normal']
        for para in contact['note'].split("\n"):
            if len(para) == 0:
                Elements.append(Spacer(10,10))        
            else:
                para = para.replace("&","&")
                Elements.append(Paragraph(para,para_style))

        doc.addPageTemplates([PageTemplate(id='OneCol',frames=frame,onPage=self.headers_and_footers)])

        doc.build(Elements)


    def log(self,log_str=None):
        str = "Rendered PDF"
        if log_str:
            str = "%s: %s" % (str, log_str)
        self.contact.log("contact_printer",str)
        self.addressbook.save(self.contact)
        

    def display(self,log=None):
        self.log(log)
        os.system("%s %s" % (jppy.config.get("core","pdfviewer"),
                             self.filename))

    def hardcopy(self,log=None):
        self.log(log)        
        os.system("%s %s" % (jppy.config.get("core","printercommand"),
                             self.filename))

    def savecopy(self,filename,log=None):
        self.log(log)
        shutil.copy(self.filename, filename)

    def __del__(self):
        import os
        if os.path.exists(self.filename):
            os.unlink(self.filename)


class contact_label:
    initial_offset = (210,10)
    width_in_chars = 30
    line_skip = 18
    char_height = 22
    
    def __init__(self, addressbook, contact,select=1,sender=1):
        self.addressbook = addressbook
        self.contact = contact

        if sender:
            self.sender = jppy.config.get("labels","sender").split("|")
        else:
            self.sender = None

        data = {}

        
        for key in ('firstname','lastname', 'company',
                    'address', 'city', 'state', 'country', 'zip'):

            if key in ('firstname','lastname','company'):
                data[key] = contact[key] or ""
            else:
                data[key] = contact["%s%d" % (key,select)] or ""

        block = """
%(firstname)s %(lastname)s
%(company)s
%(address)s
%(city)s
%(state)s
%(country)s
%(zip)s
        """ % data

        self.address = block.strip()
        self.address = re.sub(",[\t ]?\n","\n",self.address)
        self.address = re.sub("\n+","\n",self.address)        


    def render(self,required=1):
        r = []
        r.append("N")
        r.append("R%d,%d" % self.initial_offset)

        vertoffset = 0
        for line in self.address.split('\n'):
            for subline in self._wrap_str(line):
                r.append("A0,%d,0,3,1,1,N,\"%s\"" % (vertoffset, subline))
                vertoffset += self.char_height
            vertoffset += self.line_skip

        if self.sender:
            r.append("""
LO85,293,330,3
A0,285,0,2,1,1,N,"Sender:"
A0,305,0,3,1,1,N,"%s"
A0,328,0,3,1,1,N,"%s"
A0,352,0,3,1,1,N,"%s"
""" % tuple([s.center(self.width_in_chars) for s in self.sender]))
        
        r.append("P%d" % required)
        r.append("")
            
        return string.join(r,"\n")

    def _wrap_str(self,str):
        max = self.width_in_chars
        ll = []
        lines = string.split(str, '\n')
        if len(lines) > 1:
            return wrap_list(lines, max)
        words = string.split(lines[0])
        for i in range(len(words)):
            if len(words[i]) == 0:
                del words[i]
        while len(words):
            cc = 0
            cw = 0
            for w in words:
                tmp = (cc > 0) + cc + len(w)
                if tmp > max:
                    break
                cc = tmp
                cw = cw + 1
            if cw == 0:
                # must break word in middle
                ll.append(words[cw][:max-1] + '+')
                words[cw] = words[cw][max-1:]
            else:
                ll.append(string.join(words[:cw]))
                words = words[cw:]
        return ll

    def hardcopy(self,required=1,port="/dev/lp0",log="No Entry"):
        lp = open(port,"w")
        lp.write(self.render(required))
        lp.close()
        self.contact.log("Label Printed",log)
        self.addressbook.save(self.contact)
        
class todos_printer:
    def headers_and_footers(self,canvas,doc):
        self.header(canvas, doc)
        self.foot(canvas, doc)

    def header(self,canvas,doc):
        pass

    def foot(self,canvas,doc):
        canvas.saveState()
        p = canvas.beginPath()
        p.moveTo(doc.leftMargin, (0.9 * inch))    
        p.lineTo(self.PAGE_WIDTH - doc.leftMargin, (0.9 * inch))
        p.close()
        canvas.drawPath(p)        
        canvas.setFont('Times-Roman',10)
        canvas.drawString(inch, 0.75 * inch, "Page %d" % doc.page)
        canvas.drawRightString(self.PAGE_WIDTH - inch, 0.75 * inch,
                               "Rendered by '%s' on %s" % (
                                   pwd.getpwuid(os.getuid())[0],
                                   mx.DateTime.now().strftime("%c")))
        canvas.restoreState()

    def __init__(self,tasklist, todolist):

        self.tasklist = tasklist
        self.PAGE_HEIGHT=defaultPageSize[1]
        self.PAGE_WIDTH=defaultPageSize[0]
        
        self.styles=getSampleStyleSheet()
        Elements=[]

        self.filename = tempfile.mktemp("todos.pdf")

        doc = BaseDocTemplate(self.filename,showBoundary=0)

        frame = Frame(doc.leftMargin, doc.bottomMargin, doc.width, doc.height, id='normal')

        para_style = self.styles['Normal']
        para_style.leading = 28
        

        cats = jppy.taskList().getCategories()
        
        for todo in todolist:
            if todo['complete']:
                continue
            para = todo['description'].encode("iso8859-15")
            para = para.replace("&","&")
            para = para.replace("<","&lt;")
            para = para.replace(">","&gt;")                        
            para = "%s <i>%s</i>" % (para, cats[todo.category])
            if todo['due']:
                para = "%s <i>%s, <b>%s days</b></i>" % (para,
                                                         todo['due'].date,
                                                         int((todo['due'] - mx.DateTime.now()).days))
            Elements.append(Paragraph(para,para_style))
            
        doc.addPageTemplates([PageTemplate(id='OneCol',frames=frame,onPage=self.headers_and_footers)])

        doc.build(Elements)


    def display(self):
        os.system("%s %s" % (jppy.config.get("core","pdfviewer"),
                             self.filename))

    def hardcopy(self,log=None):
        os.system("%s %s" % (jppy.config.get("core","printercommand"),
                             self.filename))

    def savecopy(self,filename,log=None):
        shutil.copy(self.filename, filename)

    def __del__(self):
        import os
        os.unlink(self.filename)

Generated by  Doxygen 1.6.0   Back to index