MediaSize 不适用于 Selenium Chrome 驱动程序 打印到 PDF

MediaSize does not work for Selenium Chrome driver Print to PDF

提问人:ThoughtfulHistorian 提问时间:11/17/2023 最后编辑:ThoughtfulHistorian 更新时间:11/17/2023 访问量:34

问:

我希望它以 A2 纸尺寸打印。但输出仍然是合法的。我尝试了其他纸张尺寸,但无济于事。

Python、Selenium 和 Chrome 是最新版本。

import json
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import time

url = 'file:///C:/Users/XYZ/Downloads/page_1.html'

# Set app state
app_state = {
    "recentDestinations": [
        {
            "id": "Save as PDF",
            "origin": "local",
            "account": ""
        }
    ],
    "selectedDestinationId": "Save as PDF",
    "isCssBackgroundEnabled": True,
    "isHeaderFooterEnabled": False,
    "isLandscapeEnabled": False,
    "version": 2,
    "mediaSize": {"height_microns": 594000, "width_microns": 420000}
}
profile = {'printing.print_preview_sticky_settings.appState':json.dumps(app_state)}

#STart
chrome_options = webdriver.ChromeOptions() 
chrome_options.add_experimental_option('prefs', profile) 
chrome_options.add_argument('--kiosk-printing')

driver = webdriver.Chrome(options=chrome_options) 

driver.get(url)
time.sleep(2)
driver.execute_script('window.print();')
driver.quit()

替代版本也不起作用。"mediaSize": {"height_microns": 594000, "width_microns": 420000, "custom_display_name": "A2"}

selenium-web驱动程序

评论

0赞 ThoughtfulHistorian 11/17/2023
@KJ Mediasize 是一个字典。请参阅此链接
1赞 ThoughtfulHistorian 11/17/2023
@KJ 我通过添加样式标签来做到这一点;所以,谢谢。您上一条评论中的 mediasize 变体已经被我尝试过,但无济于事。

答:

0赞 Mahboob Nur 11/17/2023 #1

您可以尝试使用这样的 pagesize 参数

import json
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import time

url = 'file:///C:/Users/XYZ/Downloads/page_1.html'

# Set app state
app_state = {
    "recentDestinations": [
        {
            "id": "Save as PDF",
            "origin": "local",
            "account": ""
        }
    ],
    "selectedDestinationId": "Save as PDF",
    "isCssBackgroundEnabled": True,
    "isHeaderFooterEnabled": False,
    "isLandscapeEnabled": False,
    "version": 2,
    "pageSize": "A2"  # Set the pageSize directly
}
profile = {'printing.print_preview_sticky_settings.appState': json.dumps(app_state)}

chrome_options = webdriver.ChromeOptions() 
chrome_options.add_experimental_option('prefs', profile) 
chrome_options.add_argument('--kiosk-printing')

driver = webdriver.Chrome(options=chrome_options) 
driver.get(url)
time.sleep(2)
driver.execute_script('window.print();')
driver.quit()