簡體   English   中英

打印頁面為 pdf selenium python

[英]Print page as pdf selenium python

如何將帶有頁眉和頁腳的網頁打印為 PDF,使其看起來像是從 google chrome 打印出來的。

到目前為止,這是我使用 PhantomJS 嘗試過的方法,但它沒有頁眉和頁腳。

from selenium import webdriver
import selenium

def execute(script, args):
    driver.execute('executePhantomScript', {'script': script, 'args' : args })

driver = webdriver.PhantomJS('phantomjs')

# hack while the python interface lags
driver.command_executor._commands['executePhantomScript'] = ('POST', '/session/$sessionId/phantom/execute')

driver.get('http://stackoverflow.com')

# set page format
# inside the execution script, webpage is "this"
pageFormat = '''this.paperSize = {format: "A4", orientation: "portrait" };'''
execute(pageFormat, [])

# render current page
render = '''this.render("test.pdf")'''
execute(render, [])

這可以通過遵循pyppeteer示例使用Selenium v4.1.3來完成。

您將需要能夠向 Chromium 發送命令並調用Page.printToPDF Devtools API,如以下片段所示:

# ...
result = send_cmd(driver, "Page.printToPDF", params={
            'landscape': True
        ,'margin':{'top':'1cm', 'right':'1cm', 'bottom':'1cm', 'left':'1cm'}
        ,'format': 'A4'
        ,'displayHeaderFooter': True
        ,'headerTemplate': '<span style="font-size:8px; margin-left: 5px">Page 1 of 1</span>'
        ,'footerTemplate': f'<span style="font-size:8px; margin-left: 5px">Generated on {datetime.now().strftime("%-m/%-d/%Y at %H:%M")}</span>'
        ,'scale': 1.65
        ,'pageRanges': '1'
})

with open(out_path_full, 'wb') as file:
    file.write(base64.b64decode(result['data']))

# ...

def send_cmd(driver, cmd, params={}):
  response = driver.command_executor._request(
     'POST'
    ,f"{driver.command_executor._url}/session/{driver.session_id}/chromium/send_command_and_get_result"
    ,json.dumps({'cmd': cmd, 'params': params}))
  if response.get('status'): raise Exception(response.get('value'))
  return response.get('value')

我在我的GitHub Repo中包含了一個完整的示例。

pdfkit可能會幫助您。 它將從html頁面呈現PDF。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM