Rúnar Berg
Rúnar Berg

Reputation: 4842

knitr, pandoc: embeding SVG directly to HTML document

I am using knitr to generate reports automatically to a mediawiki page. The report output is in HTML via pandoc. But I am having problems uploading the figures to the wiki site. So I figured that I would use the SVG device and include the code in the final document instead of relying on external documents. However I am having trouble doing that with either knitr or pandoc. Does anybody know about a pandoc or a knitr option that creates the SVG embedded instead of linking to the image? Or even a small shell script that replaces <img src="myFigure.svg"> with the contents of myFigure.svg.

Upvotes: 4

Views: 1425

Answers (1)

R&#250;nar Berg
R&#250;nar Berg

Reputation: 4842

I ended up using a simple python script for the job

from sys import argv
import re
import os

def svgreplace(match):
    "replace match with the content of a filename match"
    filename = match.group(1)
    with open(filename) as f:
        return f.read()

def svgfy(string):
    img = re.compile(r'<img src="([^"]*\.svg)"[^>]*>')
    return img.sub(svgreplace, string)

if __name__ == "__main__":
    fname = argv[1]
    with open(fname) as f:
        html = f.read()
        out_fname = fname + ".tmp"
        out = open(out_fname, 'w')
        out.write(svgfy(html))
        out.close()
        os.rename(out_fname, fname)

Upvotes: 1

Related Questions