Skip to content

Instantly share code, notes, and snippets.

@136s
Created June 14, 2023 09:05
Show Gist options
  • Save 136s/4ea95ded6d70c039dbb4e2dbc64742fa to your computer and use it in GitHub Desktop.
Save 136s/4ea95ded6d70c039dbb4e2dbc64742fa to your computer and use it in GitHub Desktop.
A minimal working example to reproduce the margins when pdfing WikiPathways pathway maps using selenium.
import base64
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.print_page_options import PrintOptions
url = "https://example.com/"
url = "https://pathway-viewer.toolforge.org/embed/WP1"
window_width, window_height = 800, 600
chrome_options = Options()
chrome_options.add_argument("--headless")
driver = webdriver.Chrome(options=chrome_options)
driver.set_window_size(window_width, window_height)
driver.get(url)
driver.save_screenshot("screenshot.png")
cm_per_px = 2.54 / 72
print_options = PrintOptions()
print_options.background = False
print_options.page_width = window_width * cm_per_px
print_options.page_height = window_height * cm_per_px
print_options.margin_top = 0
print_options.margin_left = 0
print_options.margin_bottom = 0
print_options.margin_right = 0
with open("screenshot.pdf", mode="wb") as f:
f.write(base64.b64decode(driver.print_page(print_options)))
@136s
Copy link
Author

136s commented Jun 14, 2023

The following fix will remove the margins, but the pdf size will be 600*450.

- print_options.page_width = window_width * cm_per_px
- print_options.page_height = window_height * cm_per_px
+ print_options.page_width = window_height * cm_per_px
+ print_options.page_height = window_height**2 / window_width * cm_per_px

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment