1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108
| import os import re
def escape_latex_chars(text): """ Escape LaTeX special characters in the text. """ text = text.replace('%', '\\%') return text
def md_to_latex_box(md_content): """ Convert markdown content to LaTeX box content. """ box_content = re.sub(r'^(## .+)$', r'\\end{mybox}\n\n\\begin{mybox}{\g<1>}', md_content, flags=re.MULTILINE) box_content = re.sub(r'\\begin{mybox}{## (.+)}', r'\\begin{mybox}{\1}', box_content) box_content = re.sub(r'^(?!\\begin{mybox}|\\end{itemize})(.+)$', lambda match: ' ' + escape_latex_chars(match.group(0)), box_content, flags=re.MULTILINE) if '\\begin{mybox}' in box_content: box_content += r'\end{mybox}' + '\n' return box_content
def md_to_latex_section(md_content): md_content = re.sub(r'^(# .+)$', r'\\end{mybox}\n\n\\section*{\g<1>}', md_content, flags=re.MULTILINE) md_content = re.sub(r'\\section\*{# (.+)}', r'\\section*{\1}', md_content) md_content = escape_latex_chars(md_content) return md_content
def convert_md_file_to_latex(md_file_path, latex_file_path): with open(md_file_path, 'r', encoding='utf-8') as md_file: md_content = md_file.read()
latex_content = md_to_latex_section(md_content) latex_content = md_to_latex_box(latex_content)
preamble = r'''\documentclass{article} \usepackage{amsmath} \usepackage{multicol} % 用于多列布局 \usepackage[most]{tcolorbox} % 引入 tcolorbox 的 most 库以获得额外功能
\usepackage[ a4paper, top=0mm, bottom=0mm, left=0mm, marginparwidth=0mm, marginparsep=0mm, centering, includefoot]{geometry}
% 设置 section 的样式 \usepackage{titlesec} \titleformat{\section} {\normalfont\large\bfseries\centering}{\thesection}{1em}{} \titlespacing{\section}{0pt}{*1.5}{*1.5} % 创建一个自定义的 box \newtcolorbox{mybox}[2][]{ colback=white, % 盒子背景颜色 colframe=black, % 盒子边框颜色 coltitle=black, % 标题文本颜色 boxsep=1px, % 内部与边框的空间 top=1px, % 盒子顶部的空间 bottom=1px, % 盒子底部的空间 left=1px, % 盒子左边的空间 right=1px, % 盒子右边的空间 boxrule=0.5pt, % 边框宽度 sharp corners, % 设置为直角边框 fonttitle=\bfseries\scriptsize, % 标题字体加粗和大小 title={#2}, % 标题文本 attach title to upper, % 将标题文本放在盒子上方的内容顶部 % before=\vspace{-0.2px}, % 减小盒子前的垂直间距 after=\vspace{-8pt}, % 减小盒子后的垂直间距 #1 }
\begin{document} \begin{multicols*}{2} % 创建一个三列的布局 '''
ending = r''' \end{multicols*} \end{document} '''
full_latex_content = preamble + latex_content + ending
with open(latex_file_path, 'w', encoding='utf-8') as latex_file: latex_file.write(full_latex_content)
for file in os.listdir('./'): if file.endswith('.md'): md_file_path = os.path.join('./', file) latex_file_path = os.path.join('./', os.path.splitext(file)[0] + '.tex') convert_md_file_to_latex(md_file_path, latex_file_path) print(f"Converted {md_file_path} to {latex_file_path}")
|