Search code examples
pythonscreenshot

Capturing a screenshot and saving to a document with a Python background script


I’m doing some testing activity which requires me to capture a screenshot of applications, database systems, 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 a Windows shortcut key (for example, Ctrl + Alt + Shift + C) and it appends the image to a document file?

I believe the Python program should be running in the background, like nohup in Unix.


Solution

  • 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" # The main document
    hotkey = 'ctrl+shift+q'  # Use this combination anytime while the 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 a screenshot, active app
            # shot = pyautogui.screenshot() # Take a screenshot full screen
            shot.save(shotfile) # Save the screenshot
    
            # Append to the document. Doc must exist.
            doc = Document(docxfile) # Open the document
            doc.add_picture(shotfile, width=Inches(7))  # Add the image, 7 inches wide
            doc.save(docxfile)  # Update the document
            print ('Done capture.')
        except Exception as e:  # Allow the 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