Search code examples
htmlcssscriptingmarkdownpandoc

Inline CSS with Pandoc


I apologize if a simple way to this programmatically (not by copying/pasting in a browser field and clicking a button to convert) is documented somewhere. In my searches and reading I cannot find it.

I would like to programmatically turn a Markdown and CSS file into what sounds like may be called "inline" CSS.For example:

This Markdown file (file.md)

# Install
Install instructions

## Update
Update instructions

This CSS file (style.css)

h1 {
    font-size: 100px;
}

h2 {
    color: red;
}

Becomes this (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>

I am transforming the Markdown to HTML with Pandoc

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

When I use

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

(or --standalone)

It returns

    <!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>

As mentioned above this is not my goal. I would like the CSS to be strictly "inline":

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

Is anyone aware of a tool or script already written than can programmatically achieve this? I have searched and come up empty. Ideally I could use Pandoc for this, but I cannot discover a way.

I do not care if the <head> and <style> blocks of the HTML exist or not. This HTML will be sent via cURL to a content-management system that strips out all HTML elements except the contents inside <body> and any "inline" CSS.

Thank you for any thoughts or pointing me in a direction.


Solution

  • I had a similar scenario and found premailer. Install with pip install premailer and use as python3 -m premailer -f INPUT.html -o OUT.html.

    Credit: https://qiita.com/kimagure/items/6820e2df2a7604047862