Feature: page count (#7750)

---------

Co-authored-by: shamoon <4887959+shamoon@users.noreply.github.com>
This commit is contained in:
s0llvan
2024-09-25 17:22:12 +02:00
committed by GitHub
parent 4adf20af1e
commit c92c3e224a
23 changed files with 319 additions and 45 deletions

View File

@@ -0,0 +1,62 @@
# Generated by Django 4.2.16 on 2024-09-21 15:44
from pathlib import Path
import pikepdf
from django.conf import settings
from django.db import migrations
from django.db import models
from django.utils.termcolors import colorize as colourise
def source_path(self):
if self.filename:
fname = str(self.filename)
return Path(settings.ORIGINALS_DIR / fname).resolve()
def add_number_of_pages_to_page_count(apps, schema_editor):
Document = apps.get_model("documents", "Document")
if not Document.objects.all().exists():
return
for doc in Document.objects.filter(mime_type="application/pdf"):
print(
" {} {} {}".format(
colourise("*", fg="green"),
colourise("Calculating number of pages for", fg="white"),
colourise(doc.filename, fg="cyan"),
),
)
try:
with pikepdf.Pdf.open(source_path(doc)) as pdf:
if pdf.pages is not None:
doc.page_count = len(pdf.pages)
doc.save()
except Exception as e: # pragma: no cover
print(f"Error retrieving number of pages for {doc.filename}: {e}")
class Migration(migrations.Migration):
dependencies = [
("documents", "1052_document_transaction_id"),
]
operations = [
migrations.AddField(
model_name="document",
name="page_count",
field=models.PositiveIntegerField(
blank=False,
null=True,
unique=False,
db_index=False,
),
),
migrations.RunPython(
add_number_of_pages_to_page_count,
migrations.RunPython.noop,
),
]