python - 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)
解决方案
推荐阅读
- python - 连续到分类二维数组
- arrays - 如何在 Pyomo 的集合数组中声明由子集索引的参数/变量?
- excel - 如何使用两个不同选项卡之间的日期正确索引匹配
- c# - 如何使用不断变化的模式处理 XML 反序列化
- corda - 在公证人签名后,发起者无法将状态提交到 vault_linear_states
- python - Spyder 无法在 Ubuntu 上的 Anaconda 中启动
- dotnetnuke - DNN 主题。如何从设置中填充 DropDownList 值?
- c++ - c ++套接字多个请求
- swift - 当 AVCaptureConnection videoOrientation 设置为纵向时,MLKit 人脸跟踪无法在视频流中找到人脸
- invantive-sql - 检索不活跃的员工