Skip to content

Instantly share code, notes, and snippets.

@DiKorsch
Last active August 16, 2022 12:09
Show Gist options
  • Save DiKorsch/da624dc483d1747744651580a5b4990c to your computer and use it in GitHub Desktop.
Save DiKorsch/da624dc483d1747744651580a5b4990c to your computer and use it in GitHub Desktop.
Scan files under Windows and save them under filename present in the clipboard
"""
- python2.7 32bit installieren (https://www.python.org/ftp/python/2.7.12/python-2.7.12.msi)
- C:\python\pip install pyperclip twain pillow
- C:\python\python.exe run.py
"""
import pyperclip, twain, os
from os.path import isdir, isfile, dirname, abspath
from PIL import Image
FORMAT = "pdf"
SCANNER = "CHANGE ME!"
DUPLEX = True
fpath = pyperclip.paste()
if not isdir(dirname(abspath(fpath))):
print("Folder \"{}\" does not exist!".format(dirname(abspath(fpath))))
exit()
if isfile(fpath):
print("File \"{}\" already exists!".format(fpath))
exit()
sm = twain.SourceManager(0)
try:
ss = sm.OpenSource(SCANNER)
except twain.excDSOpenFailed as e:
ss = sm.OpenSource()
print("Scanner name: {}".format(ss.GetSourceName()))
if DUPLEX:
ss.SetCapability( twain.CAP_DUPLEXENABLED, twain.TWTY_BOOL, True )
ss.RequestAcquire(0,0)
print("Scanning...")
tmp_bmp, _ = ss.GetXferFileName()
ss.XferImageByFile()
print("Converting to '{}'".format(FORMAT))
Image.open(tmp_bmp).save(fpath, FORMAT)
os.remove(tmp_bmp)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment