From a78b9c25d1bbe1490855501430264a49a45632bc Mon Sep 17 00:00:00 2001 From: Esa Kataja Date: Tue, 3 Dec 2024 22:53:23 +0200 Subject: [PATCH] Improve PDF generation with proper A4 sizing and borders - Move PDF border size to settings.py - Use standard A4 dimensions (210x297mm) - Fix aspect ratio preservation in layout function - Use img2pdf's built-in layout function with proper border specification --- pdf_cleaner.py | 17 +++++++++++++++-- settings.py | 3 +++ 2 files changed, 18 insertions(+), 2 deletions(-) diff --git a/pdf_cleaner.py b/pdf_cleaner.py index 0f7c1a0..ceaa31f 100755 --- a/pdf_cleaner.py +++ b/pdf_cleaner.py @@ -20,6 +20,7 @@ class Settings: TRIM_PADDING_PIXELS = 20 MONOCHROME_THRESHOLD = 127 OPTIPNG_OPTIMIZATION_LEVEL = 7 + PDF_BORDER_SIZE = 50 settings = Settings() @@ -379,9 +380,21 @@ def finalize(output_pdf): print(f"Combining {len(temp_files)} pages into {output_pdf}...") - # Convert to PDF + # A4 size in millimeters + A4_WIDTH_MM = 210 + A4_HEIGHT_MM = 297 + + # Convert to PDF with border with open(output_pdf, "wb") as f: - f.write(img2pdf.convert(temp_files)) + f.write(img2pdf.convert( + temp_files, + with_pdfrw=True, + layout_fun=img2pdf.get_layout_fun( + pagesize=(img2pdf.mm_to_pt(A4_WIDTH_MM), img2pdf.mm_to_pt(A4_HEIGHT_MM)), + border=(settings.PDF_BORDER_SIZE,) * 4, # Same border size for all sides (top, right, bottom, left) + fit=img2pdf.FitMode.into + ) + )) # Clean up temporary files print("Cleaning up temporary files...") diff --git a/settings.py b/settings.py index a7785d4..6d40474 100644 --- a/settings.py +++ b/settings.py @@ -23,6 +23,9 @@ DEFAULT_PARALLEL_PROCESSES = max(1, multiprocessing.cpu_count() - 1) # Can be overridden by environment variable PARALLEL_PROCESSES = int(os.getenv('NOTES_CLEANER_PARALLEL_PROCESSES', DEFAULT_PARALLEL_PROCESSES)) +# Border size in pixels for the final PDF output +PDF_BORDER_SIZE = 50 + # Optimization settings OPTIPNG_OPTIMIZATION_LEVEL = int(os.getenv('NOTES_CLEANER_OPTIPNG_LEVEL', '7')) # 0-7, higher = better compression but slower TRIM_PADDING_PIXELS = int(os.getenv('NOTES_CLEANER_TRIM_PADDING', '20')) # Padding around content after trimming