简体   繁体   中英

Django : How to convert pdf file object to image using pdf2image?

I am trying to create a epaper web app, in which admin can upload file in pdf format and which is converted to image while rendering the page from client side. I have tried pdf2image but getting error something like this:

PDFPageCountError at /city_list
Unable to get page count.
I/O Error: Couldn't open file '['/media/pdf/Akola/2020/04/24/page01.pdf']': No such file or directory.

here is my code:

models.py

class City(models.Model):
    cityid =models.AutoField(primary_key=True)
    name = models.CharField( max_length=50)
def user_directory_path(instance, filename):
# file will be uploaded to MEDIA_ROOT/user_<id>/<filename>
ab = instance.date.strftime("%Y/%m/%d")
return 'pdf/{0}/{1}/{2}'.format(instance.city.name,ab, filename)

class DailyFeed(models.Model):
    city = models.ForeignKey(City, on_delete=models.CASCADE)
    date =models.DateField(auto_now=False, auto_now_add=False)
    page1  = models.FileField(upload_to=user_directory_path)
    page2 = models.FileField(upload_to=user_directory_path) 
    page3 = models.FileField(upload_to=user_directory_path)

views.py:

def city(request):
    city_list = City.objects.all()

    daily = DailyFeed.objects.filter(date=timezone.now().date()).filter(city__name = "Akola")
    ab = [pdfurl.page1.url for pdfurl in daily ]
    path = r'{}'.format(ab)
    a = str(path)
    pages = convert_from_path('{}'.format(a), 200)
    for pdf in pages:
        pdf.save('{}.jpg'.format(a.name[:-4]), 'JPEG')
    return render (request,'main.html',{'city_list':city_list,'page':pdf})

urls.py

re_path(r'^city_list',views.city,name='city'),

I am have not getting where I am going wrong?

use path instead of url. URL is not where the file is, but how the browser can access it

[pdfurl.page1.url for pdfurl in daily ]

to

[pdfurl.page1.path for pdfurl in daily ]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM