Download images as png or pdf

 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
# This is not a full working example, just a starting point
# for downloading images in different formats.

import subprocess
import Image

def image_as_png_pdf(request):
  output_format = request.GET.get('format')
  im = Image.open(path_to_image) # any Image object should work
  if output_format == 'png':
    response = HttpResponse(mimetype='image/png')
    response['Content-Disposition'] = 'attachment; filename=%s.png' % filename
    im.save(response, 'png') # will call response.write()
  else:
    # Temporary disk space, server process needs write access
    tmp_path = '/tmp/'
    # Full path to ImageMagick convert binary
    convert_bin = '/usr/bin/convert' 
    im.save(tmp_path+filename+'.png', 'png')
    response = HttpResponse(mimetype='application/pdf')
    response['Content-Disposition'] = 'attachment; filename=%s.pdf' % filename
    ret = subprocess.Popen([ convert_bin, 
                            "%s%s.png"%(tmp_path,filename), "pdf:-" ],
                            stdout=subprocess.PIPE)
    response.write(ret.stdout.read())
  return response
 

More like this

  1. Convert LaTeX templates to various output formats by blizz 5 years, 2 months ago
  2. Custom 'save' method, automate creating pdf file from entry. by I159 8 months ago
  3. RML2PDF with Django by meitham 2 years, 2 months ago
  4. A form field for valdating PDF and Microsoft Word document by jimmylam 3 years, 6 months ago
  5. dynamic model graph by findlay 4 years ago

Comments

nick125 (on April 5, 2007):

Looking at the PIL documentation, you could use PIL to create the PDF (http://www.pythonware.com/library/pil/handbook/format-pdf.htm)

#

gkelly (on April 5, 2007):

doh!

That's much simpler. Well, at least I figured out how to use subprocess and pipe stdout to a django response...

#

(Forgotten your password?)