Monday, November 12, 2012

How To Render Total Pagenumber In Pdf's With Reportlab

Here is my way to render pdf-files with a "totalPagenumber" option:

Note: The pdf is rendered twice. This may cause problems on low-performance machines or for very big files.

The idea is to pass the number of pages from the first rendering to the second.
To do this I use this function:

from pyPdf import PdfFileReader

def genPdf(renderPageNumber=True):
    filename = pdfWriter()
    if renderPageNumber:
        pdfFile = pdfFileReader(open(filename,'rb'))
        filename = pdfWriter(' / %d'%pdfFile.numPages)

To get the number of pages of a pdf file you need the pyPdf package!

The pdfWriter function generates the pdf file:

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

def pdfWriter( totalPages='' ):

    filename = 'test.pdf'
    PAGE_HEIGHT=defaultPageSize[1]
    PAGE_WIDTH=defaultPageSize[0]
    styles = getSampleStyleSheet()
    Title = "Hello world"
    pageinfo = "platypus example"

    def myFirstPage(canvas, doc):
        canvas.saveState()
        canvas.setFont('Times-Bold',16)
        canvas.drawCentredString(PAGE_WIDTH/2.0, PAGE_HEIGHT-108, Title)
        canvas.setFont('Times-Roman',9)
        canvas.drawString(inch, 0.75 * inch,"%s: Page %d%s" % (pageinfo, doc.page, totalPages) )
        canvas.restoreState()

    def myLaterPages(canvas, doc):
        canvas.saveState()
        canvas.setFont('Times-Roman', 9)
        canvas.drawString(inch, 0.75 * inch,"%s: Page %d%s" % (pageinfo, doc.page, totalPages) )
        canvas.restoreState()

    doc = SimpleDocTemplate(filename)
    Story = [Spacer(1,2*inch)]
    style = styles["Normal"]
    for i in range(100):
        bogustext = ("Paragraph number %s. " % i) *20
        p = Paragraph(bogustext, style)
        Story.append(p)
        Story.append(Spacer(1,0.2*inch))
    doc.build(Story, onFirstPage=myFirstPage, onLaterPages=myLaterPages)
    return filename

The pdf rendering is done by the ReportLab Toolkit.

To return the pdf as responce in a django app, I use a function like this, where i render the pdf into a cStringIO. The output I add to the response in the view.

Wednesday, November 7, 2012

Django Tips: How To Get Current Variables Or Request

When developing django-apps, I often raise a ZeroDivisionError to stop the script at a certain point.

print 1/0

This makes especially sense to debug code which includes save or redirect commands.

This is also an easy possibility to access the current local vars or request at a certain point of your script via the django traceback.

You have to enable debugging in your django settings:

DEBUG = True

Sunday, October 21, 2012

How To Setup Vertical Centered Labels With One Or Two Lines

The Problem

You try to style a form where you have labels with a fixed width. In some cases this leads to more than one line. You could define an individual style for each label. But this solution is very costly and it crashes if you need multilingual support because different languages may lead to different numbers of lines.

The Solution

There is an easy css-trick to get this behavior. You can set vertical-align: middle; in order to center the label. The vertical-align property requires the label to be wrapped into a div which is displayed as table. The label-tag itself has to be displayed as table-cell.

Example

CSS

.labelWrapper {
    display: table;
    float: left;
    height: 40px;
    line-height: 20px;
    margin: 3px 0; /*input border+padding*/
    width: 100px;
}

label {
    display: table-cell;
    vertical-align: middle;
}

input {
    height: 40px;
    padding: 2px 20px;
}

HTML

<form action="#" method="GET">
  <div class="fieldWrapper">
    <div class="labelWrapper">
      <label for="id_name">Name</label>
    </div>
    <input id="id_name" name="name" type="text">
  </div>
  <div class="fieldWrapper">
    <div class="labelWrapper">
      <label for="id_honorific_prefixes">Honorific Prefixes</label>
    </div>
    <input id="id_honorific_prefixes" name="honorific_prefixes" type="text">
  </div>
</form>

Monday, November 21, 2011

Random Passwort Generator

I would like to share my password generator with you:

Features:

  • set length
  • set possible caracters
    • lowercase
    • uppercase
    • digits
    • special
  • set frequency of different types
  • possibility to validate passwords
    • at least one lowercase letter included
    • at least one uppercase letter included
    • at least one digit included
    • at least one special caracter included
  • generates printable passwords
    • without: Il1oO0"'`
  • generates multiple passwords

Install:

The following commands should work at standard linux intallations:

$ sudo wget -P/usr/bin/ https://pool.umws.de/public/blog/passgen
$ sudo chmod +x passgen

The following commands should work at standard mac intallations:

$ sudo curl https://pool.umws.de/public/blog/passgen -o /opt/local/bin/passgen
$ sudo chmod +x /opt/local/bin/passgen

Otherwise you can download it manually: passgen

When you downloaded the file, you have to give execute permissions to it.

Usage:

Usage: passgen [-options]
where options include:

optiondefault
-N <number>number of generated passwords1
-L <length>length of generated passwords8
-P Falsenot printableTrue
-U <types>set types of possible caracters:
L = lowercase
U = uppercase
D = digit
S = special caracters
LUDS
-T <types>at least on caracter of these types will be included:
L = lowercase
U = uppercase
D = digit
S = special caracters
LUDS
-cL <multiplier>[1-9] multiply chance for lowercase caracters2
-cU <multiplier>[1-9] multiply chance for uppercase caracters2
-cD <multiplier>[1-9] multiply chance for digits2
-cS <multiplier>[1-9] multiply chance for special caracters1
In order to generate secure passwords, I would strongly recommend to change number and length options only!

Examples:

Use default settings:

$ passgen


1 password generated:
--------
fzU6r.qE
--------

Generate 5 passwords with 12 caracters:

$ passgen -L 12 -N 5


5 passwords generated:
------------
.B3Tcw4gGh@|
;X9$XGGkkc$E
7vxUC.5UcxES
T,Je.9_ZVQzA
qw<CJV6aJBmr
------------

Generate password without special caracters:

$ passgen -U LUD


1 password generated:
--------
Na84V5Wi
--------

License:

License: GPLv3

This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or any later version.

This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.

Tuesday, May 17, 2011

Pure Css Rating

I was looking for a pure css rating template and couldn't find anything.

Here's my solution:

HTML:

<div class="rateBar">
    <a class="r5" href="/rate/5"></a>
    <a class="r4" href="/rate/4"></a>
    <a class="r3" href="/rate/3"></a>
    <a class="r2" href="/rate/2"></a>
    <a class="r1" href="/rate/1"></a>
</div>

CSS:

.rateBar {
    margin: 30px auto;
    width:260px; height:48px;
    background-image:url("rate_off_bg.png");
}

.rateBar a       { height:48px; position: absolute; }
.rateBar a:hover { background-image:url("rate_on.png"); }

.r1 { width: 48px; }
.r2 { width:101px; }
.r3 { width:154px; }
.r4 { width:207px; }
.r5 { width:260px; }

Images:

based on: Crystal Clear (crystal_clear), license: LGPL-2.1
based on: Crystal Clear (crystal_clear), license: LGPL-2.1