Skip to content

Instantly share code, notes, and snippets.

@yoojinyoung
Last active December 4, 2019 05:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yoojinyoung/31baf1d1cae82d41d62f5ff2ead40e5a to your computer and use it in GitHub Desktop.
Save yoojinyoung/31baf1d1cae82d41d62f5ff2ead40e5a to your computer and use it in GitHub Desktop.
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