【问题标题】:Python pass request headers to pdfkitPython将请求标头传递给pdfkit
【发布时间】:2016-04-21 11:37:10
【问题描述】:

我正在尝试使用 python 中的 pdfkit 将 URL 转换为 pdf,如下所示。

import pdfkit
pdfkit.from_url(url, file_path)

我想知道是否有某种方法可以将带有此 URL 的自定义请求标头(例如 X-Proxy-REMOTE-USER)传递给某些东西。

【问题讨论】:

    标签: python pdf pdf-generation webpage python-pdfkit


    【解决方案1】:

    python-pdfkit 只是wkhtmltopdf 的包装。查看usage section of the docs 中的第五个示例,您可以为其他选项指定第三个参数:

    options = {
        'page-size': 'Letter',
        'margin-top': '0.75in',
        'margin-right': '0.75in',
        'margin-bottom': '0.75in',
        'margin-left': '0.75in',
        'encoding': "UTF-8",
        'no-outline': None
    }
    
    pdfkit.from_url('http://google.com', 'out.pdf', options=options)
    

    options are specified here 和您对--custom-header <name> <value> 特别感兴趣。不幸的是,他们没有说如何传递一个带有多个参数的选项,但是由于命令行希望两者之间有一个空格并查看代码,所以他们似乎没有更改 value 参数,我尝试只传递 @ 987654330@ 和 value 作为选项的值,两者之间有一个空格。

    options = {
        'custom-header': 'X-Proxy-REMOTE-USER STEVE'
    }
    
    pdfkit.from_url('http://google.com', 'out.pdf', options=options)
    

    【讨论】:

    • 现在我收到此错误IOError: wkhtmltopdf exited with non-zero code 1. error: You need to specify at least one input file, and exactly one output file Use - for stdin or stdout
    • 您可能需要检查正在发送和接收的实际 HTTP 标头,也许在本地服务器上进行测试,然后将它们转储到磁盘。
    • @ChrisHaas,您建议的格式会导致@station 报告的错误。正确的格式是'custom-header': [('x-header-name', 'header-value')]。从这里:github.com/JazzCore/python-pdfkit/issues/45
    • 谢谢@John!在我写完这个答案 9 个月后增加了对它的支持。如果这确实是这样做的方法(看起来确实如此),那么为其编写专门的答案可能很有价值。
    猜你喜欢
    • 2013-11-23
    • 2015-06-09
    • 1970-01-01
    • 2012-11-17
    • 2013-03-08
    • 2014-09-18
    • 1970-01-01
    • 1970-01-01
    • 2018-09-21
    相关资源
    最近更新 更多