Skip to content

Instantly share code, notes, and snippets.

@rg3915
Created September 22, 2018 02:40
Show Gist options
  • Select an option

  • Save rg3915/c24676e435f9d67af0e703bb85f3a875 to your computer and use it in GitHub Desktop.

Select an option

Save rg3915/c24676e435f9d67af0e703bb85f3a875 to your computer and use it in GitHub Desktop.
Convert PDF to JPG with Python with ghostscript or imagemagick.
# Criando o objeto
obj = Expense.objects.create(**data)

doc = obj.document  # Pega o documento

file_url = doc.url  # Pega a url
file_out_pdf = '/tmp/%s' % doc.name
file_out_jpg = '/tmp/%s.jpg' % doc.name[:-4]  # remove a extensão .pdf

O segredo está aqui urllib.request.urlretrieve

# Download do arquivo do S3 pela url.
new_file = urllib.request.urlretrieve(file_url, file_out_pdf)[0]

Converte pra JPG com ghostscript

# Converte pra JPG
subprocess.call("gs -dBATCH -dNOPAUSE -q -sDEVICE=jpeg -r150 -dAutoRotatePages=/None -sOutputFile=%s %s " %
                (file_out_jpg, new_file), shell=True)

Eu poderia converter com Imagemagick

subprocess.call('convert -density 150 %s %s' % (new_file, file_out_jpg), shell=True)

mas é mais lento.

Thanks @olivx

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment