Skip to content

Commit 2a9906e

Browse files
authored
Add two commands: print and get_driver (#10)
1 parent 2dd95c6 commit 2a9906e

File tree

6 files changed

+122
-51
lines changed

6 files changed

+122
-51
lines changed

.github/workflows/ci-windows.yml

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -66,6 +66,10 @@ jobs:
6666
run: |
6767
invoke build
6868
69+
- name: Download ChromeDriver
70+
run: |
71+
python hpdf/hpdf.py get_driver
72+
6973
- name: Run tests (Bash)
7074
run: |
7175
invoke test

hpdf/hpdf.py

Lines changed: 98 additions & 45 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,8 @@
2525

2626
__version__ = "0.0.1"
2727

28+
DEFAULT_CACHE_DIR = os.path.join(Path.home(), ".hpdf", "chromedriver")
29+
2830
# HTML2PDF.js prints unicode symbols to console. The following makes it work on
2931
# Windows which otherwise complains:
3032
# UnicodeEncodeError: 'charmap' codec can't encode characters in position 129-130: character maps to <undefined>
@@ -35,9 +37,6 @@
3537

3638
class HTML2PDF_HTTPClient(HttpClient):
3739
def get(self, url, params=None, **kwargs) -> Response:
38-
"""
39-
Add you own logic here like session or proxy etc.
40-
"""
4140
last_error: Optional[Exception] = None
4241
for attempt in range(1, 3):
4342
print( # noqa: T201
@@ -147,9 +146,6 @@ def get_pdf_from_html(driver, url) -> bytes:
147146
"marginRight": get_inches_from_millimeters(21),
148147
}
149148

150-
print("html2pdf: executing print command with ChromeDriver.") # noqa: T201
151-
result = driver.execute_cdp_cmd("Page.printToPDF", calculated_print_options)
152-
153149
class Done(Exception):
154150
pass
155151

@@ -180,25 +176,33 @@ class Done(Exception):
180176
print(entry) # noqa: T201
181177
print('"""') # noqa: T201
182178

179+
#
180+
# Execute Print command with ChromeDriver.
181+
#
182+
print("html2pdf: executing print command with ChromeDriver.") # noqa: T201
183+
result = driver.execute_cdp_cmd("Page.printToPDF", calculated_print_options)
184+
183185
data = base64.b64decode(result["data"])
184186
return data
185187

186188

189+
def get_chrome_driver(path_to_cache_dir: str) -> str:
190+
cache_manager = HTML2PDF_CacheManager(
191+
file_manager=FileManager(os_system_manager=OperationSystemManager()),
192+
path_to_cache_dir=path_to_cache_dir,
193+
)
194+
195+
http_client = HTML2PDF_HTTPClient()
196+
download_manager = WDMDownloadManager(http_client)
197+
path_to_chrome = ChromeDriverManager(
198+
download_manager=download_manager, cache_manager=cache_manager
199+
).install()
200+
return path_to_chrome
201+
202+
187203
def create_webdriver(chromedriver: Optional[str], path_to_cache_dir: str):
188-
print("html2pdf: creating ChromeDriver service.", flush=True) # noqa: T201
189204
if chromedriver is None:
190-
cache_manager = HTML2PDF_CacheManager(
191-
file_manager=FileManager(
192-
os_system_manager=OperationSystemManager()
193-
),
194-
path_to_cache_dir=path_to_cache_dir,
195-
)
196-
197-
http_client = HTML2PDF_HTTPClient()
198-
download_manager = WDMDownloadManager(http_client)
199-
path_to_chrome = ChromeDriverManager(
200-
download_manager=download_manager, cache_manager=cache_manager
201-
).install()
205+
path_to_chrome = get_chrome_driver(path_to_cache_dir)
202206
else:
203207
path_to_chrome = chromedriver
204208
print(f"html2pdf: ChromeDriver available at path: {path_to_chrome}") # noqa: T201
@@ -236,50 +240,99 @@ def main():
236240
os.environ["WDM_LOCAL"] = "1"
237241

238242
parser = argparse.ArgumentParser(description="HTML2PDF printer script.")
243+
239244
parser.add_argument(
245+
"-v", "--version", action="version", version=__version__
246+
)
247+
248+
command_subparsers = parser.add_subparsers(title="command", dest="command")
249+
command_subparsers.required = True
250+
251+
#
252+
# Get driver command.
253+
#
254+
command_parser_get_driver = command_subparsers.add_parser(
255+
"get_driver",
256+
help="Check if ChromeDriver already exists locally. If not, download it.",
257+
description="",
258+
)
259+
command_parser_get_driver.add_argument(
260+
"--cache-dir",
261+
type=str,
262+
help="Optional path to a cache directory whereto the ChromeDriver is downloaded.",
263+
)
264+
265+
#
266+
# Print command.
267+
#
268+
command_parser_print = command_subparsers.add_parser(
269+
"print",
270+
help="Main print command",
271+
description="",
272+
)
273+
command_parser_print.add_argument(
240274
"--chromedriver",
241275
type=str,
242276
help="Optional chromedriver path. Downloaded if not given.",
243277
)
244-
parser.add_argument(
278+
command_parser_print.add_argument(
245279
"--cache-dir",
246280
type=str,
247281
help="Optional path to a cache directory whereto the ChromeDriver is downloaded.",
248282
)
249-
parser.add_argument("paths", nargs="+", help="Paths to input HTML file.")
283+
command_parser_print.add_argument(
284+
"paths", nargs="+", help="Paths to input HTML file."
285+
)
286+
250287
args = parser.parse_args()
251288

252-
paths: List[str] = args.paths
289+
path_to_cache_dir: str
290+
if args.command == "get_driver":
291+
path_to_cache_dir = (
292+
args.cache_dir
293+
if args.cache_dir is not None
294+
else (DEFAULT_CACHE_DIR)
295+
)
253296

254-
path_to_cache_dir: str = (
255-
args.cache_dir
256-
if args.cache_dir is not None
257-
else (os.path.join(Path.home(), ".hpdf", "chromedriver"))
258-
)
259-
driver = create_webdriver(args.chromedriver, path_to_cache_dir)
297+
path_to_chrome = get_chrome_driver(path_to_cache_dir)
298+
print(f"html2pdf: ChromeDriver available at path: {path_to_chrome}") # noqa: T201
299+
sys.exit(0)
260300

261-
@atexit.register
262-
def exit_handler():
263-
print("html2pdf: exit handler: quitting the ChromeDriver.") # noqa: T201
264-
driver.quit()
301+
elif args.command == "print":
302+
paths: List[str] = args.paths
265303

266-
assert len(paths) % 2 == 0, (
267-
f"Expecting an even number of input/output path arguments: {paths}."
268-
)
269-
for current_pair_idx in range(0, 2, len(paths)):
270-
path_to_input_html = paths[current_pair_idx]
271-
path_to_output_pdf = paths[current_pair_idx + 1]
304+
path_to_cache_dir = (
305+
args.cache_dir
306+
if args.cache_dir is not None
307+
else (DEFAULT_CACHE_DIR)
308+
)
309+
driver = create_webdriver(args.chromedriver, path_to_cache_dir)
272310

273-
assert os.path.isfile(path_to_input_html), path_to_input_html
311+
@atexit.register
312+
def exit_handler():
313+
print("html2pdf: exit handler: quitting the ChromeDriver.") # noqa: T201
314+
driver.quit()
274315

275-
path_to_output_pdf_dir = os.path.dirname(path_to_output_pdf)
276-
Path(path_to_output_pdf_dir).mkdir(parents=True, exist_ok=True)
316+
assert len(paths) % 2 == 0, (
317+
f"Expecting an even number of input/output path arguments: {paths}."
318+
)
319+
for current_pair_idx in range(0, 2, len(paths)):
320+
path_to_input_html = paths[current_pair_idx]
321+
path_to_output_pdf = paths[current_pair_idx + 1]
277322

278-
url = Path(os.path.abspath(path_to_input_html)).as_uri()
323+
assert os.path.isfile(path_to_input_html), path_to_input_html
279324

280-
pdf_bytes = get_pdf_from_html(driver, url)
281-
with open(path_to_output_pdf, "wb") as f:
282-
f.write(pdf_bytes)
325+
path_to_output_pdf_dir = os.path.dirname(path_to_output_pdf)
326+
Path(path_to_output_pdf_dir).mkdir(parents=True, exist_ok=True)
327+
328+
url = Path(os.path.abspath(path_to_input_html)).as_uri()
329+
330+
pdf_bytes = get_pdf_from_html(driver, url)
331+
with open(path_to_output_pdf, "wb") as f:
332+
f.write(pdf_bytes)
333+
else:
334+
print("html2pdf: unknown command.") # noqa: T201
335+
sys.exit(1)
283336

284337

285338
if __name__ == "__main__":

tasks.py

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -77,6 +77,18 @@ def format_readme(context):
7777
)
7878

7979

80+
@task
81+
def get_chrome_driver(
82+
context,
83+
):
84+
run_invoke(
85+
context,
86+
"""
87+
python hpdf/hpdf.py get_driver
88+
""",
89+
)
90+
91+
8092
@task
8193
def lint_ruff_format(context):
8294
result: invoke.runners.Result = run_invoke(
@@ -132,14 +144,16 @@ def lint(context):
132144
lint_mypy(context)
133145

134146

135-
@task
147+
@task(aliases=["ti"])
136148
def test_integration(
137149
context,
138150
focus=None,
139151
debug=False,
140152
):
141153
clean_itest_artifacts(context)
142154

155+
get_chrome_driver(context)
156+
143157
cwd = os.getcwd()
144158

145159
html2pdf_exec = f'python3 \\"{cwd}/hpdf/hpdf.py\\"'
@@ -163,7 +177,7 @@ def test_integration(
163177
run_invoke(context, itest_command)
164178

165179

166-
@task
180+
@task(aliases=["t"])
167181
def test(context):
168182
test_integration(context)
169183

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
RUN: %html2pdf %S/index.html %S/Output/index.pdf
1+
RUN: %html2pdf print %S/index.html %S/Output/index.pdf
22

33
RUN: %check_exists --file "%S/Output/index.pdf"
44
RUN: python %S/test.py
Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
RUN: %html2pdf %S/index.html %S/Output/index.pdf
1+
RUN: %html2pdf print %S/index.html %S/Output/index.pdf
22

33
RUN: %check_exists --file "%S/Output/index.pdf"
44
RUN: python %S/test.py

tests/integration/03_cache_dir_argument/test.itest

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,10 @@
1-
RUN: %html2pdf --cache-dir %S/Output/cache %S/index.html %S/Output/index.pdf | filecheck %s --dump-input=fail --check-prefix CHECK-RUN1
1+
RUN: %html2pdf print --cache-dir %S/Output/cache %S/index.html %S/Output/index.pdf | filecheck %s --dump-input=fail --check-prefix CHECK-RUN1
22
RUN: %check_exists --file "%S/Output/index.pdf"
33
RUN: python %S/test.py
44

55
CHECK-RUN1: html2pdf: ChromeDriver does not exist in the local cache:
66

7-
RUN: %html2pdf --cache-dir %S/Output/cache %S/index.html %S/Output/index.pdf | filecheck %s --dump-input=fail --check-prefix CHECK-RUN2
7+
RUN: %html2pdf print --cache-dir %S/Output/cache %S/index.html %S/Output/index.pdf | filecheck %s --dump-input=fail --check-prefix CHECK-RUN2
88
RUN: %check_exists --file "%S/Output/index.pdf"
99
RUN: python %S/test.py
1010

0 commit comments

Comments
 (0)