Markdown 作为一种轻量级标记语言,特别适合平时随手写一些文档使用,但是通常来说,渲染器会将 Markdown 文件渲染为 HTML 文件,而我有时候需要使用 PDF 文件(相对而言更加利于阅读)。最简单的方法显然是将生成的 HTML 直接打印为 PDF 文档,但是这样的话会出现一些格式紊乱以及链接丢失的问题。
经过简单的搜索我找到了一种使用 pandoc + xelatex 进行转换的方案,以此可以相对优雅的得到规整的 PDF 文档。
以下是简单介绍:
Contents
工具:
sublimetext 3, SumatraPDF(快速预览), pandoc, xelatex.
安装工具:
- sublime 直接下载安装即可,未注册不直接影响功能。
- SumatraPDF 也是直接下载安装。没有太多讲究。
- pandoc 下载并安装,注意:需要将 pandoc 的路径加入系统环境变量 path 中。
- Latex 系统推荐使用 MiKTex 或者 TeX Live。这两个系统在安装后通常会自动写入环境变量,如果没有检测到,请自行写入。
以上工具安装完成后即可进行工具链配置。
配置工具链:
打开 %appdata%\Sublime Text 3\Packages\User,为工具链创建一个设定:例如 Markdown2PDF.sublime-build 并且写入以下内容,注意修改用户名:
{
"shell_cmd": "pandoc -f markdown+tex_math_dollars --pdf-engine=xelatex -N --highlight-style=tango --mathjax -H \"${packages}\"/User/head.tex -V colorlinks \"${file}\" -o \"${file_path}/${file_base_name}.pdf\" ",
"path": "C:/Users/demo/AppData/Local/Pandoc/;%PATH%",
"file_regex": "^(..[^:]*):([0-9]+):?([0-9]+)?:? (.*)$",
"working_dir": "${file_path}",
"selector": "text.html.markdown",
"variants":
[
{
"name": "Build and View",
"shell_cmd": "pandoc -f markdown+tex_math_dollars --pdf-engine=xelatex -N --highlight-style=tango --mathjax -H \"${packages}\"/User/head.tex -V colorlinks \"${file}\" -o \"${file_path}/${file_base_name}.pdf\" && SumatraPDF \"${file_path}/${file_base_name}.pdf\" ",
// "shell_cmd": "start \"$file_base_name\" call $file_base_name"
}
]
}
再写入如下头文件 head.tex,保存在同一文件夹:
\usepackage{fancyvrb,newverbs}
\usepackage{xeCJK}
\usepackage{siunitx}
\usepackage{amsmath}
% set up page geometry
\usepackage[top=2cm, bottom=1.5cm, left=1.5cm, right=1.5cm]{geometry}
% change background color for inline code in
% markdown files. The following code does not work well for
% long text as the text will exceed the page boundary
\definecolor{bgcolor}{HTML}{e6e6e6}
\let\oldtexttt\texttt
\renewcommand{\texttt}[1]{
\colorbox{bgcolor}{\oldtexttt{#1}}
}
%% color and other settings for the hyperref package
\hypersetup{
bookmarksopen=true,
linkcolor=blue,
filecolor=magenta,
urlcolor=NavyBlue,
}
\setlength{\tabcolsep}{12pt}
\renewcommand{\arraystretch}{1.5}
%% Set fonts
%\setmainfont{Source Han Sans}
%\setsansfont{Source Han Sans}
%\setmonofont{Sarasa Mono SC}
%\setCJKmainfont{Source Han Sans CN}
%\setCJKsansfont{Source Han Sans CN}
%\setCJKmonofont{Sarasa Mono SC}
此时简单的配置已经完成。
Tips:
- 此配置已支持 Math 公式解析,使用符号 $,详见 pandoc 文档或者 latex 文档
- latex 命令亦可在这里使用,例如 \clearpage 等
- 通过对 head.tex 文件的修改,可以很方便的控制字体,页边距,纸张大小等参数