我想在pdf文件中添加一个情节图。这应该在本地完成(没有plotly_IMAGE)。不幸的是我没有访问webshot(因为我没有安装PhantomJS的权利)。因此,我尝试了一种解决方法:https://github.com/ropensci/plotly/issues/311使用闪亮的小工具。但是我想对它进行调整,以便在没有点击小工具的情况下进行复制。
我的所有尝试(见下文)都失败了,因为在复制完成之前我无法延迟downloadHandler。
任何建议如何删除结果(复制情节 - 图像首先是png并在之后的pdf-Export中使用它)都是在点击下载按钮后按顺序完成的?
UI:
library(shiny)
library(plotly)
library(rsvg)
shinyUI(fluidPage(
title = 'Download a PDF report',
sidebarLayout(
sidebarPanel(
helpText(),
selectInput('x', 'Build a regression model of mpg against:',
choices = names(mtcars)[-1]),
radioButtons('format', 'Document format', c('PDF', 'HTML', 'Word'),
inline = TRUE),
downloadButton('downloadReport'),
tags$script('
document.getElementById("downloadReport").onclick = function() {
var plotly_svg = Plotly.Snapshot.toSVG(
document.querySelectorAll(".plotly")[0]
);
Shiny.onInputChange("plotly_svg", plotly_svg);
};
')
),
mainPanel(
plotlyOutput('regPlot')
)
)
))
服务器:
library(shiny)
library(plotly)
library(rsvg)
shinyServer(function(input, output, session) {
output$regPlot <- renderPlotly({
library(plotly)
set.seed(100)
d <- diamonds[sample(nrow(diamonds), 1000), ]
print("render")
p <- plot_ly(d, x = carat, y = price, text = paste("Clarity: ", clarity),
mode = "markers", color = carat, size = carat)
p
})
observeEvent(input$plotly_svg, priority = 10, {
png_gadget <- tempfile(fileext = ".png")
png_gadget <- "out.png"
print(png_gadget)
rsvg_png(charToRaw(input$plotly_svg), png_gadget)
})
output$downloadReport <- downloadHandler(
filename = function() {
paste('my-report', sep = '.', switch(
input$format, PDF = 'pdf', HTML = 'html', Word = 'docx'
))
},
content = function(file) {
src <- normalizePath('testreport.Rmd')
# temporarily switch to the temp dir, in case you do not have write
# permission to the current working directory
owd <- setwd(tempdir())
on.exit(setwd(owd))
file.copy(src, 'testreport.Rmd')
library(rmarkdown)
out <- render('testreport.Rmd', params = list(region = "Test"), switch(
input$format,
PDF = pdf_document(), HTML = html_document(), Word = word_document()
))
file.rename(out, file)
}
)
})