首页 > 解决方案 > 使用 Pandoc 内联 CSS

问题描述

如果在某处记录了一种以编程方式实现此目的的简单方法(而不是通过在浏览器字段中复制/粘贴并单击按钮进行转换),我深表歉意。在我的搜索和阅读中我找不到它。

我想以编程方式将 Markdown 和 CSS 文件转换为听起来可能被称为“内联”CSS 的内容。例如:

这个 Markdown 文件 ( file.md)

# Install
Install instructions

## Update
Update instructions

这个 CSS 文件 ( style.css)

h1 {
    font-size: 100px;
}

h2 {
    color: red;
}

变成这个 ( file.html)

<h1 style="font-size: 100px;"><a id="install"></a>Install</h1>
<p>Install instructions</p>
<h2 style="color: red;"><a id="update"><a>Update</h2>
<p>Update instructions</p>

我正在使用Pandoc将 Markdown 转换为 HTML

pandoc -f markdown -t html file.md -o file.html

当我使用

pandoc -f markdown -t html file.md -o file.html --css=style.css --self-contained

(或--standalone

它返回

    <!DOCTYPE html>
    <html xmlns="http://www.w3.org/1999/xhtml" lang xml:lang>
    <head>
      <meta charset="utf-8" />
      <meta name="generator" content="pandoc" />
      <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=yes" />
      <title>file</title>
      <style type="text/css">
          code{white-space: pre-wrap;}
          span.smallcaps{font-variant: small-caps;}
          span.underline{text-decoration: underline;}
          div.column{display: inline-block; vertical-align: top; width: 50%;}
      </style>
      <style type="text/css">h1 {font-size: 100px;}h2 {color: red;}</style>
      <!--[if lt IE 9]>
        <script src="//cdnjs.cloudflare.com/ajax/libs/html5shiv/3.7.3/html5shiv-printshiv.min.js"></script>
      <![endif]-->
    </head>
    <body>
      <h1><a id="install"></a>Install</h1>
      <p>Install instructions</p>
      <h2><a id="update"><a>Update</h2>
      <p>Update instructions</p>
    </body>
    </html>

如上所述,这不是我的目标。我希望 CSS 严格“内联”:

<h1 style="font-size: 100px;"><a id="install"></a>Install</h1>

是否有人知道已经编写的工具或脚本不能以编程方式实现这一点?我已经搜索并空了。理想情况下,我可以为此使用 Pandoc,但我找不到方法。

我不在乎 HTML 的<head>and<style>块是否存在。此 HTML 将通过 cURL 发送到内容管理系统,该系统会去除除内部内容<body>和任何“内联”CSS 之外的所有 HTML 元素。

感谢您的任何想法或为我指明方向。

标签: htmlcssscriptingmarkdownpandoc

解决方案


对于大多数人来说,比-H使用以下--self-contained选项更好的选择:

生成一个没有外部依赖的独立 HTML 文件,使用 data: URI 来合并链接脚本、样式表、图像和视频的内容。

然后你可以这样做:

pandoc -f markdown -t html file.md -o file.html --self-contained --css=github-pandoc.css

这样,您不需要创建.css带有样式标签的特殊文件。请注意,这不再-s是必要的(尽管它没有伤害)。--self-contained-s

请注意,这将尝试包含显示页面所需的任何其他资产(如有必要,请从网络下载它们!) - 请查看 pandoc 文档以--self-contained获取详细信息。


推荐阅读