HTML-格式的超链接未保留在 bookdown PDF 中

HTML-formatted hyperlinks not preserved in bookdown PDF

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

例如,<a href="https://www.cygwin.com" target="_blank">Cygwin</a> 只是显示为 Cygwin(没有 hyperlink)。

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

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

我是 运行 在 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

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

它似乎有效的原因

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

这里有一个方法仍然可以解析那些 link。它使用 Lua filter 将原始 HTML 转换为正确的 link。只需将以下脚本作为 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