How do i disable headers and footers Selenium Printing

Viewed 1936

Does anyone know how to disable the "headers and footers" option while printing in selenium? It's by default set to true, Anyone know how to fix this? Thank you!!!

import json
import os
from selenium import webdriver

# setting html path
htmlPath = os.getcwd() + "\\sample.html"
addr = "file:///" + htmlPath

# setting Chrome Driver
chromeOpt = webdriver.ChromeOptions()
appState = {
   "recentDestinations": [
        {
            "id": "Save as PDF",
            "origin": "local",
            "account": ""
        }
    ],
    "selectedDestinationId": "Save as PDF",
    "version": 2
}
prefs = {
    'printing.print_preview_sticky_settings.appState': json.dumps(appState)}
chromeOpt.add_experimental_option('prefs', prefs)
chromeOpt.add_argument('--kiosk-printing')
driver = webdriver.Chrome('.\\bin\\chromedriver', options=chromeOpt)

# HTML open and print
driver.get(addr)
driver.execute_script('return window.print()')```
2 Answers

Just add "isHeaderFooterEnabled": False to your appstate this below change.

appState = {
   "recentDestinations": [
        {
            "id": "Save as PDF",
            "origin": "local",
            "account": ""
        }
    ],
    "selectedDestinationId": "Save as PDF",
    "version": 2,
    "isHeaderFooterEnabled": False
}

Screenshot : commented chromeOpt.add_argument('--kiosk-printing') line just to show the de-selected option in screenshot. enter image description here

You can find the details about the chromium options on the below page

https://github.com/chromium/chromium/blob/eadef3f685cd9e96e94fcb9645b6838b6d0907a8/chrome/browser/resources/print_preview/data/model.js

enter image description here

This can be done using Selenium by following pyppeteer examples.

You will need to be able to send commands to chromium and call Page.printToPDF Devtools API as shown in the following snip:

    result = send_cmd(driver, "Page.printToPDF", params={
             'landscape': False
            ,'margin':{'top':'1cm', 'right':'1cm', 'bottom':'1cm', 'left':'1cm'}
            ,'format': 'A4'
            ,'displayHeaderFooter': False
            ,'scale': 1
    })

    with open(out_path_full, 'wb') as file:
        file.write(base64.b64decode(result['data']))

I've included a full example in my GitHub Repo with more settings that are available.

Related