-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtext_to_pdf.py
More file actions
95 lines (77 loc) · 2.69 KB
/
text_to_pdf.py
File metadata and controls
95 lines (77 loc) · 2.69 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
#!/usr/bin/env python3
"""
Convert a text file to PDF
Usage: python text_to_pdf.py input.txt output.pdf
"""
from reportlab.lib.pagesizes import letter
from reportlab.pdfgen import canvas
from reportlab.lib.units import inch
import sys
def text_to_pdf(input_file, output_file):
"""Convert a text file to PDF with proper formatting"""
# Read the text file
with open(input_file, 'r', encoding='utf-8') as f:
text_content = f.read()
# Create PDF
c = canvas.Canvas(output_file, pagesize=letter)
width, height = letter
# Set up formatting
margin = 0.75 * inch
y_position = height - margin
line_height = 14
max_width = width - (2 * margin)
# Set font
c.setFont("Helvetica", 10)
# Split text into lines
lines = text_content.split('\n')
for line in lines:
# Handle empty lines
if not line.strip():
y_position -= line_height
if y_position < margin:
c.showPage()
c.setFont("Helvetica", 10)
y_position = height - margin
continue
# Wrap long lines
words = line.split()
current_line = ""
for word in words:
test_line = current_line + word + " "
if c.stringWidth(test_line, "Helvetica", 10) <= max_width:
current_line = test_line
else:
# Draw the current line
if current_line:
c.drawString(margin, y_position, current_line.rstrip())
y_position -= line_height
if y_position < margin:
c.showPage()
c.setFont("Helvetica", 10)
y_position = height - margin
current_line = word + " "
# Draw remaining text
if current_line:
c.drawString(margin, y_position, current_line.rstrip())
y_position -= line_height
if y_position < margin:
c.showPage()
c.setFont("Helvetica", 10)
y_position = height - margin
# Save the PDF
c.save()
print(f"PDF created successfully: {output_file}")
if __name__ == "__main__":
if len(sys.argv) != 3:
print("Usage: python text_to_pdf.py input.txt output.pdf")
sys.exit(1)
input_file = sys.argv[1]
output_file = sys.argv[2]
try:
text_to_pdf(input_file, output_file)
except FileNotFoundError:
print(f"Error: File '{input_file}' not found")
sys.exit(1)
except Exception as e:
print(f"Error: {e}")
sys.exit(1)