首页 > 解决方案 > 使用 python 在 Chrome 中将 HTML 文件另存为 PDF 时,页面大小规范不起作用

问题描述

我想在Chrome上打开一个HTML文件并将其保存为PDF,我使用python编写了以下代码,但即使我将代码中appState中的“pageSize”设置为A3,A5,字母大小或其他大小,页面输出 PDF 文件的大小将始终为 A4。

如果我在 appState 中更改其他属性“isLandscapeEnabled”或“isHeaderFooterEnabled”的值,则效果很好。因此,似乎“pageSize”属性不起作用。

而且,我发现当控制面板->区域->格式(F)设置为日本时,输出PDF文件的页面大小将始终为A4,如果我将其设置为美国,则始终为字母大小. 所以,我认为“pageSize”总是由默认值设置。

我是一个python初学者,我还不太明白。我的代码有问题吗?

请给我任何建议。

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import json
import time

def PrintSetUp():
    chopt=webdriver.ChromeOptions()
    appState = {
        "recentDestinations": [
            {
                "id": "Save as PDF",
                "origin": "local",
                "account":""
            }
        ],
        "selectedDestinationId": "Save as PDF",
        "version": 2,
        "isLandscapeEnabled": False,
        "pageSize": 'A3', 
        "marginsType": 0,
        "scalingType": 3 , 
        "scaling": "100" ,
        "isHeaderFooterEnabled": False, #ヘッダーとフッター
        "isCssBackgroundEnabled": True, #背景のグラフィック
    }
    
    prefs = {'printing.print_preview_sticky_settings.appState':
             json.dumps(appState),
             "download.default_directory": "~/Downloads"
             }
    chopt.add_experimental_option('prefs', prefs)
    chopt.add_argument('--kiosk-printing')
    return chopt

def main_WebToPDF(BlogURL):
    chopt = PrintSetUp()
    driver_path = "C:/Work/pythonTest/Ver94/chromedriver_win32/chromedriver.exe" #webdriverのパス
    driver = webdriver.Chrome(executable_path=driver_path, options=chopt)
    driver.implicitly_wait(10) # 秒 暗示的待機 
    driver.get(BlogURL) #ブログのURL 読み込み
    WebDriverWait(driver, 15).until(EC.presence_of_all_elements_located)  # ページ上のすべての要素が読み込まれるまで待機(15秒でタイムアウト判定)
    driver.execute_script('return window.print()') #Print as PDF
    time.sleep(10) #ファイルのダウンロードのために10秒待機
    driver.quit() #Close Screen
    
if __name__ == '__main__':
    BlogURLList=["file://C:/Work/pythonTest/1_pdf.html",
                 "file://C:/Work/pythonTest/2_pdf.html",
                 "file://C:/Work/pythonTest/3_pdf.html"]
    for BlogURL in  BlogURLList:
        main_WebToPDF(BlogURL)

标签: pythonhtmlpdfselenium-chromedriver

解决方案


推荐阅读