Tuesday 13 July 2021

Selenium print PDF in A4 format

I have the following code for printing to PDF (and it works), and I am using only Google Chrome for printing.

def send_devtools(driver, command, params=None):
    # pylint: disable=protected-access
    if params is None:
        params = {}
    resource = "/session/%s/chromium/send_command_and_get_result" % driver.session_id
    url = driver.command_executor._url + resource
    body = json.dumps({"cmd": command, "params": params})
    resp = driver.command_executor._request("POST", url, body)
    return resp.get("value")


def export_pdf(driver):
    command = "Page.printToPDF"
    params = {"format": "A4"}
    result = send_devtools(driver, command, params)
    data = result.get("data")
    return data

As we can see, I am using Page.printToPDF to print to base64, and passing "A4" as format on params paramenter.

Unfortunately this parameter seems to be being ignored. I saw some code using puppeteer using it (format A4) and I thought that could help me.

Even with hardcoded width and height (see bellow) I have no luck.

"paperWidth": 8.27,  # inches
"paperHeight": 11.69,  # inches

Using the code above, is it possible to set the page to A4 format?



from Selenium print PDF in A4 format

No comments:

Post a Comment