How to Convert Text to PDF in Python?

Estimated read time 2 min read

To convert text to PDF in Python, you can use the reportlab library. reportlab is a powerful PDF generation library that allows you to create PDF documents programmatically. Here’s an example of how to convert text to PDF using reportlab:

from reportlab.pdfgen import canvas

def convert_text_to_pdf(text, output_path):
    c = canvas.Canvas(output_path)

    # Set font and font size
    c.setFont("Helvetica", 12)

    # Set text color
    c.setFillColorRGB(0, 0, 0)

    # Set starting position for text
    x = 50
    y = 750

    # Split the text into lines
    lines = text.split('\n')

    # Write each line of text to the PDF
    for line in lines:
        c.drawString(x, y, line)
        y -= 20  # Move to the next line

# Example usage
text = "This is a sample text.\nIt will be converted to PDF."
output_path = "output.pdf"

convert_text_to_pdf(text, output_path)

In this example, we define the convert_text_to_pdf function that takes the text content and the output path as parameters. Inside the function, we create a canvas object from reportlab.pdfgen module. We set the font, font size, and text color for the PDF. Then, we split the text into lines using the newline character (\n). We iterate over each line and use the drawString method of the canvas object to write the text to the PDF. We update the y-coordinate to move to the next line after each iteration. Finally, we save the PDF using the save method of the canvas object.

In the example usage section, we provide some sample text and the output path for the PDF. You can modify the text and output_path variables to your desired text content and output file path.

After running the code, a PDF file will be generated at the specified output path containing the converted text.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply