import pypandoc import os from pathlib import Path def convert_md_to_pdf(input_path: str, output_path: str, template_path: str = None) -> None: """ 将Markdown文件转换为PDF,支持中文 Args: input_path: 输入的Markdown文件路径 output_path: 输出的PDF文件路径 template_path: 可选的LaTeX模板文件路径 """ # 验证输入文件是否存在 if not os.path.exists(input_path): raise FileNotFoundError(f"输入文件 {input_path} 不存在") # 准备额外参数 extra_args = ['--pdf-engine=xelatex'] # 如果提供了模板文件,验证并添加模板参数 if template_path: if not os.path.exists(template_path): raise FileNotFoundError(f"模板文件 {template_path} 不存在") extra_args.append(f'--template={template_path}') # 确保输出目录存在 output_dir = os.path.dirname(output_path) if output_dir and not os.path.exists(output_dir): os.makedirs(output_dir) try: # 执行转换 pypandoc.convert_file( input_path, 'pdf', outputfile=output_path, extra_args=extra_args ) print(f"成功将 {input_path} 转换为 {output_path}") except Exception as e: print(f"转换失败: {str(e)}") raise if __name__ == "__main__": # 使用示例 input_file = '开放接口文档.md' output_file = 'output/example.pdf' # 可以指定子目录 template_file = 'template.tex' # 可选模板 # 使用Path处理路径更安全 input_file = str(Path(input_file).resolve()) output_file = str(Path(output_file).resolve()) convert_md_to_pdf(input_file, output_file, template_file)