I am trying to save an .svg that I generate inside a shiny app using htmltools (MRE below). This requires adding the svg namespace to the svg tag with xmlns:xlink="http://www.w3.org/1999/xlink". It renders fine inside the app, but when I open the generated file in a browser I get this error:
This XML file does not appear to have any style information associated with it. The document tree is shown below.
Looking in a text editor the code looks fine:
<svg xlmns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" viewbox="0 0 100 100" height="100%">
In Firefox, xmlns:xlink is missing completely from what's presented in the tree:
<svg xlmns="http://www.w3.org/2000/svg" version="1.1" viewbox="0 0 100 100" height="100%">
In Chromium, the xmlns:xlink is presented before xlmns:
<svg xmlns:xlink="http://www.w3.org/1999/xlink" xlmns="http://www.w3.org/2000/svg" version="1.1" viewbox="0 0 100 100" height="100%">
I've edited the text file and typed the exact same line and then it renders correctly! I suspect it is something to do with the encoding of the : character. I've also tried using gsub() to add the xmlns:xlink inside the downloadHandler() rather than in the tags$svg but have the same error.
library(shiny)
library(htmltools)
ui <- fluidPage(
sidebarPanel(
downloadButton("download")
),
mainPanel(
uiOutput("svgout")
)
)
server <- function(input, output, session){
svg_pattern <- reactive({
tagList(tags$svg(xlmns = "http://www.w3.org/2000/svg",
`xmlns:xlink` = "http://www.w3.org/1999/xlink",
version="1.1",
viewbox = "0 0 100 100",
height = "100%",
tags$circle(cx = 50,
cy = 50,
r = 10,
`stroke-width` = 1,
stroke = "black")),
)
})
output$svgout <- renderUI({
svg_pattern()
})
output$download <- downloadHandler(
filename = function(){
"your.svg"
},
content = function(file){
write(as.character(svg_pattern()), file)
}
)
}
shinyApp(ui, server)
I tried with Edge and it works without the
xmlns:xlink, but this isviewBoxand notviewbox:In fact, even without the
xmlnsyou can visualize the file with a viewer such as Image Glass on Windows, but in a browser you'll only see the XML code.