如何通过命令行将Viewer Pane保存为图像?

Col*_*FAY 22 r rstudio

假设我在查看器窗格中查看了以下HTML

tempDir <- tempfile()
dir.create(tempDir)
htmlFile <- file.path(tempDir, "index.html")
write('<h1> Content</h1>', htmlFile, append = TRUE)
write('<h2> Content</h2>', htmlFile, append = TRUE)
write('lorem ipsum...', htmlFile, append = TRUE)
viewer <- getOption("viewer")
viewer(htmlFile)
Run Code Online (Sandbox Code Playgroud)

当我在查看器窗格中有这个html时,我可以点击"另存为图像"按钮:

在此输入图像描述

我将html内容作为png,例如:

在此输入图像描述

有没有办法用命令行执行此操作?我知道rstudioapi::savePlotAsImage(),所以我正在寻找一种saveViewerAsImage.

编辑:我知道我们可以使用{webshot}包来做到这一点,但我正在寻找能够做到这一点的RStudio函数.

RLe*_*sur 15

这是一个提案.策略如下:

  1. 让观众建立 png
  2. png从观众发送给R

让观众建立 png

canvas图像拥有.toDataURL()方法返回包含在该图像的表示的数据URI png格式(我们还可以得到一个jpeg格式).

html2canvas可用于截取屏幕截图:此库将当前页面呈现为canvas图像.

因此,可以在查看器中组合这两个函数:

  • 截取屏幕截图 html2canvas
  • 将此屏幕截图转换为png使用.toDataURL()

但是,该html2canvas库使用Promise(Windows版本)RStudio查看器不支持的JavaScript :需要填充填充.

png观众发送给R

可以使用WebSockets实现此任务.

httpuv包可用于创建Web服务器.此服务器将提供HTML将在RStudio查看器中打开的页面.

httpuv服务器和RStudio查看器之间建立WebSocket通信.

从R命令行,可以向RStudio查看器发送WebSocket消息:接收此消息,查看器获取屏幕截图并将其发送回服务器.

代码

对不起,这段代码很长时间才能得到答案.

library(httpuv)

# Initialize variables
png <- NULL
websocket <- NULL

# Download Javascript libraries
polyfill_promise <- readLines('https://cdn.jsdelivr.net/npm/es6-promise/dist/es6-promise.auto.min.js')
html2canvas <- readLines('https://html2canvas.hertzen.com/dist/html2canvas.min.js')

# Configure the httpuv server
app <- list(
  call = function(req) {
    list(
      status = 200L,
      headers = list(
        'Content-Type' = 'text/html'
      ),
      body = paste0(collapse = "\r\n",
                    c("<!DOCTYPE html>",
                      "<html>",
                      "<head>",
                      # polyfill the RStudio viewer to support JavaScript promises
                      '<script type="text/javascript">',
                      polyfill_promise,
                      "</script>",
                      # use html2canvas library
                      '<script type="text/javascript">',
                      html2canvas,
                      "</script>",
                      "</head>",
                      "<body>",
                      html_body,
                      "</body>",
                      '<script type="text/javascript">',
                      # Configure the client-side websocket connection:
                      'var ws = new WebSocket("ws://" + location.host);',
                      # When a websocket message is received:
                      "ws.onmessage = function(event) {",
                      # Take a screenshot of the HTML body element
                      "  html2canvas(document.body).then(function(canvas) {",
                      # Transform it to png
                      "    var dataURL = canvas.toDataURL();",
                      # Send it back to the server
                      "    ws.send(dataURL);",
                      "  });",
                      "};",
                      "</script>",
                      "</html>"
                    )
      )
    )
  },
  # Configure the server-side websocket connection
  onWSOpen = function(ws) {
    # because we need to send websocket message from the R command line:
    websocket <<- ws
    # when a websocket message is received from the client
    ws$onMessage(function(binary, message) {
      png <<- message
    })
  }
)

# From your question:
html_body <- c(
  '<h1> Content</h1>', 
  '<h2> Content</h2>', 
  'lorem ipsum...'
)

# Start the server:
server <- startDaemonizedServer("0.0.0.0", 9454, app)

# Open the RStudio viewer:
rstudioapi::viewer("http://localhost:9454")
# Wait to see the result...

# Send a websocket message from the command line:
websocket$send("go") # send any message

# Write the png image to disk:
writeBin(
  RCurl::base64Decode(
    gsub("data:image/png;base64,", "", png), 
    "raw"
  ), 
  "screenshot.png"
)

# Close the websocket connection
websocket$close()

# Stop the server
stopDaemonizedServer(server)
Run Code Online (Sandbox Code Playgroud)

  • 我觉得`wsUrl` 可能是`location.host`? (2认同)
  • @YihuiXie 好收获!由于这简化了答案,我已经更新了它。谢谢夸奖和赏金! (2认同)