Last active
September 12, 2024 07:57
-
-
Save jayvynl/68db88460b4e8adcad0e32bb8adc2664 to your computer and use it in GitHub Desktop.
pywin32 capture thumbnail of first page of docx document
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os.path | |
import time | |
from PIL import ImageGrab | |
from win32com.client import constants | |
import win32com.client as win32 | |
def create_docx_thumbnail(docx_file, output_image): | |
# Launch the Word application | |
word = win32.Dispatch("Word.Application") | |
# Hide the Word application interface (run in background) | |
word.Visible = False | |
# Open the specified Word document | |
doc = word.Documents.Open(os.path.abspath(docx_file)) | |
selection = doc.ActiveWindow.Selection | |
# Navigate to the first page of the document | |
selection.GoTo(constants.wdGoToPage, constants.wdGoToAbsolute, 1) | |
# Select the content of the first page | |
selection.WholeStory() | |
# Capture the content of the Word window and save it as an image | |
selection.CopyAsPicture() | |
# Or paste to a new document | |
# new_doc = word.Documents.Add() | |
# new_doc.Activate() | |
# selection = word.Selection | |
# Paste the first page content as an image | |
selection.PasteSpecial(DataType=constants.wdPasteMetafilePicture) | |
selection.Copy() | |
# Add a short delay to ensure the copy operation is complete. | |
time.sleep(1) | |
# Close the document and the Word application | |
doc.Close(SaveChanges=0) | |
word.Quit() | |
# Save image file from clipboard | |
win32clipboard.OpenClipboard() | |
try: | |
if win32clipboard.IsClipboardFormatAvailable(win32clipboard.CF_DIB): | |
data = win32clipboard.GetClipboardData(win32clipboard.CF_DIB) | |
image = BmpImagePlugin.DibImageFile(BytesIO(data)) | |
image.save(output_image, format="PNG") | |
return True | |
finally: | |
win32clipboard.CloseClipboard() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment