Reputation: 11
I am trying to run a script that will go through a specific folder and use Wand to create a .png file of every .pdf file that it finds in that folder.
from wand.image import Image
import os
pdf_dir = r"D:\Program Files\Python\Python36-32\tom's shitty programs\Downloads"
for x in os.listdir(pdf_dir):
if x.endswith(".pdf"):
pdf_path = pdf_dir + '\\' + x
with Image(filename=pdf_path, resolution=300) as pdf:
page_index = 0
height = pdf.height
with Image(width=pdf.width, height=len(pdf.sequence)*height) as png:
for page in pdf.sequence:
png.composite(page, 0, page_index * height)
page_index += 1
png.save(filename=pdf_path[:-3] + "png")
This returns the following errors:
Traceback (most recent call last):
File "D:\Program Files\Python\Python36-32\tom's shitty programs\venv\lib\site-packages\wand\image.py", line 1799, in wand return self.resource
File "D:\Program Files\Python\Python36-32\tom's shitty programs\venv\lib\site-packages\wand\resource.py", line 151, in resource raise DestroyedResourceError(repr(self) + ' is destroyed already')
wand.resource.DestroyedResourceError: is destroyed already
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "D:/Program Files/Python/Python36-32/tom's shitty programs/wand_test.py", line 13, in with Image(width=pdf.width, height=len(pdf.sequence)*height) as png:
File "D:\Program Files\Python\Python36-32\tom's shitty programs\venv\lib\site-packages\wand\image.py", line 1817, in width return library.MagickGetImageWidth(self.wand)
File "D:\Program Files\Python\Python36-32\tom's shitty programs\venv\lib\site-packages\wand\image.py", line 1801, in wand raise ClosedImageError(repr(self) + ' is closed already')
wand.image.ClosedImageError: is closed already
Any help is appreciated... thank you
Upvotes: 1
Views: 906
Reputation: 24419
This is just some minor with ... as ..
context manager issues and/or typos. As the error message states, you are attempting to work with a variable (pdf
) after the resources has already been closed. Double check the indentation.
with Image(filename=pdf_path, resolution=300) as pdf:
page_index = 0
height = pdf.height
with Image(width=pdf.width, height=len(pdf.sequence)*height) as png:
for page in pdf.sequence:
png.composite(page, 0, page_index * height)
page_index += 1
png.save(filename=pdf_path[:-3] + "png")
If you're using version 0.5.0 of Wand, then you might be able to take advantage of wand.image.Image.concat
method.
with Image(filename=pdf_path, resolution=300) as pdf:
pdf.concat(True)
pdf.save(filename=pdf_path[:-3] + "png")
Upvotes: 1