Skip to content
Advertisement

How do I convert Python scripts files to images files representing the code with highlighting?

In short, how do I get this:

enter image description here

From this:

def fiblike(ls, n):         
    store = []              
    for i in range(n):      
        a = ls.pop(0)       
        ls.append(sum(ls)+a)
        store.append(a)     
    return store 

With all the indentation guide and code highlighting.

I have written hundreds of Python scripts and I need to convert all of them to images…

I have seen this:

import Image
import ImageDraw
import ImageFont

def getSize(txt, font):
    testImg = Image.new('RGB', (1, 1))
    testDraw = ImageDraw.Draw(testImg)
    return testDraw.textsize(txt, font)

if __name__ == '__main__':

    fontname = "Arial.ttf"
    fontsize = 11   
    text = "example@gmail.com"
    
    colorText = "black"
    colorOutline = "red"
    colorBackground = "white"


    font = ImageFont.truetype(fontname, fontsize)
    width, height = getSize(text, font)
    img = Image.new('RGB', (width+4, height+4), colorBackground)
    d = ImageDraw.Draw(img)
    d.text((2, height/2), text, fill=colorText, font=font)
    d.rectangle((0, 0, width+3, height+3), outline=colorOutline)
    
    img.save("D:/image.png")

from here

But it does not do code highlighting and I want either a numpy or cv2 based solution.

How can I do it?

Advertisement

Answer

You can use pygments library to convert to HTML with highlighting and then convert the HTML to an image.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement