0

I'm trying to convert a pdf file uploaded in Django to a jpg file. I would like to use the file directly in the InMemoryUploadedFile state.

I tried to use wand but without any success. Here is the code I wrote:

from django.shortcuts import render
from wand.image import Image as wi

# Create your views here.
def readPDF(request):
    context = {}
    if request.method == 'POST':
        uploaded_file = request.FILES['document']
        if uploaded_file.content_type == 'application/pdf':
            pdf = wi(filename=uploaded_file.name, resolution=300)
            pdfImage = pdf.convert("jpeg")
    return render(request, 'readPDF.html', {"pdf": pdfImage})

I tried different things like using uploaded_file.file or uploaded_file.name as the first argument for the wand image but without any success.`

I thank you in advance for your help!

1 Answers1

1

Should be able to pass InMemoryUploadedFile directly to Wand's constructor.

uploaded_file = request.FILES['document']
if uploaded_file.content_type == 'application/pdf':
    with wi(file=uploaded_file, resolution=300) as pdf:
        # ...

However, I wouldn't recommend attempting to convert PDF pages to JPEGs in a HTTP request. Best to write the document to storage, and have a background worker manage the slow / unsafe tasks.

emcconville
  • 23,800
  • 4
  • 50
  • 66