英文:
Markdown to pdf for Python
问题
I want to convert markdown file as pdf in python. how can i do this my library downloads are ok but there is always a problem, i tried the code below and it gives an error
import markdown2
import pdfkit
filename = "sample.md";
mode = "r";
with open(filename, mode) as file:
markdown_text = file.read()
html_text = markdown2.markdown(markdown_text)
pdfkit.from_string(html_text, "output.pdf")
I wrote the code I tried in the description.
英文:
I want to convert markdown file as pdf in python. how can i do this my library downloads are ok but there is always a problem, i tried the code below and it gives an error
import markdown2
import pdfkit
filename = "sample.md"
mode = "r"
with open(filename, mode) as file:
markdown_text = file.read()
html_text = markdown2.markdown(markdown_text)
pdfkit.from_string(html_text, "output.pdf")
I wrote the code I tried in the description.
答案1
得分: 2
这是抛出的异常:
OSError: 未找到 wkhtmltopdf 可执行文件
浏览互联网,我看到这是一个常见问题。它要求您下载某种二进制文件并将其传递给参数。就像这样:
import markdown2
import pdfkit
filename = "sample.md"
mode = "r"
with open(filename, mode) as file:
markdown_text = file.read()
html_text = markdown2.markdown(markdown_text)
config = pdfkit.configuration(wkhtmltopdf="/path/to/wkhtmltopdf.exe")
pdfkit.from_string(html_text, "output.pdf", configuration=config)
请查看此帖子以获取有关如何下载 wkhtmltopdf.exe
的更多信息。
另外,看起来您最终可以使用 pdfkit.from_file()
而不是 .from_string()
。它可能会为您提供更准确的输出并且代码更轻,但仍然需要您下载 wkhtmltopdf.exe
。类似于这样:
import pdfkit
filename = "sample.md"
mode = "r"
with open(filename, mode) as file:
config = pdfkit.configuration(wkhtmltopdf="/path/to/wkhtmltopdf.exe")
pdfkit.from_file(file, "output.pdf", configuration=config)
它应该可以工作,但我没有测试输出。
英文:
This is the exception being thrown:
OSError: No wkhtmltopdf executable found
Browsing the internet, I see it as a common problem. It requires you to download some sort of binaries and pass it in the parameter. Like so:
import markdown2
import pdfkit
filename = "sample.md"
mode = "r"
with open(filename, mode) as file:
markdown_text = file.read()
html_text = markdown2.markdown(markdown_text)
config = pdfkit.configuration(wkhtmltopdf="/path/to/wkhtmltopdf.exe")
pdfkit.from_string(html_text, "output.pdf", configuration=config)
Please, check this post for further information on how to download this wkhtmltopdf.exe
.
Plus, it looks like you can eventually use the pdfkit.from_file()
instead of .from_string()
. It may give you a more correct output with a lighter code, but it still requires you to download this wkhtmltopdf.exe
.
Something like this:
import pdfkit
filename = "sample.md"
mode = "r"
with open(filename, mode) as file:
config = pdfkit.configuration(wkhtmltopdf="/path/to/wkhtmltopdf.exe")
pdfkit.from_file(file, "output.pdf", configuration=config)
It should work, but I didn't test the output.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论