Search code examples
pythonclipboarddocxtypographypyperclip

Is there a way to format the clipboard with italics through python?


I'm looking to automate the formatting of sources in a Microsoft word document(.docx). The problem is that some of the text in the new format has to be in italics. Is there a way in python to format text in italics to the clipboard? If you manually(ctrl + c) copy italics, the italic part of the string is still kept in the clipboard. Because when you paste it out(ctrl + v) it's still in italics. This is why I\m wondering if it\s possible in python.

I've already looked at pyperclip, but they only provide information on how to copy plain strings. (https://pyperclip.readthedocs.io/en/latest/introduction.html).


Solution

  • It is possible with klembord.

    Installation

    pip install klembord
    

    Code to set italic text to clipboard

    import klembord
    klembord.init()
    
    # Set HTML formatted clipboard
    klembord.set_with_rich_text('', 'Normal text, <i>Italic text</i>')
    

    Short explanation

    The set_with_rich_text() takes two arguments. The first argument is what is set to the "plain text" clipboard, which is then used if user pastes for example to Notepad. The second argument is the "HTML formatted clipboard", which is uses if user pastes to a rich text editor, such as Word.

    Output when pasted to Word

    example output