'Capturing Screenshot and saving to a Document with Python background script

I’m doing some testing activity which requires me to capture screenshot of applications/DB etc and save it to a document. The whole activity has more than 50 screenshots. Is there a way in Python through which I can take a screenshot with windows shortcut key( eg; CTRL ALT shift C) and it appends the image to a document file. I believe the python program should be running in background like nohup in Unix.



Solution 1:[1]

For storing screen captures in Word using a hotkey, you can use a combination of libraries.

  • Use win32gui to open Word
  • Use python-docx to update the document and save
  • Use PyAutoGUI to do the screen capture
  • Use keyboard to listen for the hotkey

For this script to work, you will need to create the Word document before running the script.

# Need these libraries
# pip install keyboard
# pip install PyAutoGUI
# pip install python-docx
# pip install win32gui

import keyboard
import pyautogui
from docx import Document
from docx.shared import Inches
import win32gui
from PIL import ImageGrab

shotfile = "C:/tmp/shot.png"  # temporary image storage 
docxfile = "C:/tmp/shots.docx" # main document
hotkey = 'ctrl+shift+q'  # use this combination anytime while script is running

def do_cap():
    try:
        print ('Storing capture...')
        
        hwnd = win32gui.GetForegroundWindow()  # active window
        bbox = win32gui.GetWindowRect(hwnd)  # bounding rectangle

        # capture screen
        shot = pyautogui.screenshot(region=bbox) # take screenshot, active app
        # shot = pyautogui.screenshot() # take screenshot full screen
        shot.save(shotfile) # save screenshot
        
        # append to document. Doc must exist.
        doc = Document(docxfile) # open document
        doc.add_picture(shotfile, width=Inches(7))  # add image, 7 inches wide
        doc.save(docxfile)  # update document
        print ('Done capture.')
    except Exception as e:  # allow program to keep running
        print("Capture Error:", e)

keyboard.add_hotkey(hotkey, do_cap)  # set hot keys

print("Started. Waiting for", hotkey)

keyboard.wait()   # Block forever

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1