#!/usr/bin/env python3 # scan.py (AHG, 2023), output directory in line 24 import os,sane from subprocess import run from string import ascii_letters from time import strftime from pypdf import PdfReader, PdfWriter # my_name = "Gitter" san = sane.init() if not sane.get_devices(): print("\nScan Program",__file__) print("ERROR: no scanner found",\ "(use USB 3 or an active USB hub)\n") sane.exit() ; os._exit(1) else: print("\nScan Program",__file__+\ ", scanner:",sane.get_devices()[0][2]) # dev = sane.open(sane.get_devices()[0][0]) wh = dev.get_parameters()[2] print("width x height (pixels):",str(wh[0]),"x",\ str(wh[1])+",","output file format: PDF") dir = os.getenv("HOME")+"/docum/scan/" # directory if os.path.isdir(dir)==False: print("ERROR: missing directory", dir,"\n") sane.exit() ; os._exit(1) # print("\nName your file without extension .pdf,") dat = input("output file (ENTER for default): ") dat = dat.strip().replace(" ","_") # remove spaces if dat: # string not empty -> check file name if dat[0] not in ascii_letters: print("ERROR: must start with letter\n") sane.exit() ; os._exit(1) dat=dir+dat+".pdf" # path to output file if os.path.exists(dat)==True: print("ERROR: cannot overwrite file\n") sane.exit() ; os._exit(1) else: # string is empty -> use the default name dat = dir+"scan"+strftime("%y%m%d%H%M%S.pdf") # tit = input("Title of PDF (ENTER for default): ") tit = tit.strip().replace(" ","_") # remove spaces if not tit: # string is empty -> use the default name tit = my_name+"_scan_"+strftime("%y%m%d") # # now we scan, save in PDF file and show result: dev.start() ; img = dev.snap() ; img.save(dat) dev.close() ; sane.exit() rdr = PdfReader(dat) ; wrt =PdfWriter() for p in rdr.pages: wrt.add_page(p) wrt.add_metadata(rdr.metadata) wrt.add_metadata({"/Title":tit}) with open(dat,"wb") as f: wrt.write(f) try: run(["fbgs",dat]) # we need fbgs to show PDF except: print("WARNING: cannot show output file\n") print("\nEnd of scanning, output file:",dat,"\n")