require 'asciidoctor' require 'asciidoctor-pdf' require 'securerandom' class SnippetToImageFilter < Asciidoctor::Extensions::Preprocessor def process(document, reader) new_lines = [] image_id = nil capture = false html_content = "" reader.lines.each do |line| if line.strip == "" capture = true image_id = SecureRandom.hex(10) next elsif line.strip == "" && capture output_path = "generated_images/#{image_id}.png" `node saveAsImage.js "#{html_content}" "#{output_path}"` new_lines << "image::#{output_path}[Generated Image, scaledwidth=75%]" capture = false html_content = "" next elsif capture html_content += line else new_lines << line end end # Ensure all lines are added if the document doesn't end properly if capture new_lines.concat(html_content.split("\n")) end Asciidoctor::PreprocessorReader.new(document, new_lines) end end Asciidoctor::Extensions.register do preprocessor SnippetToImageFilter end