fix: uploading barcode pdf files instead of images

This commit is contained in:
2024-11-06 15:35:28 +04:00
parent 4f9d55d2c6
commit fced9b8101
4 changed files with 36 additions and 22 deletions

View File

@@ -30,21 +30,9 @@ class BarcodeImagesUploader(BaseImagesUploader):
file_location.unlink()
async def upload(self, upload_file: UploadFile) -> str:
# Create temp file in filesystem
temp_filename = str(uuid4()) + '.' + upload_file.filename.split('.')[-1]
temp_file_location = self.storage_path / temp_filename
with open(temp_file_location, 'wb') as buffer:
filename = str(uuid4()) + '.' + upload_file.filename.split('.')[-1]
file_location = self.storage_path / filename
with open(file_location, 'wb') as buffer:
await copyfileobj(upload_file.file, buffer)
# Generate PDF file and save it
res_filename = str(uuid4()) + '.pdf'
res_file_location = f"{self.storage_path}/{res_filename}"
temp_file_url = f"{self.relative_path}/{temp_filename}"
pdf_gen = PDFGenerator()
pdf_gen.generate_barcode_image(temp_file_url, res_file_location)
# Remove temp file
self.delete(temp_filename)
return res_filename
return filename

View File

@@ -189,8 +189,3 @@ class PDFGenerator:
pdf_maker.add_pdfs(file)
return pdf_maker.get_bytes()
def generate_barcode_image(self, barcode_image_url: str, path_to_save_pdf: str):
c = canvas.Canvas(path_to_save_pdf, pagesize=(self.page_width, self.page_height))
c.drawImage(barcode_image_url, 0, 0, width=self.page_width, height=self.page_height)
c.save()

View File

@@ -1,7 +1,11 @@
from io import BytesIO
from typing import BinaryIO
from fpdf import FPDF
import pdfrw
from pdfrw import PdfReader
from pdfrw.objects.pdfdict import PdfDict
class PdfMaker:
def __init__(self, size: tuple):
@@ -36,3 +40,29 @@ class PdfMaker:
self.writer.write(result_io)
result_io.seek(0)
return result_io
@staticmethod
def check_is_correct_aspects_ratio(file: BinaryIO):
pdf = PdfReader(file)
allowed_aspects_ratio = 1.45
page: PdfDict
try:
page: PdfDict = pdf.getPage(0)
except IndexError:
raise Exception("Ошибка. В документе нет страниц.")
try:
pdf.getPage(1)
raise Exception("Ошибка. В документе должна быть только одна страница.")
except IndexError:
pass
media_box = page.MediaBox
width = float(media_box[2]) - float(media_box[0])
height = float(media_box[3]) - float(media_box[1])
aspect_ratio = width / height
if abs(aspect_ratio - allowed_aspects_ratio) > 0.01:
raise Exception("Ошибка. Страница документа должна быть размером 58х40.")
file.seek(0)