You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Shiny应用页面的输入框旁直接展示生成的二维码SVG图像

Fix: Display QR Code Directly in Shiny App (No File Save, No New Window)

I get exactly what you're aiming for—you want the QR code to show right next to your input box without saving a file or having Edge pop open a new window. The issue with your original code is that renderPlot() isn't the right tool here (since the qr_code object isn't a standard R plot), and saving to an SVG file triggers that unwanted browser behavior.

Here's a clean solution that generates the QR code as an inline SVG and renders it directly in your Shiny app:

Full Working Example

library(shiny)
library(qrcode)

ui <- fluidPage(
  titlePanel("QR Code Generator"),
  fluidRow(
    column(4,
           textInput("qr_gen", "Enter text to encode:", placeholder = "Type here..."),
           actionButton("safe_qr", "Generate QR Code")
    ),
    column(4,
           # This is where the QR code will appear
           uiOutput("qr_display")
    )
  )
)

server <- function(input, output) {
  observeEvent(input$safe_qr, {
    req(input$qr_gen) # Make sure input isn't empty
    
    # Generate QR code data
    qr <- qr_code(input$qr_gen)
    
    # Generate SVG as a string (no file saved!)
    qr_svg <- generate_svg(qr, file = NULL, size = 100, 
                           foreground = "black", background = "white")
    
    # Render the SVG directly in the app
    output$qr_display <- renderUI({
      HTML(qr_svg)
    })
  })
}

shinyApp(ui, server)

Key Changes Explained:

  • No file saving: We use file = NULL in generate_svg() which returns the SVG content as a character string instead of writing it to a file.
  • Inline SVG rendering: Instead of renderPlot(), we use renderUI() combined with HTML() to inject the SVG directly into the page. This keeps everything within your Shiny app window.
  • Side-by-side layout: The fluidRow and column functions place the input controls and QR code next to each other, just like you wanted.

Notes:

  • Make sure you have the qrcode package installed (install.packages("qrcode") if you haven't already).
  • You can adjust the size parameter in generate_svg() to make the QR code larger or smaller as needed.

内容的提问来源于stack exchange,提问作者user18864224

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.27 21:54:06