コード例 #1
0
    def create(self, request):
        # Create the HttpResponse object with the appropriate PDF headers.
        content = json.loads(request.body)

        response = HttpResponse(content_type='application/pdf')
        response[
            'Content-Disposition'] = 'attachment; filename=somefilename.pdf'

        doc = SimpleDocTemplate(response,
                                rightMargin=6.5,
                                leftMargin=6.5,
                                topMargin=15 * cm,
                                bottomMargin=15 * cm)
        doc.author = "carlos"

        def drawFooter(canvas, doc):
            x = 330
            canvas.saveState()
            canvas.setStrokeColorRGB(0, 0, 0)
            canvas.setLineWidth(0.5)
            canvas.line(66, 78, A4[0] - 66, 78)
            canvas.setFont('Helvetica', 10)
            canvas.drawString(A4[0] - x, 65, "Generated by User")
            canvas.restoreState()

        doc.build(self._PDFElements(doc, content), onFirstPage=drawFooter)

        return response
コード例 #2
0
    def go(self):
        """Render the PDF foer individual item."""
        doc = SimpleDocTemplate(self.buf,
                                leftMargin=LEFTMARGIN,
                                rightMargin=RIGHTMARGIN)
        doc.title = self.filename
        doc.creator = "Romain Belia."
        doc.author = "Romain Belia."
        doc.subject = "Report created by Romain Belia."
        doc.keywords = ["report", "Romain Belia"]
        story = []
        # First Page

        story.append(self._build_title("The Report"))
        story.append(Spacer(1, 1 * cm))
        story.append(
            self._build_document_title("organization", self.organization))
        story.append(
            self._build_document_title("reported_at", self.reported_at))
        story.append(self._build_document_title("created_at", self.created_at))
        story.append(Spacer(1, 1 * cm))
        story.append(Spacer(1, 1 * cm))
        if not self.inventory:
            story.append(self._build_no_content())
        for x in self.inventory:
            story.append(self._build_document_content(x))
            story.append(Spacer(1, 1 * cm))
        story.append(PageBreak())

        doc.build(story,
                  onFirstPage=self.firstpage,
                  onLaterPages=self.laterpages)
        return
コード例 #3
0
ファイル: lucky.py プロジェクト: kuba/SIS
    def current_week_pdf(self):
        """Lucky numbers for current or next week in pdf format."""
        change_hour = 15
        numbers = LuckyNumber.current_week(change_hour)

        if len(numbers) == 0:
            return redirect(url('lucky_week'))

        # Register fonts
        ubuntu_r = resource_filename(Requirement.parse("SIS"), "resources/Ubuntu-R.ttf")
        ubuntu_b = resource_filename(Requirement.parse("SIS"), "resources/Ubuntu-B.ttf")
        pdfmetrics.registerFont(TTFont('Ubuntu', ubuntu_r))
        pdfmetrics.registerFont(TTFont('Ubuntu Bold', ubuntu_b))

        numbers_pdf = StringIO.StringIO()
        doc = SimpleDocTemplate(numbers_pdf, pagesize=A4, topMargin=A4[1]*0.26)
        doc.author = 'SIS'
        doc.title = 'Szczęśliwy numerek'

        data = []
        for number in numbers:
            date = number.date.strftime("%d.%m.%y")
            data.append(('{0} -'.format(date), str(number.number)))

        table = Table(data)
        table.setStyle(TableStyle([
            ('FONT', (0, 0), (0, -1), 'Ubuntu', 80),
            ('FONT', (1, 0), (1, -1), 'Ubuntu Bold', 80),
        ]))

        def header_and_footer(canvas, document):
            canvas.saveState()
            size = document.pagesize
            center = size[0] / 2

            canvas.setFont('Ubuntu', 80)
            canvas.drawCentredString(center,
                size[1] - document.topMargin / 2, "SZCZĘŚLIWY")
            canvas.drawCentredString(center, size[1] - document.topMargin + 20, 'NUMEREK')

            canvas.setFont('Ubuntu', 15)
            canvas.drawRightString(size[0] - document.rightMargin,
                document.bottomMargin - 20, "Samorząd Uczniowski")

            canvas.restoreState()

        doc.build([table], onFirstPage=header_and_footer,
            onLaterPages=header_and_footer)

        response.headers['Content-type'] = 'application/pdf'
        return numbers_pdf.getvalue()
