python - 使用 python 在 Chrome 中将 HTML 文件另存为 PDF 时,页面大小规范不起作用
问题描述
我想在Chrome上打开一个HTML文件并将其保存为PDF,我使用python编写了以下代码,但即使我将代码中appState中的“pageSize”设置为A3,A5,字母大小或其他大小,页面输出 PDF 文件的大小将始终为 A4。
如果我在 appState 中更改其他属性“isLandscapeEnabled”或“isHeaderFooterEnabled”的值,则效果很好。因此,似乎“pageSize”属性不起作用。
而且,我发现当控制面板->区域->格式(F)设置为日本时,输出PDF文件的页面大小将始终为A4,如果我将其设置为美国,则始终为字母大小. 所以,我认为“pageSize”总是由默认值设置。
我是一个python初学者,我还不太明白。我的代码有问题吗?
请给我任何建议。
- 蟒蛇 3.9.6
- 硒 3.141.0
- 铬 94.0.4606.71
- ChromeDriver 94.0.4606.61
- 窗户10
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)
解决方案
推荐阅读
- c++ - 声明一个空的析构函数会阻止编译器调用 memmove() 来复制连续的对象
- r - 如何在 R Shiny 应用程序中下载 PowerPoint 文件?
- google-calendar-api - 在 webforms 应用程序中使用 ASP.NET C# 在我的日历上添加/更新事件
- iar - IAR是否兼容Win10
- javascript - 获取 html 文件而不是获取 json 并创建 html 会很糟糕吗?为什么?
- macos - 在 macos 10.13.6 上安装 Bazel 0.16.1 时权限被拒绝
- apache-spark - Spark 中的迭代 RDD/Dataframe 处理
- javascript - 路由器 click.native 在 Vue 中传递了错误的参数
- r - 无法让 R 读取 GPS 坐标
- firebase - Http 请求在 Google 助理的 Firebase webhook 中不起作用