首页 > 解决方案 > Selenium 4 + Python:如何在将网站打印为 PDF 之前压缩图像?

问题描述

出于存档目的,我们使用 Selenium 4 和 Python (linux/macOS) 创建我们网站的 PDF 目录。有时,由于 a) 未压缩的图像(就 jpeg 压缩级别而言)以及 b) 大图像(就像素尺寸而言),PDF 文件的文件大小会过大。如何在生成 PDF之前减小图像文件的大小?

(我知道,可以在创建 PDF 后对其进行压缩,但这不合适,因为整个工作流程包括合并 PDF 文件中的链接和书签)。

这是创建 PDF 的方式:

def send_devtools(driver, cmd, params={}):
    resource = "/session/%s/chromium/send_command_and_get_result" % driver.session_id
    url = driver.command_executor._url + resource
    body = json.dumps({'cmd': cmd, 'params': params})
    response = driver.command_executor._request('POST', url, body)
    if (response.get('value') is not None):
        return response.get('value')
    else:
        return None

def save_as_pdf(driver, path, options={}):
    result = send_devtools(driver, "Page.printToPDF", options)
    if (result is not None):
        with open(path, 'wb') as file:
            file.write(base64.b64decode(result['data']))
        return True
    else:
        return False

options = webdriver.ChromeOptions()
# headless setting is mandatory, otherwise saving tp pdf won't work
options.add_argument("--headless")

driver = webdriver.Chrome(executable_path='/usr/local/bin/chromedriver', options=options)
# chrome has to operate in headless mode to procuce PDF
driver.get(r'https://example.my')

send_devtools(driver, "Emulation.setEmulatedMedia", {'media': 'screen'})
pdf_options = { 'paperHeight': 22, 'paperWidth': 8, 'printBackground': True }
save_as_pdf(driver, 'myfilename.pdf', pdf_options)

标签: pythonselenium

解决方案


推荐阅读