Python将txt文件转换为pdf

时间:2017-04-17 20:51:48

标签: python pdf text converter

我想知道在路径批量转换为PDF时将txt文件转换成最简单的方法是什么?

我在Python https://github.com/baruchel/txt2pdf中研究过这个 但是在导入后我似乎无法在终端中调用txt2pdf。

还有其他建议吗?

类似的东西:

text_file = open(filename, 'r')
i = 0
for item in text_file:
    i += 1
    f = open("c:\\workspace\\{0}.txt".format(i), 'w')
    txt2pdf convert (whatever goes here)
        if i == 7:
           break

也尝试使用ReportLab

def hello(c):
ic = 0
c = open("c:\\workspace\\simple\\{0}.txt".format(ic), 'w')
for item in c:
    ic += 1
    c = canvas.Canvas("c:\\workspace\\simple\\{0}.pdf".format(ic))
    hello(c)
    c.showPage()
    c.save()
    if ic == 7:
        break

2 个答案:

答案 0 :(得分:1)

不确定您是否已找到解决方案,当我也在搜索与您的问题相关的答案时,恰好会看到这个问题。

如果你在终端,你可以按如下方式运行:

python txt2pdf.py yourfile.txt 
## Make sure the txt2pdf.py is at your working environment and also the .txt too

或者如果您在jupyter笔记本中运行,请按以下方式运行:

run txt2pdf.py yourfile.txt

谢谢。

答案 1 :(得分:0)

转到此处查看如何click this

这是安装pdfkit后的代码,如上面链接所示:

# from txt to html
# install wkthtml
import os
import pdfkit

with open("text.txt") as file:
    with open ("text.html", "w") as output:
        file = file.read()
        file = file.replace("\n", "<br>")
        output.write(file)

pdfkit.from_file("text.html", "output.pdf")

os.startfile("output.pdf")
相关问题