Login

Custom 'save' method, automate creating pdf file from entry.

Author:
I159
Posted:
September 28, 2011
Language:
Python
Version:
Not specified
Tags:
model pdf save reportlab
Score:
0 (after 0 ratings)

Save method, useful for automate pdf files creation if you want to use the file in database.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
import os.path
from reportlab.pdfgen import canvas

from django.db import models
from django.conf import settings


class Entry(models.Model):
    doc = models.TextField()
    file = models.FilePathField(
            path=os.path.join(settings.MEDIA_URL, '/files'), match='*\.pdf',)
    
    def save(self, *args, **kwargs):
        """Writing entry content to new pdf file, saving it in file system
        and make record to database."""
        
        counter = 0
        
        def make_path(counter):
            """Check existing and make new file."""
            
            path = os.path.join(
            settings.STATICFILES_DIRS[1], 'files', 'f' + str(counter) + '.pdf')
            
            if os.path.isfile(path):
                counter += 1
                return make_path(counter)
            return path
            
        curr_path = make_path(counter)
        
        pdf_file = canvas.Canvas(curr_path)
        pdf_file.drawString(100, 750, self.doc)
        pdf_file.save()
        self.file = curr_path
        super(Entry, self).save(*args, **kwargs)

More like this

  1. A form field for valdating PDF and Microsoft Word document by jimmylam 6 years, 9 months ago
  2. Download images as png or pdf by gkelly 8 years, 5 months ago
  3. Create PDF files using rml and django templates by mporrato 8 years, 2 months ago
  4. Automate unique slugs by taojian 7 years, 8 months ago
  5. fabric wsgi deployment strategy by hedde 10 months, 2 weeks ago

Comments

Please login first before commenting.