-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
executable file
·131 lines (88 loc) · 2.59 KB
/
main.py
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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
#!/usr/bin/python3
# -----------------------------------------------------------------
# simple script for edit and creating pdf files.
# and converting txt files to pdf files.
#
#
#
# Author:N84.
#
# Create Date:Fri Mar 18 11:28:38 2022.
# ///
# ///
# ///
# -----------------------------------------------------------------
from os import system
from os import name as OS_NAME
from os import getcwd
from os import listdir
from fpdf import FPDF
from sys import argv
def clear():
"""wipe the terminal screen."""
if OS_NAME == "posix":
# for *nix machines.
system("clear")
elif OS_NAME == "windows":
system("cls")
else:
# for other os in the world.
# system("your-command")
pass
return None
clear()
def get_args():
"""return all the arguments that pass,
to the program except the program name."""
return argv[1:]
def separate2lines(string: str, max_char: int = 64):
"""separate a string into multi line string, with max_length of line,
equal to max_char.
we will use this function to align pdf lines."""
# first make sure to remove all linefeeds.
text = string.replace("\n", "")
lines = []
temp_string, counter = "", 0
for char in text:
if counter == max_char-1:
lines.append(temp_string + char + "\n")
temp_string = ""
counter = 0
continue
temp_string += char
counter += 1
lines.append(temp_string)
return lines
def file_exist(file_name: str):
"""checkout if the given file name is exist,
in the working dir or not."""
return file_name in listdir(getcwd())
def txt2pdf(file_name: str = None):
"""convert any text => *.txt, to pdf"""
# guard condition.
if not file_exist(file_name):
return
if file_name is None:
raise Exception("FilePathError: please enter the file path.")
with open(f"{getcwd()}/{file_name}", "r") as file:
text = file.read()
# create pdf object.
pdf = FPDF()
pdf.add_page()
pdf.set_font("Arial", size=12)
text_lines = separate2lines(text, 90)
# print(text_lines)
for index, line in enumerate(text_lines):
pdf.cell(0, 10, txt=line, ln=1, align="L")
# make sure to split the file from the dot and get the name only.
# in simple words remove the file extension.
pdf.output(f"./{file_name.split('.')[0]}.pdf")
pdf.close()
return None
def main():
# get all the args=>file-names.
files = get_args()
for file in files:
txt2pdf(file)
if __name__ == '__main__':
main()