Converte de PDF para JPG

Publicado por Artur Gaspar (última atualização em 13/04/2010)

[ Hits: 6.219 ]

Download hello.py




Converte PDF para JPG e retorna uma lista com as imagens.

Depende do pacote ghostscript-library ou algum outro que contenha o programa "gs" no $PATH.

  



Esconder código-fonte

from os import listdir, path
from re import match
from signal import SIGKILL
from subprocess import Popen, PIPE
from tempfile import mkdtemp
from time import time

def pdf2jpg(pdf, timeout=False):
    dir = mkdtemp()
    gs = Popen(['gs', '-dSAFER', '-dBATCH', '-dNOPAUSE', '-sDEVICE=jpeg', 
                '-r150', '-dTextAlphaB', 'its=4', '-dGraphicsAlphaBits=4', 
                '-dMaxStripSize=8192', '-sOutputFile=%s/page%%d.jpg' % dir, 
                pdf], stdin=PIPE, stdout=PIPE, stderr=PIPE)
    if timeout:
        start = time()
        while time() - start <= timeout:
            if gs.poll() == None:
                # Not terminated
                pass
            elif gs.poll() == 0:
                # Terminated ok
                break
            else:
                # Not ok
                stdout, stderr = gs.communicate()
                raise EnvironmentError(None, 'GhostScript terminated unexpect'
                                       'edly', 'Stdout: \n%s\nStderr: \n%s\n'
                                       % (stdout, stderr))
                return False
        gs.send_signal(SIGKILL)
    else:
        if gs.wait() != 0:
            stdout, stderr = gs.communicate()
            raise EnvironmentError(None, 'GhostScript terminated unexpectedly', 
                                   'Stdout: \n%s\nStderr: \n%s\n' % (stdout, 
                                   stderr))
            return False
    images = []
    for image in listdir(dir):
        if match('page[0-9][0-9]*.jpg', image):
            images.append(path.join(dir, image))
    return images

Scripts recomendados

Manipulando arquivos com Pickle

subwrite - um simples editor de texto em Python

Agenda Python

Converte valor de Bytes 2 Kbyte 2 Mbyte

Leitor de arquivo via linha de comandoEs


  

Comentários

Nenhum comentário foi encontrado.


Contribuir com comentário