コード例 #4
0
    def go_all(self):
        """Render the PDF for all items."""
        doc = SimpleDocTemplate(self.buf,
                                leftMargin=LEFTMARGIN,
                                rightMargin=RIGHTMARGIN)
        doc.title = self.filename
        doc.creator = "Romain Belia."
        doc.author = "Romain Belia."
        doc.subject = "Report created by Romain Belia."
        doc.keywords = ["report", "Romain Belia"]
        story = []
        # First Page

        story.append(self._build_title("Full Report"))
        story.append(Spacer(1, 1 * cm))
        for item in self.data:
            data = item['data']
            inventory = data['inventory'] if 'inventory' in data else []
            if 'id' in item:
                story.append(self._build_document_title("id", item['id']))
            if 'organization' in data:
                story.append(
                    self._build_document_title("organization",
                                               data['organization']))
            if 'reported_at' in data:
                story.append(
                    self._build_document_title("reported_at",
                                               data['reported_at']))
            if 'created_at' in data:
                story.append(
                    self._build_document_title("created_at",
                                               data['created_at']))
            story.append(Spacer(1, 1 * cm))
            story.append(Spacer(1, 1 * cm))
            if not inventory:
                story.append(self._build_no_content())
            for x in inventory:
                story.append(self._build_document_content(x))
                story.append(Spacer(1, 1 * cm))
            story.append(PageBreak())

        doc.build(story,
                  onFirstPage=self.firstpage,
                  onLaterPages=self.laterpages)
        return
コード例 #5
0
    def build_doc(self, tables):
        """Build & return a simple PDF document from tables.

        tables: A list of DataTable instances. *

        * Required.
        """
        # Build a story out of the tables provided.
        common_style = [
            ('INNERGRID', (0, 0), (-1, -1), .25, colors.black),
            ('BOX', (0, 0), (-1, -1), .25, colors.black),
            ('FONT', (0, 0), (-1, -1), "Helvetica", 9),
            ('ALIGN', (0, 0), (-1, -1), 'LEFT'),
        ]
        story = []
        for table in tables:
            data_list = []
            for row in table.rows:
                data_list.append([cell.get_data() for cell in row])
            pdf_table = Table(data=data_list,
                              splitByRow=1,
                              repeatRows=1,
                              repeatCols=3,
                              colWidths=table.widths)
            pdf_table.setStyle(common_style + table.get_styles())
            story += [Spacer(1, 1 * inch), pdf_table]
            if table.page_break:
                story += [PageBreak()]
        if not story:
            story.append(Spacer(1, 1 * inch))
        # Generate & return a PDF from the story
        buff = BytesIO()
        doc = SimpleDocTemplate(buff, pagesize=pagesizes.A4)
        doc.title = self.title
        doc.author = "Report-maker"
        doc.subject = self.title
        doc.build(story,
                  onFirstPage=self.get_first_page(),
                  onLaterPages=self.get_later_pages())
        doc_pdf = buff.getvalue()
        buff.close()
        return doc_pdf
コード例 #6
0
ファイル: report.py プロジェクト: FedericoCeratto/Dinemo
def create(nodenick):
    buffer = StringIO()
    doc = SimpleDocTemplate(buffer)
    doc.author = "dinemo"
    doc.subject = "Network monitoring report"
    doc.title = "Network monitoring report"
    Story = []
#   img = Image("dinemomaster/static/images/logo.jpg", 214, 50)
    img = Image("dinemomaster/static/images/logo.jpg", 107, 25)
    img.hAlign='RIGHT'
    Story.append(img)
    Story.append(Spacer(1,7 * cm))
    style = styles["title"]
    style.textColor = "darkblue"
    style.fontSize = 20
    Story.append(Paragraph("Network moritoring report", style))
    Story.append(Spacer(1,0.5 * cm))
    style.fontSize = 14
    Story.append(Paragraph("Generated on %s" % strftime("%d %h %Y"), style))
    if nodenick:
        style.fontSize = 16
        Story.append(Spacer(1,1 * cm))
        Story.append(Paragraph("            \"%s\" node network metrics""" % nodenick, style))
    style = styles["Normal"]
    style.textColor = "black"
    Story.append(PageBreak())




    for i in range(100):
        bogustext = ("Paragraph number %s. " % i) *20
        p = Paragraph(bogustext, style)
        Story.append(p)
        Story.append(Spacer(1,0.2*cm))

    doc.build(Story, onLaterPages= _later_page)
    pdf = buffer.getvalue()
    buffer.close()
    return pdf
コード例 #7
0
ファイル: mangagrab.py プロジェクト: nagisa/Manga-Fox-Grabber
 def run(self):
     linkbundle = self.link.split('/')[-3:][:2]
     if linkbundle[0] == interface.series:
         linkbundle[0] = '/'
     else:
         linkbundle[0] = '/' + linkbundle[0] + '/'
     ##Check if not downloaded already.
     try:
         chapters = os.listdir(interface.series)
     except:
         chapters = []
     if linkbundle[1] + '.pdf' in chapters and not interface.force:
         interface.completed = interface.completed + 1.0 / interface.seriesLen
         idle_add(
             self.update_status, interface.completed, 'Chapter ' +
             linkbundle[1].strip('c') + ' was found downloaded.')
         return True
         ##Completed that chapter!
     idle_add(self.update_status, None,
              'Start reading chapter ' + linkbundle[1].strip('c'))
     for page in range(1, 1000):
         url = 'http://mangafox.me/manga/' + interface.series + linkbundle[
             0] + linkbundle[1] + '/' + str(page) + '.html'
         request = urllib2.Request(url, interface.urllib, interface.headers)
         try:
             response = urllib2.urlopen(request)
             content = response.read()
             if response.info().get('Content-Encoding') == 'gzip':
                 content = gzip.GzipFile(fileobj=StringIO(content)).read()
         except Exception as e:
             print 'Could not get html for chapter ' + linkbundle[
                 1] + ' page ' + str(page)
             print 'Exception: {0}'.format(e)
             continue
         try:
             image = interface.regex.search(content).group(0)
             if not image in self.images:
                 self.images.append(image)
             else:
                 break  ##Chapter END
         except:
             print 'Could not get image for chapter ' + linkbundle[
                 1] + ' page ' + str(page)
             break  ##Could not get image!
     interface.completed = interface.completed + (0.25 /
                                                  interface.seriesLen)
     idle_add(self.update_status, interface.completed,
              'Downloading chapter ' + linkbundle[1].strip('c'))
     ###
     ##Downloading images.
     ###
     chapterLen = len(self.images)
     if chapterLen < 2:
         interface.completed = interface.completed + (0.75 /
                                                      interface.seriesLen)
         idle_add(self.update_status, interface.completed,
                  'Done chapter ' + linkbundle[1].strip('c'))
         return True
     try:
         os.mkdir(interface.series)
     except:
         pass
     try:
         os.mkdir(os.path.join(interface.series, linkbundle[1]))
     except:
         pass
     for image in self.images:
         imagename = image.split('/')[-1]
         img = open(
             os.path.join(interface.series, linkbundle[1], imagename), 'w')
         img.write(urllib2.urlopen(image).read())
         img.close()
         interface.completed = interface.completed + (
             0.5 / interface.seriesLen / chapterLen)
         idle_add(self.update_status, interface.completed, None)
     ###
     ##Making PDF
     ###
     c = SimpleDocTemplate(os.path.join(interface.series,
                                        linkbundle[1] + '.pdf'),
                           pagesize=interface.psize,
                           rightMargin=0,
                           leftMargin=0,
                           topMargin=0,
                           bottomMargin=0)
     Story = []
     maxh = interface.psize[1] - 20
     maxw = interface.psize[0] - 30
     title = ' '.join(interface.series.split('_'))
     c.title = title + ' ' + linkbundle[1]
     c.author = interface.author
     directory = os.path.join(interface.series, linkbundle[1])
     images = sorted(os.listdir(directory))
     for image in images:
         img = PImage.open(os.path.join(directory, image))
         width, height = img.size
         img = img.crop((0, 0, width, height - 40))
         img.save(os.path.join(directory, image))
         img = PImage.open(os.path.join(directory, image))
         width, height = img.size
         if width / maxw > height / maxh:
             height = height / (width / maxw)
             width = maxw
             if width > height:
                 img = img.rotate(90)
                 img.save(os.path.join(directory, image))
                 width, height = img.size
                 if width / maxw > height / maxh:
                     height = height / (width / maxw)
                     width = maxw
                 else:
                     width = width / (height / maxh)
                     height = maxh
         else:
             width = width / (height / maxh)
             height = maxh
         im = Image(os.path.join(directory, image), width, height)
         Story.append(im)
     c.build(Story)
     interface.completed = interface.completed + (0.2499 /
                                                  interface.seriesLen)
     idle_add(self.update_status, interface.completed,
              'Done chapter ' + linkbundle[1].strip('c'))
     interface.temps.append(os.path.join(interface.series, linkbundle[1]))
