Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env python3
- # -*- coding: utf-8 -*-
- # Filename: txt2pdf.py
- # Version: 1.0.0
- # Author: Jeoi Reqi
- """
- Description:
- This script converts a text file (.txt) to a PDF file (.pdf).
- It handles word wrapping to ensure that each line in the text file is properly displayed within the PDF.
- Requirements:
- - Python 3.x
- - ReportLab library (install using: pip install reportlab)
- Usage:
- 1. Save this script as 'txt2pdf.py'.
- 2. Ensure your text file ('example.txt') is in the same directory as the script.
- 3. Install the ReportLab library using the command: 'pip install reportlab'
- 4. Run the script.
- 5. The converted PDF file ('txt2pdf.pdf') will be generated in the same directory.
- Note: Adjust the 'txt_filename' and 'pdf_filename' variables in the script as needed.
- """
- from reportlab.pdfgen import canvas
- from reportlab.lib.pagesizes import letter
- def txt_to_pdf(txt_filename, pdf_filename):
- with open(txt_filename, 'r', encoding='utf-8') as txtfile:
- lines = txtfile.readlines()
- pdf = canvas.Canvas(pdf_filename, pagesize=letter)
- # Set the font and size
- pdf.setFont("Helvetica", 12)
- # Set the initial y-position and line spacing
- y_position = 750
- line_spacing = 12
- # Get the PDF width
- pdf_width, pdf_height = letter
- # Iterate through lines and add to PDF with word wrapping
- for line in lines:
- if y_position < 50:
- pdf.showPage()
- y_position = pdf_height - 50 # Reset y-position for the new page
- words = line.strip().split()
- if not words:
- continue # Skip empty lines
- current_line = words[0]
- for word in words[1:]:
- if pdf.stringWidth(current_line + " " + word) < pdf_width - 20:
- current_line += " " + word
- else:
- pdf.drawString(10, y_position, current_line)
- y_position -= line_spacing
- current_line = word
- pdf.drawString(10, y_position, current_line)
- y_position -= line_spacing
- pdf.save()
- if __name__ == "__main__":
- # Set the filenames for the text and PDF files
- txt_filename = 'example.txt'
- pdf_filename = 'txt2pdf.pdf'
- # Convert the text to a multi-page PDF file using reportlab with improved word wrapping
- txt_to_pdf(txt_filename, pdf_filename)
- print(f"Converted '{txt_filename}' to '{pdf_filename}'.")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement