backend/api/photolog_generator.py
2022-05-20 19:14:48 +02:00

64 lines
1.8 KiB
Python

from photo_log.models import Photo
import os
from django_tex.shortcuts import render_to_pdf, compile_template_to_pdf
from django.db.models import FileField
from django.conf import settings
from .photolog_layout import generate_tex
def get_img_path_by_id(photo_id):
if not photo_id:
return None
photo = Photo.objects.get(id=photo_id)
img = None
if not photo.cropped_image.name:
img = photo.original_image.url
else:
img = photo.cropped_image.url
return img
def get_all_photo_paths(slides, start_slide_image):
id_to_path = {}
image_paths = []
for slide in slides:
for photo_id in slide:
if photo_id == None:
continue
if not photo_id in id_to_path:
path = get_img_path_by_id(photo_id)
id_to_path[photo_id] = path
image_paths.append(id_to_path[photo_id])
start_slide_photo = get_img_path_by_id(start_slide_image)
if not start_slide_image in id_to_path:
path = get_img_path_by_id(start_slide_image)
id_to_path[start_slide_image] = path
if start_slide_photo and not start_slide_photo in image_paths:
image_paths.append(start_slide_photo)
id_to_name = {}
for id in id_to_path:
id_to_name[id], _ = os.path.splitext(os.path.basename(id_to_path[id]))
return image_paths, id_to_name
def generate_photolog_from_latex(request, title, date, render_date, start_slide_image, slides):
image_paths, id_to_name = get_all_photo_paths(slides, start_slide_image)
template_name = 'photolog.tex'
context = {
'content': generate_tex(title, date, render_date, start_slide_image, slides, id_to_name)
}
pdf_bytes = compile_template_to_pdf(template_name, context)
return pdf_bytes