[magick-users] pdf to png in python

Carl Karsten carl at personnelware.com
Thu Dec 27 22:41:18 PST 2007


Carl Karsten wrote:
> I am using python's reportlab to create a pdf (of a conference name tag) 
> and I want to be able to have an image preview on the registration form 
> web page.
> 
> convert foo.pdf foo.png does what I need.  What I am looking for is a 
> good API to that, or anything similar.
> 
> Ideally, it won't require a file system file (easier on the web server.)
> 
> Here is what the code looks like that generates the pdf:
> 
>     buffer = StringIO()
>     rw = dReportWriter(OutputFile=buffer, ReportFormFile=xmlfile, 
> Cursor=ds)
>     rw.write()
>     pdf = buffer.getvalue()
>     return pdf
> 

lucky for me Achim Domma just made a very early alpha version of python bindings 
for ImageMagick.  yay!  http://www.procoders.net/?p=39

this works:

from PythonMagickWand import *
def test1():
     MagickWandGenesis()
     wand = NewMagickWand()
     MagickReadImage(wand,"badge.pdf")
     MagickWriteImage(wand,"badge.png")

But that is reading/writing a file.  I took a shot at coding it to accept the 
pdf as a blob, and here is what I get:

def test2():
     MagickWandGenesis()
     wand = NewMagickWand()

     # read in the pdf
     pdf=open("badge.pdf").read()

     # convert pdf to png
     MagickReadImageBlob(wand, pdf, len(pdf) )

At this point it crashes:
Error: /ioerror in --run--
Operand stack:
    --nostringval--   --nostringval--   ( !\n%)
Execution stack:
    %interp_exit   .runexec2   --nostringval--   --nostringval-- 
--nostringval--   2   %stopped_push   --nostringval--   --nostringval-- 
--nostringval--   false   1   %stopped_push   1889   1   3   %oparray_pop 
--nostringval--
Dictionary stack:
    --dict:1156/1684(ro)(G)--   --dict:0/20(G)--   --dict:92/200(L)--
Current allocation mode is local
Last OS error: 21
GPL Ghostscript SVN PRE-RELEASE 8.61: Unrecoverable error, exit code 1
12397 Segmentation fault      (core dumped) python ckpmw.py

The fact that ghostscript is involved is encouraging - it means it knows it is 
pdf data.

Once I get that working, I will need this to work:

def test3():
     MagickWandGenesis()
     wand = NewMagickWand()
     MagickReadImage(wand,"badge.pdf")

     MagickSetFormat(wand, 'PNG' )
     png=MagickGetImageBlob(wand, 1000000 )

     # png = MagickWriteImageBlob(wand, ???)
     # http://www.imagemagick.org/www/api/magick-deprecate.html#MagickWriteImageBlob

     # write the png
     open("badge.png", 'wb').write(png)


This is the closest I have come to working with python ctypes, so forgive me if 
I am totally missing something.

Carl K


More information about the Magick-users mailing list