【问题标题】:HTML-formatted hyperlinks not preserved in bookdown PDF在 bookdown PDF 中未保留 HTML 格式的超链接
【发布时间】:2018-10-23 21:49:17
【问题描述】:

我的 bookdown .Rmd 文件中有几个 html 格式的 URL,它们在生成的 PDF 中消失了。似乎链接被忽略了,PDF 只显示应该连接链接的文本。

例如,<a href="https://www.cygwin.com" target="_blank">Cygwin</a> 仅显示为 Cygwin(无超链接)。

但是当网站与显示的文本匹配时,它可以正常工作(例如:<a href="https://www.cygwin.com" target="_blank">https://www.cygwin.com</a>),大概是因为文本是链接本身。

有没有办法让 bookdown 在 PDF 输出中保留这些 html 超链接?

我正在运行以下命令在 R Studio 中生成 PDF:

    render_book("index.Rmd", "bookdown::pdf_book")

index.Rmd 的顶部是这样的:

    title: "My Title"
    site: bookdown::bookdown_site
    documentclass: book
    link-citations: yes
    output:
      bookdown::pdf_book:
        pandoc_args: [--wrap=none]
    urlcolor: blue

【问题讨论】:

    标签: r r-markdown pandoc bookdown


    【解决方案1】:

    Pandoc,在扩展 R Markdown 中,只保留链接的原始 HTML。原始 HTML 块输出为支持 HTML 的格式(如 epub),但不适用于 LaTeX(用于生成 PDF)。 Pandoc 只会解析链接的内容,这就是为什么如果您的链接文本是 URL,它似乎可以工作的原因。

    最简单的解决方案当然是对链接使用 Markdown 语法,它与 HTML 一样具有表现力:[Cygwin](https://www.cygwin.com){target="_blank"}。但是,如果这不是一个选项,那么事情就会变得有点棘手。

    这是一种仍然解析这些链接的方法。它使用 Lua filter 将原始 HTML 转换为正确的链接。只需将以下脚本作为parse-html-links.lua 保存到与您的Rmd 文件相同的目录中,并将'--lua-filter=parse-html-links.lua' 添加到您的pandoc_args 列表中。

    local elements_in_link = {}
    local link_start
    local link_end
    
    Inline = function (el)
      if el.t == 'RawInline' and el.format:match'html.*' then
        if el.text:match'<a ' then
          link_start = el.text
          return {}
        end
        if el.text:match'</a' then
          link_end = el.text
          local link = pandoc.read(link_start .. link_end, 'html').blocks[1].content[1]
          link.content = elements_in_link
          -- reset
          elements_in_link, link_start, link_end = {}, nil, nil
          return link
        end
      end
      -- collect link content
      if link_start then
        table.insert(elements_in_link, el)
        return {}
      end
      -- keep original element
      return nil
    end
    

    【讨论】:

      猜你喜欢
      • 2019-12-18
      • 2017-12-21
      • 1970-01-01
      • 1970-01-01
      • 2013-03-08
      • 1970-01-01
      • 1970-01-01
      • 2015-04-12
      • 2021-05-12
      相关资源
      最近更新 更多