-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
save_as_pdf.py
45 lines (37 loc) · 1.37 KB
/
save_as_pdf.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
import pdfkit
import platform
import re
# Path to wkhtmltopdf for Windows Machine
path_wkthmltopdf = r'C:\Program Files\wkhtmltopdf\bin\wkhtmltopdf.exe'
#path_wkthmltopdf = r'.\wkhtmltopdf\bin\wkhtmltopdf.exe'
config = pdfkit.configuration(wkhtmltopdf = path_wkthmltopdf)
def is_linux():
"""
Identify the current platform
:return: True if Linux else False
"""
return platform.system() == "Linux"
def remove_unwanted(name):
"""
Function to remove characters from contest like VK Cup 2015 Раунд 3
https://codeforces.com/contest/541/problems
"""
# Valid Name in Contest
pattern = re.compile('[a-z0-9\s\-()[\]\.,\+#]+', re.IGNORECASE)
for i, elem in enumerate(name):
if not re.match(pattern, elem):
return name[: i]
return name
def write_pdf(DIR, file_name, title, html):
if is_linux():
try:
pdfkit.from_string(html, file_name, configuration=config)
except:
file_name = DIR + remove_unwanted(title) + ".pdf"
pdfkit.from_string(html, file_name, configuration=config)
else:
try:
pdfkit.from_string(html, file_name, configuration=config)
except Exception as e:
file_name = DIR + remove_unwanted(title) + ".pdf"
pdfkit.from_string(html, file_name, configuration=config)