python将epub文件转pdf
说明:我最近突然碰到一个需求,将epub文件转pdf,花了我三个小时才弄好,虽然不起眼,但是处理起来是真的麻烦,报了一堆错误,才弄好 (ps:新手弄三天都弄不好,不过可以参考我这篇博客,十分钟可搞定)
step1:安装软件和环境
安装 Pandoc安装 wkhtmltopdf
step2:添加环境变量
C:\Program Files\Pandoc
C:\Program Files\wkhtmltopdf\bin
step3:完整代码 可直接运行,亲测可用 完美支持中文
C:\Users\wangrusheng\PycharmProjects\FastAPIProject1\hello.py
import os
import sys
import subprocess
import tracebackdef epub_to_pdf_simple(epub_path, output_pdf=None):"""使用完整路径调用 pandoc"""if output_pdf is None:output_pdf = os.path.splitext(epub_path)[0] + ".pdf"# 指定所有工具的完整路径pandoc_path = r'C:\Program Files\Pandoc\pandoc.exe'wkhtmltopdf_path = r'C:\Program Files\wkhtmltopdf\bin\wkhtmltopdf.exe'# 修改后的命令 - 移除了不支持的参数command = [pandoc_path,epub_path,"-o", output_pdf,f"--pdf-engine={wkhtmltopdf_path}","--verbose"]try:result = subprocess.run(command,check=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE,text=True,encoding='utf-8',errors='replace')print(f"转换成功!PDF保存至: {output_pdf}")print("命令输出:\n", result.stdout)return output_pdfexcept subprocess.CalledProcessError as e:print(f"转换失败: {e.stderr if e.stderr else 'Unknown error'}")print("详细错误信息:")traceback.print_exc()sys.exit(1)if __name__ == "__main__":epub_file = r"C:\Users\wangrusheng\Downloads\us.epub"epub_to_pdf_simple(epub_file)
end