feat: product barcode pdf resize

This commit is contained in:
2025-01-19 17:37:13 +04:00
parent b8947ce68e
commit defe31b55e
5 changed files with 52 additions and 36 deletions

View File

@@ -1,10 +1,8 @@
from io import BytesIO
from typing import BinaryIO
from fpdf import FPDF
import fitz
import pdfrw
from pdfrw import PdfReader
from pdfrw.objects.pdfdict import PdfDict
from fpdf import FPDF
class PdfMaker:
@@ -42,27 +40,44 @@ class PdfMaker:
return result_io
@staticmethod
def check_is_correct_aspects_ratio(file: BinaryIO):
pdf = PdfReader(file)
allowed_aspects_ratio = 1.45
page: PdfDict
def _get_target_rect(page: fitz.Page, target_ratio: float) -> fitz.Rect:
original_width, original_height = page.rect.width, page.rect.height
try:
page: PdfDict = pdf.getPage(0)
except IndexError:
raise Exception("Ошибка. В документе нет страниц.")
if original_width / original_height > target_ratio:
# Image is wider than target aspect ratio
new_width = original_width
new_height = int(original_width / target_ratio)
else:
# Image is taller than target aspect ratio
new_height = original_height
new_width = int(new_height * target_ratio)
try:
pdf.getPage(1)
raise Exception("Ошибка. В документе должна быть только одна страница.")
except IndexError:
pass
return fitz.Rect(0, 0, new_width, new_height)
media_box = page.MediaBox
width = float(media_box[2]) - float(media_box[0])
height = float(media_box[3]) - float(media_box[1])
@staticmethod
def resize_pdf_with_reportlab(input_pdf_bytesio: BytesIO) -> BytesIO:
output_pdf = BytesIO()
aspect_ratio = width / height
if abs(aspect_ratio - allowed_aspects_ratio) > 0.01:
raise Exception("Ошибка. Страница документа должна быть размером 58х40.")
file.seek(0)
pdf_document = fitz.open(stream=input_pdf_bytesio.getvalue(), filetype="pdf")
if len(pdf_document) != 1:
raise Exception("Ошибка. В документе должна быть одна страница.")
page = pdf_document[0]
target_ratio = 29 / 20
actual_ratio = page.rect.width / page.rect.height
if abs(actual_ratio - target_ratio) < 0.1:
return input_pdf_bytesio
rect = PdfMaker._get_target_rect(page, target_ratio)
page.set_mediabox(rect)
page.set_cropbox(rect)
page.set_bleedbox(rect)
page.set_trimbox(rect)
pdf_document.save(output_pdf)
pdf_document.close()
output_pdf.seek(0)
return output_pdf