1.在DeepSeek对话框上传markdown文件,并提示
编写python程序,读入附件格式的md文件,用适当的库生成pdf格式幻灯片,只要一个代码,不做别的
它的输出:
以下Python程序可以读取您提供的Markdown格式课件,并使用适当的库生成PDF格式的幻灯片:
python
import re
import markdown
from weasyprint import HTML
import os
def md_to_pdf_slides(md_file_path, output_pdf_path):
"""
将Markdown格式的课件转换为PDF幻灯片
"""
# 读取Markdown文件
with open(md_file_path, 'r', encoding='utf-8') as f:
md_content = f.read()
# 预处理:将Markdown标题转换为幻灯片分隔标记
# 检测一级标题(# 开头)作为新幻灯片的开始
slides_content = []
current_slide = []
lines = md_content.split('\n')
for line in lines:
if line.startswith('# ') or line.startswith('#') and line.startswith('##'):
# 如果是标题行,保存当前幻灯片并开始新幻灯片
if current_slide:
slides_content.append('\n'.join(current_slide))
current_slide = []
current_slide.append(line)
elif line.startswith('---'):
# 显式的幻灯片分隔符
if current_slide:
slides_content.append('\n'.join(current_slide))
current_slide = []
else:
current_slide.append(line)
# 添加最后一张幻灯片
if current_slide:
slides_content.append('\n'.join(current_slide))
# 生成HTML幻灯片样式
html_template = """
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>计算机常识科普课件</title>
<style>
body {{
margin: 0;
padding: 0;
font-family: 'Microsoft YaHei', '宋体', Arial, sans-serif;
background-color: #f5f5f5;
}}
.slide-container {{
width: 100%;
max-width: 1200px;
margin: 0 auto;
}}
.slide {{
page-break-after: always;
width: 100%;
min-height: 100vh;
padding: 40px 60px;
box-sizing: border-box;
background-color: white;
box-shadow: 0 4px 8px rgba(0,0,0,0.1);
margin-bottom: 20px;
position: relative;
border-radius: 8px;
}}
h1 {{
color: #FFA500;
font-size: 48px;
border-bottom: 3px solid #FFA500;
padding-bottom: 15px;
margin-top: 20px;
}}
h2 {{
color: #FF8C00;
font-size: 36px;
margin-top: 30px;
}}
h3 {{
color: #FF6346;
font-size: 28px;
}}
p {{
font-size: 24px;
line-height: 1.6;
color: #333333;
margin: 20px 0;
}}
table {{
width: 100%;
border-collapse: collapse;
margin: 25px 0;
font-size: 22px;
}}
th {{
background-color: #FFA500;
color: white;
font-weight: bold;
padding: 12px;
text-align: left;
border: 1px solid #ddd;
}}
td {{
padding: 12px;
border: 1px solid #ddd;
background-color: #f9f9f9;
}}
tr:hover td {{
background-color: #f1f1f1;
}}
blockquote {{
background-color: #e6f3ff;
border-left: 8px solid #FFA500;
padding: 15px 25px;
margin: 20px 0;
font-size: 24px;
border-radius: 0 8px 8px 0;
}}
ul, ol {{
font-size: 24px;
line-height: 1.6;
padding-left: 40px;
}}
li {{
margin: 10px 0;
}}
hr {{
border: none;
border-top: 3px dashed #FFA500;
margin: 30px 0;
}}
.emoji {{
font-size: 28px;
}}
strong {{
color: #FF4500;
}}
em {{
color: #2E8B57;
font-style: italic;
}}
.slide-number {{
position: absolute;
bottom: 20px;
right: 30px;
font-size: 18px;
color: #999;
}}
/* 互动提问框样式 */
p:contains("互动提问") {{
background-color: #FFF3E0;
padding: 15px;
border-radius: 10px;
border-left: 5px solid #FFA500;
}}
</style>
</head>
<body>
<div class="slide-container">
"""
# 转换每个幻灯片内容为HTML
slide_counter = 1
for slide_md in slides_content:
# 过滤掉空幻灯片
if slide_md.strip():
# 将Markdown转换为HTML
html_content = markdown.markdown(
slide_md,
extensions=['extra', 'tables', 'nl2br']
)
# 添加特殊样式标记
html_content = html_content.replace('互动提问',
'<span style="background-color: #FFF3E0; padding: 5px 10px; border-radius: 5px;">🔍 互动提问</span>')
# 包装为幻灯片
slide_html = f"""
<div class="slide">
{html_content}
<div class="slide-number">{slide_counter}</div>
</div>
"""
html_template += slide_html
slide_counter += 1
html_template += """
</div>
</body>
</html>
"""
# 保存临时HTML文件
temp_html = "temp_slides.html"
with open(temp_html, 'w', encoding='utf-8') as f:
f.write(html_template)
# 使用WeasyPrint生成PDF
try:
HTML(temp_html).write_pdf(output_pdf_path)
print(f"✅ PDF幻灯片已成功生成:{output_pdf_path}")
print(f"📊 共生成 {slide_counter-1} 页幻灯片")
except Exception as e:
print(f"❌ 生成PDF时出错:{e}")
finally:
# 清理临时文件
if os.path.exists(temp_html):
os.remove(temp_html)
# 主程序
if __name__ == "__main__":
# 设置文件路径
input_md = "computer_common_knowledge_课件.md" # 输入Markdown文件
output_pdf = "计算机常识科普课件.pdf" # 输出PDF文件
# 检查输入文件是否存在
if not os.path.exists(input_md):
print(f"❌ 错误:找不到文件 {input_md}")
print("请确保Markdown文件在当前目录下,或修改文件路径")
else:
# 转换文件
md_to_pdf_slides(input_md, output_pdf)
print("\n💡 提示:如果PDF生成失败,请确保已安装必要的库:")
print("pip install markdown weasyprint")
使用方法
- 安装依赖库:
bash
pip install markdown weasyprint
- 运行程序:
bash
python md_to_pdf_slides.py
程序功能说明
- 自动分页 :根据Markdown的一级标题(
#开头)自动分割幻灯片 - 保留格式:完整保留Markdown的表格、列表、引用等格式
- 美观样式 :
- 标题使用亮黄色/橙色
- 正文为浅灰色
- 关键词和重点内容突出显示
- 互动提问框特殊样式
- 页码标注:每页幻灯片底部显示页码
- 响应式设计:适应不同纸张大小
生成的PDF将完美呈现您提供的课件内容,包括表格、互动提问、思考题等所有元素。
2.安装依赖库
pip install markdown weasyprint
Looking in indexes: https://mirrors.aliyun.com/pypi/simple
Successfully installed Pyphen-0.17.2 brotli-1.2.0 cffi-2.0.0 cssselect2-0.9.0 fonttools-4.61.1 markdown-3.10.2 pycparser-3.0 pydyf-0.12.1 tinycss2-1.5.1 tinyhtml5-2.0.0 weasyprint-68.1 webencodings-0.5.1 zopfli-0.4.1
3.执行脚本,报错了。
C:\d>python md2pdf.py
-----
WeasyPrint could not import some external libraries. Please carefully follow the installation steps before reporting an issue:
https://doc.courtbouillon.org/weasyprint/stable/first_steps.html#installation
https://doc.courtbouillon.org/weasyprint/stable/first_steps.html#troubleshooting
-----
Traceback (most recent call last):
File "C:\d\md2pdf.py", line 3, in <module>
from weasyprint import HTML
File "C:\Users\lt\AppData\Local\Programs\Python\Python313\Lib\site-packages\weasyprint\__init__.py", line 372, in <module>
from .css import preprocess_stylesheet # noqa: I001, E402
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\lt\AppData\Local\Programs\Python\Python313\Lib\site-packages\weasyprint\css\__init__.py", line 29, in <module>
from ..text.fonts import FontConfiguration
File "C:\Users\lt\AppData\Local\Programs\Python\Python313\Lib\site-packages\weasyprint\text\fonts.py", line 17, in <module>
from .constants import ( # isort:skip
CAPS_KEYS, EAST_ASIAN_KEYS, FONTCONFIG_STRETCH, FONTCONFIG_STYLE, FONTCONFIG_WEIGHT,
LIGATURE_KEYS, NUMERIC_KEYS, PANGO_STRETCH, PANGO_STYLE, PANGO_VARIANT)
File "C:\Users\lt\AppData\Local\Programs\Python\Python313\Lib\site-packages\weasyprint\text\constants.py", line 5, in <module>
from .ffi import pango
File "C:\Users\lt\AppData\Local\Programs\Python\Python313\Lib\site-packages\weasyprint\text\ffi.py", line 476, in <module>
gobject = _dlopen(
ffi, 'libgobject-2.0-0', 'gobject-2.0-0', 'gobject-2.0',
'libgobject-2.0.so.0', 'libgobject-2.0.0.dylib', 'libgobject-2.0-0.dll')
File "C:\Users\lt\AppData\Local\Programs\Python\Python313\Lib\site-packages\weasyprint\text\ffi.py", line 464, in _dlopen
return ffi.dlopen(names[0], flags) # pragma: no cover
~~~~~~~~~~^^^^^^^^^^^^^^^^^
File "C:\Users\lt\AppData\Local\Programs\Python\Python313\Lib\site-packages\cffi\api.py", line 150, in dlopen
lib, function_cache = _make_ffi_library(self, name, flags)
~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^
File "C:\Users\lt\AppData\Local\Programs\Python\Python313\Lib\site-packages\cffi\api.py", line 834, in _make_ffi_library
backendlib = _load_backend_lib(backend, libname, flags)
File "C:\Users\lt\AppData\Local\Programs\Python\Python313\Lib\site-packages\cffi\api.py", line 829, in _load_backend_lib
raise OSError(msg)
OSError: cannot load library 'libgobject-2.0-0': error 0x7e. Additionally, ctypes.util.find_library() did not manage to locate a library called 'libgobject-2.0-0'
- 安装msys2和mingw64
参考提示网页https://doc.courtbouillon.org/weasyprint/stable/first_steps.html#installation的说明
在 https://www.msys2.org/#installation 下载了 https://github.com/msys2/msys2-installer/releases/download/2025-12-13/msys2-x86_64-20251213.exe 安装并运行。
在msys2命令行中输入pacman -S mingw-w64-x86_64-pango,自动安装各种库。
回到windows cmd控制台,输入如下命令行。
C:\d>set WEASYPRINT_DLL_DIRECTORIES=C:\d\msys64\mingw64\bin
C:\d>python md2pdf.py
✅ PDF幻灯片已成功生成:计算机常识科普课件.pdf
📊 共生成 13 页幻灯片
注意:必须安装msys2,我的机器原来就安装过mingw64,但它不包括libgobject-2.0-0.dll文件,将WEASYPRINT_DLL_DIRECTORIES设成它的路径还是报同样的错。