如何在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 = NULLingenerate_svg()which returns the SVG content as a character string instead of writing it to a file. - Inline SVG rendering: Instead of
renderPlot(), we userenderUI()combined withHTML()to inject the SVG directly into the page. This keeps everything within your Shiny app window. - Side-by-side layout: The
fluidRowandcolumnfunctions place the input controls and QR code next to each other, just like you wanted.
Notes:
- Make sure you have the
qrcodepackage installed (install.packages("qrcode")if you haven't already). - You can adjust the
sizeparameter ingenerate_svg()to make the QR code larger or smaller as needed.
内容的提问来源于stack exchange,提问作者user18864224
相关产品推荐
相关产品推荐

