import fitz
from pathlib import Path

BASE_DIR = Path(r"u:\Dropbox\Ordinace\Dokumentace_ke_zpracování\AdobeFlattenStamp")

def flatten_pdf_rasterize(input_pdf: Path):
    print(f"Processing: {input_pdf.name}")
    doc = fitz.open(input_pdf)

    # Create a new empty PDF
    new_doc = fitz.open()

    for page in doc:
        # Render each page to a high-resolution image
        pix = page.get_pixmap(dpi=400)

        # Create a new PDF page with same size
        new_page = new_doc.new_page(width=page.rect.width, height=page.rect.height)

        # Insert the rasterized image
        new_page.insert_image(new_page.rect, pixmap=pix)

    # Save output
    output_pdf = input_pdf.with_name(input_pdf.stem + "_flatten.pdf")
    new_doc.save(output_pdf, deflate=True)
    new_doc.close()
    doc.close()

    print(f"   ✔ Saved: {output_pdf.name}")


def main():
    pdfs = list(BASE_DIR.glob("*.pdf"))
    if not pdfs:
        print("No PDF files found.")
        return

    for pdf in pdfs:
        flatten_pdf_rasterize(pdf)

    print("\nAll files processed.")


if __name__ == "__main__":
    main()
