如何在 Django 模型中从 PDF 中提取和保存文件

How to extract and save files from PDF in a Django Model

我现在正在做一个项目,需要提取附加到模型的 PDF。然后 PDF 与项目相关,如下所示 models.py:

class Project(models.Model):
   name = models.CharField(max_length=100)
   files = models.FileField('PDF Dataset',
                            help_text='Upload a zip here',
                            null=True)

class Pdf(models.Model):
   name = models.CharField(max_length=100)
   file = models.FileField(null=True)
   project = models.ForeignKey(Project, on_delete=models.CASCADE)

然后我有一个任务可以通过 Celery 触发以提取 PDF 并将每个保存为自己的记录。我的示例 tasks.py 下面:

from django.core.files.base import ContentFile
from celery import shared_task
from zipfile import ZipFile
import re

def extract_pdfs_from_zip(self, project_id: int):
    project = Project.objects.get(pk=project_id)
    ...
    # Start unzipping from here.
    # NOTE: This script precludes that there's no MACOSX shenanigans in the zip file.
    pdf_file_pattern = re.compile(r'.*\.pdf')
    pdf_name_pattern = re.compile(r'.*\/(.*\.pdf)')
    with ZipFile(project.files) as zipfile:
       for name in zipfile.namelist():
           # S2: Check if file is .pdf
           if pdf_file_pattern.match(name):
                pdf_name = pdf_name_pattern.match(name).group(1)
                print('Accessing {}...'.format(pdf_name))
                # S3: Save file as a new Pdf entry
                new_pdf = Pdf.objects.create(name=pdf_name, project=project)
                new_pdf.file.save(ContentFile(zipfile.read(name)),
                                  pdf_name, save=True) # Problem here
                print('New document saved: {}'.format(new_pdf))
           else:
                print('Not a PDF: {}'.format(name))
    return 'Run complete, all PDFs uploaded.'

但出于某种原因,保存文档的部分不再输出 PDF。我知道原始 zip 的内容,所以我确定它们是 PDF。有什么想法可以在保存文件的同时保留其 PDF 特性吗?

预期结果是 PDF 可读。现在,当我打开文件时,它显示为已损坏。感谢您对此的帮助。

糟糕,我的 zip 文件似乎已因删除 _MACOSX 文件而损坏。我在 tasks.py 文件之外进行了删除。有关详细信息,请参阅 Mac zip compress without __MACOSX folder?