简体   繁体   English

Python将txt文件转换为pdf

[英]Python convert txt file to pdf

I was wondering what would be simplest way to convert txt files in path batch convert to PDF?我想知道将路径批处理中的 txt 文件转换为 PDF 的最简单方法是什么?

I've looked into this in Python https://github.com/baruchel/txt2pdf but I can't seem to call txt2pdf in terminal after importing it.我已经在 Python https://github.com/baruchel/txt2pdf 中研究过这个,但在导入后我似乎无法在终端中调用 txt2pdf 。

Any other suggestions?还有其他建议吗?

Something like:就像是:

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

also tried this using ReportLab也尝试过使用 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

not sure you already found the solution or not, just happen to see this question when I also searching the answer for related to your question.不确定您是否已经找到解决方案,当我也在搜索与您的问题相关的答案时碰巧看到了这个问题。

You can just run as below if you are in terminal:如果您在终端中,则可以按如下方式运行:

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

Or if you run in jupyter notebook, just run as below:或者,如果您在 jupyter notebook 中运行,只需运行如下:

run txt2pdf.py yourfile.txt

Thank you.谢谢你。

Go here to see how click this去这里看看如何点击这个

This is the code after you installed pdfkit as the post of the link above shows这是安装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")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM