md2pdf.py 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. import pypandoc
  2. import os
  3. from pathlib import Path
  4. def convert_md_to_pdf(input_path: str, output_path: str, template_path: str = None) -> None:
  5. """
  6. 将Markdown文件转换为PDF,支持中文
  7. Args:
  8. input_path: 输入的Markdown文件路径
  9. output_path: 输出的PDF文件路径
  10. template_path: 可选的LaTeX模板文件路径
  11. """
  12. # 验证输入文件是否存在
  13. if not os.path.exists(input_path):
  14. raise FileNotFoundError(f"输入文件 {input_path} 不存在")
  15. # 准备额外参数
  16. extra_args = ['--pdf-engine=xelatex']
  17. # 如果提供了模板文件,验证并添加模板参数
  18. if template_path:
  19. if not os.path.exists(template_path):
  20. raise FileNotFoundError(f"模板文件 {template_path} 不存在")
  21. extra_args.append(f'--template={template_path}')
  22. # 确保输出目录存在
  23. output_dir = os.path.dirname(output_path)
  24. if output_dir and not os.path.exists(output_dir):
  25. os.makedirs(output_dir)
  26. try:
  27. # 执行转换
  28. pypandoc.convert_file(
  29. input_path,
  30. 'pdf',
  31. outputfile=output_path,
  32. extra_args=extra_args
  33. )
  34. print(f"成功将 {input_path} 转换为 {output_path}")
  35. except Exception as e:
  36. print(f"转换失败: {str(e)}")
  37. raise
  38. if __name__ == "__main__":
  39. # 使用示例
  40. input_file = '开放接口文档.md'
  41. output_file = 'output/example.pdf' # 可以指定子目录
  42. template_file = 'template.tex' # 可选模板
  43. # 使用Path处理路径更安全
  44. input_file = str(Path(input_file).resolve())
  45. output_file = str(Path(output_file).resolve())
  46. convert_md_to_pdf(input_file, output_file, template_file)