コード例 #8
0
ファイル: noise.py プロジェクト: morristech/applemonweb
def generate_noise_report(files):
    sound_logs = []
    other_pdfs = []
    for uploaded_file in files:
        if uploaded_file.content_type == 'text/plain':
            sound_logs.append(uploaded_file.temporary_file_path())
        elif uploaded_file.content_type == 'application/pdf':
            other_pdfs.append(uploaded_file.temporary_file_path())
        else:
            raise Exception("File type {} is not text or PDF.".format(
                uploaded_file.content_type
            ))
    assert sound_logs, "No sound level data logs provided."
    (_fh1, report_filename) = tempfile.mkstemp(suffix='.pdf')
    (_fh2, assembled_filename) = tempfile.mkstemp(suffix='.pdf')
    try:
        doc = SimpleDocTemplate(report_filename, pagesize=letter)
        doc.title = title
        doc.author = author
        styles = getSampleStyleSheet()
        min_date = None
        story = []

        for filename in sound_logs:
            assert open(filename).readline().strip() == \
                'STANDARD HD600 DATA LOGGER SamplingRate:1.0;', \
                "Sound data logs must use HD600 format with 1-second samples."
            df = pd.read_csv(filename, sep=', ', header=None, skiprows=1,
                             names=['timestamp', 'level', 'unit'],
                             parse_dates=['timestamp'],
                             date_parser=parse_timestamp, engine='python')
            date = df['timestamp'].min().date()
            if not min_date or date < min_date:
                min_date = date
            unit = df['unit'].iloc[0]
            assert unit in ['dBA', 'dBC'], \
                "Sound must be measured in A/C-weighted decibels (dBA or dBC)."
            assert df['unit'].eq(unit).all(), \
                "Sound level units must be consistent."
            df['ratio'] = df['level'].apply(to_ratio)
            leq_fmt = "{overall:.1f} {dB} (over entire session)"
            if len(df) > 3600:
                leq_fmt += "\n{min:.1f} {dB} - {max:.1f} {dB} (rolling 1-hour)"
                df['leq'] = to_decibels(
                    df['ratio'].rolling(3600, center=True).mean()
                )
                df['leq'].fillna(method='bfill', inplace=True)
                df['leq'].fillna(method='ffill', inplace=True)
            else:
                df['leq'] = to_decibels(df['ratio'].mean())
            leq = leq_fmt.format(
                overall=to_decibels(df['ratio'].mean()),
                dB=unit,
                min=df['leq'].min(), max=df['leq'].max(),
            )
            story.append(Paragraph("Sound Level Monitoring Report",
                         styles["Title"]))
            story.append(Paragraph("Session Summary", styles["Heading2"]))
            story.append(Table([
                ['Start Time', df['timestamp'].iloc[0]],
                ['Stop Time', df['timestamp'].iloc[-1]],
                ['Duration', str(
                    df['timestamp'].iloc[-1] - df['timestamp'].iloc[0]
                ).replace('0 days ', '')],
                ['Device', 'HD600'],
                ['Lmin', '{} {}'.format(df['level'].min(), unit)],
                ['Lmax', '{} {}'.format(df['level'].max(), unit)],
                ['Leq', leq],
            ]))

            fig = Figure(figsize=(6, 4))
            ax = fig.add_subplot(1, 1, 1)
            ax.set_title("Logged Data")
            ax.set_xlabel("Time")
            ax.set_ylabel(unit)
            ax.grid(True)
            (line,) = ax.plot_date(df['timestamp'], df['level'], fmt='b-',
                                   linewidth=0.5)
            line.set_label("L")
            (line2,) = ax.plot_date(df['timestamp'], df['leq'], fmt='g-',
                                    linewidth=5, alpha=0.7)
            line2.set_label("Leq")
            for threshold in thresholds:
                ax.axhline(threshold, color='r', linestyle='--', alpha=0)
            ax.xaxis.set_major_formatter(DateFormatter('%H:%M'))
            ax.legend(loc='upper right', framealpha=0)

            fig.autofmt_xdate()
            buf = io.BytesIO()
            FigureCanvasAgg(fig).print_figure(buf, format='png')
            story.append(Image(buf))

            story.append(PageBreak())

        doc.build(story)
        subprocess.check_call([
            'gs', '-dSAFER', '-dBATCH', '-dNOPAUSE', '-dQUIET',
            '-sDEVICE=pdfwrite', '-dPDFSETTINGS=/ebook',
            '-sPAPERSIZE=letter', '-dFIXEDMEDIA', '-dPDFFitPage',
            '-sOutputFile={}'.format(assembled_filename)
        ] + other_pdfs + [report_filename])
        with open(assembled_filename, 'rb') as f:
            pdf = f.read()
    finally:
        os.remove(report_filename)
        os.remove(assembled_filename)
    if min_date:
        filename = 'noise_{}.pdf'.format(min_date)
    else:
        filename = 'noise.pdf'
    return (pdf, filename)
コード例 #9
0
 def run(self):
     linkbundle = self.link.split('/')[-3:][:2]
     if linkbundle[0] == interface.series:
         linkbundle[0] = '/'
     else:
         linkbundle[0] = '/'+linkbundle[0]+'/'
     ##Check if not downloaded already.
     try:
         chapters = os.listdir(interface.series)
     except:
         chapters = []
     if linkbundle[1]+'.pdf' in chapters and not interface.force:
         interface.completed = interface.completed+1.0/interface.seriesLen
         idle_add(self.update_status, interface.completed, 'Chapter '+linkbundle[1].strip('c')+' was found downloaded.')
         return True
         ##Completed that chapter!
     idle_add(self.update_status, None, 'Start reading chapter '+linkbundle[1].strip('c'))
     for page in range(1, 1000):
         url = 'http://www.mangafox.com/manga/'+interface.series+linkbundle[0]+linkbundle[1]+'/'+str(page)+'.html'
         request = urllib2.Request(url, interface.urllib, interface.headers)
         try:
             content = urllib2.urlopen(request).read()
         except:
             continue
         try:
             image=interface.regex.search(content).group(0)
             if not image in self.images:
                 self.images.append(image)
             else:
                 break ##Chapter END
         except:
             print 'Could not get image for chapter '+linkbundle[1]+' page '+str(page)
             break ##Could not get image!
     interface.completed = interface.completed+(0.25/interface.seriesLen)
     idle_add(self.update_status, interface.completed, 'Downloading chapter '+linkbundle[1].strip('c'))
     ###
     ##Downloading images.
     ###
     chapterLen = len(self.images)
     if chapterLen < 2:
         interface.completed = interface.completed+(0.75/interface.seriesLen)
         idle_add(self.update_status, interface.completed, 'Done chapter '+linkbundle[1].strip('c'))
         return True
     try:
         os.mkdir(interface.series)
     except:
         pass
     try:
         os.mkdir(os.path.join(interface.series, linkbundle[1]))
     except:
         pass
     for image in self.images:
         imagename=image.split('/')[-1]
         img = open(os.path.join(interface.series, linkbundle[1], imagename), 'w')
         img.write(urllib2.urlopen(image).read())
         img.close()
         interface.completed = interface.completed+(0.5/interface.seriesLen/chapterLen)
         idle_add(self.update_status, interface.completed, None)
     ###
     ##Making PDF
     ###
     c=SimpleDocTemplate(os.path.join(interface.series, linkbundle[1]+'.pdf'),
                         pagesize=interface.psize,
                         rightMargin=0,
                         leftMargin=0,
                         topMargin=0,
                         bottomMargin=0)
     Story=[]
     maxh = interface.psize[1]-20
     maxw = interface.psize[0]-30
     title=' '.join(interface.series.split('_'))
     c.title=title+' '+linkbundle[1]
     c.author=interface.author
     directory=os.path.join(interface.series, linkbundle[1])
     images=sorted(os.listdir(directory))
     for image in images:
         img = PImage.open(os.path.join(directory, image))
         width, height = img.size
         img = img.crop(( 0, 0, width, height-40))
         img.save(os.path.join(directory, image))
         img = PImage.open(os.path.join(directory, image))
         width, height = img.size
         if width/maxw>height/maxh:
             height=height/(width/maxw)
             width=maxw
             if width>height:
                 img = img.rotate(90)
                 img.save(os.path.join(directory, image))
                 width, height = img.size
                 if width/maxw>height/maxh:
                     height=height/(width/maxw)
                     width=maxw
                 else:
                     width=width/(height/maxh)
                     height=maxh
         else:
             width=width/(height/maxh)
             height=maxh
         im = Image(os.path.join(directory, image), width, height)
         Story.append(im)
     c.build(Story)
     interface.completed = interface.completed+(0.2499/interface.seriesLen)
     idle_add(self.update_status, interface.completed, 'Done chapter '+linkbundle[1].strip('c'))
     interface.temps.append(os.path.join(interface.series, linkbundle[1]))
コード例 #10
0
ファイル: generate_pdf_invoice.py プロジェクト: tuian/mq
def generate(doc_id):
    """given the document id generate a pdf string output
    """
    s = couchdb.Server(settings.COUCH_DSN)
    db = s['client_docs']
    doc = db.get(doc_id)

    if doc == None:
        raise Exception('Failed to generate pdf.',
                        'Document %s not found.' % doc_id)

    client_id = doc['client_id']

    engine = create_engine(settings.MYSQL_DSN)
    conn = engine.connect()

    output_stream = StringIO()
    doc_pdf = SimpleDocTemplate(output_stream)

    #get fname, lname
    sql = text("""SELECT fname, lname, company_name, company_address from leads
        WHERE id = :client_id
        """)
    client_details = conn.execute(sql, client_id=client_id).fetchone()

    doc_pdf.client_id = client_id
    doc_pdf.client_details = client_details
    doc_pdf.order_id = doc['order_id']

    #check clients running balance
    r = db.view('client/running_balance', key=client_id)

    if len(r.rows) == 0:
        doc_pdf.running_balance = Decimal(0)
    else:
        doc_pdf.running_balance = Decimal('%0.2f' % r.rows[0].value)

    sql = text("""SELECT sign from currency_lookup
        WHERE code = :currency
        """)
    doc_pdf.currency_sign = conn.execute(
        sql, currency=doc['currency']).fetchone()['sign']
    doc_pdf.currency = doc['currency']
    doc_pdf.total_amount = locale.format('%0.2f', Decimal(doc['total_amount']),
                                         True)

    if doc.has_key('invoice_date'):
        x = doc['invoice_date']
    else:
        x = doc['added_on']
    doc_pdf.invoice_date = date(x[0], x[1], x[2]).strftime('%B %d, %Y')

    if doc.has_key('pay_before_date'):
        x = doc['pay_before_date']
        doc_pdf.pay_before_date = date(x[0], x[1], x[2]).strftime('%B %d, %Y')

    #get client settings     for the removal of Available Balance
    now = get_ph_time(as_array=True)
    view = db.view('client/settings',
                   startkey=[client_id, now],
                   endkey=[client_id, [2011, 1, 1, 0, 0, 0, 0]],
                   descending=True,
                   limit=1,
                   include_docs=True)
    doc_client_settings = view.rows[0].doc
    show_available_balance = True
    if doc_client_settings.has_key('days_before_suspension'):
        if doc_client_settings['days_before_suspension'] == -30:
            show_available_balance = False

    doc_pdf.show_available_balance = show_available_balance

    #spacer
    Story = [Spacer(1, 3 * inch)]

    #collect items
    items = doc['items']
    items_has_date = False

    styles = getSampleStyleSheet()
    style_table = styles['Normal']
    style_table.fontSize = 8
    p_num_hours = Paragraph('<b>Number of Hours / Quantity</b>', style_table)
    p_hourly_rate = Paragraph(
        '<b>Hourly Rate / Unit Price %s</b>' % (doc_pdf.currency_sign),
        style_table)
    pdf_items = [
        [
            "Item", "Date", "Name and Designation of Staff", p_num_hours,
            p_hourly_rate,
            "Amount %s" % (doc_pdf.currency_sign)
        ],
    ]

    for item in items:
        item_date = ''
        if item.has_key('start_date'):
            items_has_date = True
            x = item['start_date']
            y = date(x[0], x[1], x[2])
            item_date += y.strftime('%b %d, %Y')

        if item.has_key('end_date'):
            items_has_date = True
            x = item['end_date']
            y = date(x[0], x[1], x[2])
            item_date += y.strftime(' - %b %d, %Y')

        description = Paragraph(item['description'], style_table)
        pdf_item = [
            item['item_id'],
            Paragraph(item_date, style_table), description,
            locale.format('%0.2f', Decimal(item['qty']), True),
            locale.format('%0.2f', Decimal(item['unit_price']), True),
            locale.format('%0.2f', Decimal(item['amount']), True)
        ]
        pdf_items.append(pdf_item)

    summary = []
    #append sub_total
    p_sub_total = Paragraph('<para alignment="right"><b>Sub Total</b></para>',
                            style_table)
    summary.append([
        p_sub_total, '', '', '', '',
        locale.format('%0.2f', Decimal(doc['sub_total']), True)
    ])

    #append gst
    p_gst = Paragraph('<para alignment="right"><b>GST</b></para>', style_table)
    summary.append([
        p_gst, '', '', '', '',
        locale.format('%0.2f', Decimal(doc['gst_amount']), True)
    ])

    #append total_amount
    p_total_amount = Paragraph(
        '<para alignment="right"><b>Total Amount</b></para>', style_table)
    summary.append([
        p_total_amount, '', '', '', '',
        '%s %s%s' %
        (doc_pdf.currency, doc_pdf.currency_sign,
         locale.format('%0.2f', Decimal(doc['total_amount']), True))
    ])

    grid_style = [
        ('GRID', (0, 0), (-1, -1), 0.5, colors.grey),
        ('FONTSIZE', (0, 0), (-1, -1), 8),
        ('FONTNAME', (0, 0), (-1, 0), 'Helvetica-Bold'),
        ('ALIGN', (0, 0), (-1, 0), 'CENTER'),
        ('ALIGN', (0, 1), (0, -1), 'RIGHT'),
        ('ALIGN', (3, 1), (3, -1), 'RIGHT'),
        ('ALIGN', (4, 1), (4, -1), 'RIGHT'),
        ('ALIGN', (5, 1), (5, -1), 'RIGHT'),
    ]

    width_date = 1 * inch
    width_description = None
    if items_has_date == False:
        width_date = 0.4 * inch
        width_description = 3.5 * inch

    t = Table(pdf_items,
              colWidths=[
                  0.4 * inch, width_date, width_description, 0.6 * inch,
                  0.6 * inch, 1 * inch
              ],
              style=grid_style,
              repeatRows=1)
    Story.append(t)

    grid_style_summary = [
        ('FONTSIZE', (0, 0), (-1, -1), 8),
        ('ALIGN', (5, 0), (5, -1), 'RIGHT'),
        ('SPAN', (0, -1), (4, -1)),
        ('SPAN', (0, -2), (4, -2)),
        ('SPAN', (0, -3), (4, -3)),
        ('FONTNAME', (-1, -1), (-1, -1),
         'Helvetica-Bold'),  #bold total_amount figure
        ('BACKGROUND', (-1, -1), (-1, -1),
         colors.yellow),  #change background color or total_amount figure
        ('GRID', (-1, -3), (-1, -1), 0.5, colors.grey),
    ]
    t_summary = Table(summary,
                      colWidths=[
                          0.4 * inch, width_date, width_description,
                          0.6 * inch, 0.6 * inch, 1 * inch
                      ],
                      style=grid_style_summary)
    Story.append(t_summary)

    p = Paragraph("""HOW TO PAY:""", styleH2)
    Story.append(p)
    Story.append(Spacer(1, 0.1 * inch))

    styles = getSampleStyleSheet()
    style = styles["Normal"]
    style.borderWidth = 1
    style.borderRadius = 0.08 * inch
    style.borderPadding = 0.1 * inch
    style.fontName = 'Helvetica'
    style.borderColor = (0.22, 0.34, 0.53)
    style.backColor = (0.92, 0.96, 0.86)
    style.spaceAfter = 0.25 * inch

    #payment_link = 'https://remotestaff.com.au/portal/ClientTopUp/TopUp.html?order_id=%s' % doc['order_id']
    payment_link = 'https://remotestaff.com.au/portal/v2/payments/top-up/%s' % doc[
        'order_id']
    p = Paragraph(
        """
    <b>PAY ONLINE OR PHONE USING YOUR CREDIT CARD</b><br/>&nbsp<br/>
    We accept Visa, Master Card and AMEX. Follow this link <a color="blue" href="%s">%s</a>
    to pay for this invoice or call +61(02) 8014 9196 press 4 to pay over the phone.
    """ % (payment_link, payment_link), style)
    Story.append(p)

    debit_form_link = 'https://remotestaff.com.au/portal/pdf_report/credit_card_debit_form/THKGENDirectDebitForm.pdf'
    credit_card_form_link = 'https://remotestaff.com.au/portal/pdf_report/credit_card_debit_form/?id=%s' % client_id
    p = Paragraph(
        """
    <b>AUTO DEBIT</b><br/>&nbsp<br/>
    Have your account paid on the invoice due date automaticaly via direct debit or credit card to save time. Fill this form <a color="blue" href="%s">%s</a> (Australian Clients Only) or Credit Card form <a color="blue" href="%s">%s</a> and return to <a color="blue" href="mailto:[email protected]">[email protected]</a>
    """ % (debit_form_link, debit_form_link, credit_card_form_link,
           credit_card_form_link), style)
    Story.append(p)

    p = Paragraph(
        """
    <b>ELECTRONIC BANK TRANSFER TO</b><br/>&nbsp<br/>
    <b>Australia : </b><br/>
    Account Name: Think Innovations Pty. Ltd.<br/>
    BSB: 082 973<br/>
    Account Number: 49 058 9267<br/>
    Bank Branch: Darling Street, Balmain NSW 2041<br/>
    Swift Code: NATAAU3302S<br/>&nbsp<br/>
    <b>United Kingdom : </b><br/>
    Account Name: Think Innovations Pty. Ltd.<br/>
    UK Bank Address: HSBC. 25 Nothing Hill Gate. London. W11 3JJ<br/>
    Sort code: 40-05-09<br/>
    Acc: 61-50-63-23<br/>
    Swift Code: MIDLGB22<br/>
    IBAN Number: GB54MIDL40050961506323<br/>&nbsp;<br/>
    <b>United States : </b><br/>
    Account Name: Think Innovations Pty. Ltd.<br/>
    Bank Branch: HSBC Bank USA NA 452 Fifth Avenue, New York, NY 10018<br/>
    Account number: 048-984-515<br/>
    Routing Number: 021001088<br/>
    Swift code: MRMDUS33<br/>
    """, style)
    Story.append(p)

    p = Paragraph(
        """
    <b>Note:</b><br/>&nbsp;<br/>
    For Invoices in Australian Dollar a Merchant facility fees apply for the following credit card holders:
    <br/>
    """, styleN)
    Story.append(p)

    styleN.bulletIndent = 0.2 * inch
    p = Paragraph("""<br/><bullet>AMEX : 2%</bullet>""", styleN)
    Story.append(p)

    p = Paragraph("""<br/><bullet>Visa / MasterCard : 1%</bullet>""", styleN)
    Story.append(p)

    p = Paragraph(
        """<br/>For Invoices in Pounds and USD, 2% Merchant facility fees apply for all credit card payments.""",
        styleN)
    Story.append(p)

    p = Paragraph(
        """<br/>Paypal fees ranging from 1.1% - 2.4% of your invoice amount applies and will be reflected as a debit on your Available Balance Sheet.""",
        styleN)
    Story.append(p)

    p = Paragraph(
        """<br/>Note that we prefer payments made via bank transfer or direct debit.""",
        styleN)
    Story.append(p)

    Story.append(Spacer(1, 1 * inch))

    styles_ref_doc = getSampleStyleSheet()
    style_ref_doc = styles_ref_doc['Normal']
    style_ref_doc.fontName = 'Courier'
    style_ref_doc.fontSize = 9
    p = Paragraph(
        """
    -----------------------------------------<br/>
    Ref doc: %s
    -----------------------------------------<br/>
    """ % doc_id, style_ref_doc)
    Story.append(p)

    doc_pdf.title = 'INVOICE %s' % doc['order_id']
    doc_pdf.subject = 'doc_id %s' % doc['_id']
    doc_pdf.author = 'remotestaff'
    doc_pdf.creator = 'celery task generate_pdf_invoice.generate'
    doc_pdf.build(Story, onFirstPage=myFirstPage, onLaterPages=myLaterPages)
    output_stream.seek(0)
    return output_stream.read()