Convert TXT to PDF in Python

Andrew Wilson
2 min readMar 12, 2024

Compared with TXT text files, PDF files exhibit a higher level of professionalism, making them more appropriate for sharing and transmission purposes. PDF files are widely utilized in formal settings such as business reports, academic papers, legal contracts, and even personal documents like CVs.

In scenarios where maintaining the integrity of the document’s design is crucial, it is often necessary to convert text files to PDF format to ensure that the recipient perceives the document as intended by the creator. In this article, we will explore how to convert TXT to PDF with Python.

Python Library for TXT to PDF Conversion

Converting text files to PDF in Python requires a third-party library — Spire.PDF for Python, which can be installed with the following pip command.

pip install Spire.PDF

Python Guide for Converting Text Files to PDF

Procedures: 👇

The TXT to PDF conversion method provided by Spire.PDF for Python library is:

1. First read the text from the TXT file through the ReadFromTxt() method.

2. Then draw the text to at a specified location on a PDF page using PdfTextWidget.Draw() method.

The Python library also provides a variety of interfaces to set the font, font color, alignment style and other formatting of the drawn text.

Here is a simple code sample for converting a TXT file to a PDF file.

from spire.pdf.common import *
from spire.pdf import *

def ReadFromTxt(fname: str) -> str:
with open(fname, 'r') as f:
text = f.read()
return text

# Get text from the txt file
text = ReadFromTxt("Text.txt")

# Create a PdfDocument instance
pdf = PdfDocument()

# Add a page
page = pdf.Pages.Add()

# Create a PDF font and PDF brush
font = PdfFont(PdfFontFamily.Courier, 11.0)
brush = PdfBrushes.get_Blue()

# Set the text formatting and layout
strformat = PdfStringFormat()
strformat.LineSpacing = 10.0
strformat.Alignment = PdfTextAlignment.Left
textLayout = PdfTextLayout()
textLayout.Layout = PdfLayoutType.Paginate

# Create a PdfTextWidget instance and draw the text at the specified location on the page
textWidget = PdfTextWidget(text, font, brush)
textWidget.StringFormat = strformat
bounds = RectangleF(PointF(10.0, 20.0), page.Canvas.ClientSize)
textWidget.Draw(page, bounds, textLayout)

# Save the PDF file
pdf.SaveToFile("TxtToPdf.pdf", FileFormat.PDF)
pdf.Close()

Output result:

Python TXT to PDF

By running the above code, you can generate PDF documents from TXT files. If you need to add images, shapes, watermarks or other elements in the PDF file, you can use other interfaces provided by Spire.PDF.

Explore more demos at:

--

--

Andrew Wilson

Explore C#, Java and Python solutions for processing Word/Excel/PowerPoint/PDF files.