Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
How to make pdf to image and and save that with instance when using django.
# https://github.com/Belval/pdf2image
# https://www.revsys.com/tidbits/loading-django-files-from-code/
import os
import tempfile
from django.core.files import File
from pdf2image import convert_from_path
from .models import CustomModel
custom_model = CustomModel.objects.get(pk=1)
pdf_path = 'pdf/path/file.pdf'
with tempfile.TemporaryDirectory() as path:
image_path = convert_from_path(pdf_path, size=(500, None), fmt='jpeg', single_file=True,
output_folder=path, paths_only=True)[0]
cover_img_path = os.path.splitext(
os.path.basename(custom_model.file.name))[0] + '.jpeg'
custom_model.cover_img.save(cover_img_path, File(
open(image_path, 'rb')), save=True)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment