Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Magickwand pdf to image converting and resize the image

I need to create thumbnails of pdf files, and I am using Imagemagick to achieve that.

I have tried Pythonmagick and wand to convert the pdf to an image. However, when I try to resize the converted pdf, the resulting image becomes black.

Is there any option to set -define pdf:use-cropbox=true using python wrappers?

Is there any other method in Python to convert a pdf to a thumbnail?

The code is as follows:

    import wand
    img = wand.image.Image(filename="d:\\test.pdf[0]")
    img.resize(160,160)
    img.save(filename="d:\\test.jpg")
like image 700
user1725030 Avatar asked Oct 06 '12 12:10

user1725030


2 Answers

I found work around for this problem. Convert pdf into image 1st and save the image. open newly saved image and and resize it.

import wand
img = wand.image.Image(filename="d:\\test.pdf[0]")
img.save(filename="d:\\temp.jpg")
img = wand.image.Image(filename="d:\\temp.jpg")
img.resize(160,160)
img.save(filename="d:\\resized_image.jpg")

I am still waiting for better answer.

like image 187
user1725030 Avatar answered Nov 17 '22 13:11

user1725030


I faced the same problem today. I found another solution in other post. The reason why the image turns to black is that the background is transparent in PDF file. Since JPG file cannot recognize the alpha-channel (which record the transparent pixel information). JPG files will set those transparent pixel into black as default.

# Use the following two lines to fix this error
# img_page.background_color = Color('white')
# img_page.alpha_channel = 'remove'

with Image(filename="file.pdf",resolution= 350) as img_pdf:
    num_pages = len(img_pdf.sequence)
    for page, img in enumerate(img_pdf.sequence):
        img_page = Image(image=img)
        img_page.background_color = Color('white')
        img_page.alpha_channel = 'remove'
        img_page.resize(900,1200)
        img_page.save(filename="file"+str(page)+".jpg")
        if page == 0:
            img_page.resize(500, 500)
            img_page.save(filename="thumbnail.jpg")

ref: Python Wand convert PDF to PNG disable transparent (alpha_channel)

like image 23
Craig Avatar answered Nov 17 '22 12:11

Craig