nerdboy
nerdboy

Reputation: 751

Python convert txt file to pdf

I was wondering what would be simplest way to convert txt files in path batch convert to 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.

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

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

Upvotes: 1

Views: 10686

Answers (2)

PythonProgrammi
PythonProgrammi

Reputation: 23443

Go here to see how click this

This is the code after you installed pdfkit as the post of the link above shows

# 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")

Upvotes: 3

Tyson
Tyson

Reputation: 55

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:

run txt2pdf.py yourfile.txt

Thank you.

Upvotes: 2

Related Questions