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

Bookdown生成PDF时stringr::str_view报错的原因及输出需求

Fixing the stringr::str_view Error in Bookdown PDF Output

Hey there! Let's break down why you're hitting that error and how to get your PDF with syntax-highlighted code sorted out smoothly.

Why the Error Pops Up

The stringr::str_view() function is built to generate interactive HTML output—it shows you which parts of a string match your regex pattern in a browser-friendly way. But when you're building a PDF (which uses LaTeX under the hood), Bookdown/R Markdown blocks HTML content by default. That's because PDFs can't render interactive HTML elements, so the tool is warning you that this function's output won't work in your target format. Your hunch that the function is being "unnecessarily executed" is totally right—you don't need it to run if you just want to display the code itself!

Solution 1: Show Code Without Running It (Best for Your Use Case)

If your goal is to include the syntax-highlighted code in your PDF without executing it (and thus avoiding the HTML output entirely), add the eval=FALSE parameter to your code chunk. This tells Bookdown to render the code as formatted, highlighted text instead of running it.

Here's how your code block should look:

# Add eval=FALSE to skip execution and keep syntax highlighting
stringr::str_view(c("alice", "bob"), "o")

This will keep the code's syntax highlighting intact, avoid the error, and give you exactly what you need: clean, highlighted code in your PDF.

Solution 2: Allow HTML (If You Need to Run the Function)

If for some reason you do need to run str_view() (even though its output won't be visible in the PDF), you can follow the error message's suggestion and add the always_allow_html: yes setting to your document's YAML front-matter. Here's an example:

---
title: "Your Bookdown Project"
output:
  bookdown::pdf_book:
    toc: true
always_allow_html: yes
---

Just a heads-up: the interactive HTML output from str_view() won't show up in your PDF—this option just stops the error from appearing. For your specific need (showcasing code with syntax highlighting in PDF), Solution 1 is definitely the better choice.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 07:21:06