-
Notifications
You must be signed in to change notification settings - Fork 3
/
webpage_to_pdf.py
executable file
·147 lines (124 loc) · 4.38 KB
/
webpage_to_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
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
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
#!/usr/bin/env python3
"""
Generate PDF from a webpage
"""
import argparse
import asyncio
import logging
import os
import platform
import random
import time
from pathlib import Path
from pyppeteer import launch
from slug import slug
ENCODE_IN = "utf-8"
ENCODE_OUT = "utf-8"
TEMPLATE_DIR = os.path.dirname(os.path.abspath(__file__))
def parse_args():
"""Parse command line arguments."""
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("-i", "--input-url", type=str, required=True, help="Web Url")
parser.add_argument(
"-o",
"--output-file-path",
type=Path,
default=Path.cwd().joinpath("target"),
help="Full output file path for PDF",
)
parser.add_argument(
"-w",
"--wait-in-secs-before-capture",
type=int,
default=5,
help="Wait (in secs) before capturing screenshot",
)
parser.add_argument(
"-s",
"--headless",
action="store_true",
default=False,
help="Run headless (no browser window)",
)
return parser.parse_args()
async def open_site(browser, website_url, output_dir):
page = await browser.newPage()
await page._client.send(
"Page.setDownloadBehavior",
{"behavior": "allow", "downloadPath": output_dir},
)
await page.goto(website_url, {"waitUntil": "networkidle2"})
return browser, page
def scroll_speed():
return random.randint(300, 500)
async def scroll_to_end(page):
current_scroll_position, new_height = 0, 1
while current_scroll_position <= new_height:
await page.evaluate(f"""() => {{ window.scrollTo(0, {current_scroll_position}); }} """)
new_height = await page.evaluate("""() => { return document.body.scrollHeight; } """)
current_scroll_position += scroll_speed()
logging.info(f"current_scroll_position: {current_scroll_position}, new_height: {new_height}")
# Wait to any dynamic elements to load
time.sleep(2)
async def generate_pdf(page, output_file_path):
return await page.pdf(
{
"margin": {
"top": 50,
"bottom": 50,
"left": 30,
"right": 30,
},
"path": output_file_path,
format: "A4",
}
)
async def main():
args = parse_args()
website_url = args.input_url
output_file_path = args.output_file_path
if output_file_path.is_dir():
web_page_title = slug(website_url)
output_file_path = output_file_path.joinpath(f"{web_page_title}.pdf")
wait_in_secs_before_capture = args.wait_in_secs_before_capture
run_headless = args.headless
output_dir = output_file_path.parent
output_dir.mkdir(exist_ok=True)
launch_config = {
"headless": run_headless,
"defaultViewport": None,
}
if platform.system().lower() == "linux":
if Path("/usr/bin/chromium-browser").is_file():
launch_config["executablePath"] = "/usr/bin/chromium-browser"
else:
logging.error("Chromium not found. Please install it and make it available in /usr/bin/chromium-browser")
browser = await launch(**launch_config)
logging.info(f"Processing {website_url}")
try:
browser, page = await open_site(browser, website_url, output_dir.as_posix())
time.sleep(wait_in_secs_before_capture)
await scroll_to_end(page)
logging.info("🚒 Reached end of page. Trying to capture PDF")
if run_headless:
try:
await asyncio.wait_for(generate_pdf(page, output_file_path.as_posix()), timeout=20)
logging.info(f"📸 PDF saved {output_file_path}")
await page.close()
except asyncio.TimeoutError:
logging.error(f"PDF generation timed out for {website_url}")
else:
logging.warning("⚠️ PDF generation is only supported in headless mode. Run with --headless")
except Exception:
logging.exception(f"Error while processing {website_url}")
def setup_logging():
logging.basicConfig(
handlers=[logging.StreamHandler()],
format="%(asctime)s - %(filename)s:%(lineno)d - %(message)s",
datefmt="%Y-%m-%d %H:%M:%S",
level=logging.INFO,
)
logging.captureWarnings(capture=True)
if __name__ == "__main__":
setup_logging()
asyncio.get_event_loop().run_until_complete(main())