Skip to content
Advertisement

Is there a way to convert HTML div to a video format (MP4 or any other) in Python/Django?

I am trying to render a HTML page and use a specific <div> inside it to convert it to video format.

Explanation:

I know HTML is static content but it is necessary for me to convert it to a video format (it is a requirement). I need to know if there is a way which can render a page and export it to a video format. It can either be a direct HTML to MP4 conversion or capture rendered div (Not record canvas) as an Image and then convert that image to the video format.

Technology Stack:
Django
Django templates
HTML
Javascript

Any help would be appreciated.

Advertisement

Answer

here is a rough procedure how to do that: (be careful I just copied the “idea” from my code an removed my specific stuff, so there might be typos or small inconsistencies)

import imgkit
from moviepy import editor

# Step 1: render html to PNG

context = { ....}
rendered_html = Render_to_string('path/template.html', context)


# make sure that 'width' is set otherwise it will use a min width that maybe does not fit to your html
options = {'format': 'png', 'width': 670, 'disable-smart-width': ''}
imgkit.from_string(rendered_html,'path/tmp.png',
                       config=config, options=options)

# Step 2: create video from png and mp3
audio = editor.AudioFileClip('path/audio.mp3')
video = editor.ImageClip('path/tmp.png')
video.fps = 1
video.duration = audio.duration
final_video = video.set_audio(audio)
final_video.write_videofile('path/video.mp4', fps=1)
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement