2

I am trying to convert a URL to pdf using pdfkit in python as follows.

import pdfkit
pdfkit.from_url(url, file_path)

I wanted to know is there some way to pass custom request headers with this URL such as X-Proxy-REMOTE-USER to something.

station
  • 6,715
  • 14
  • 55
  • 89

1 Answers1

1

python-pdfkit is just a wrapper around wkhtmltopdf. Looking at the fifth example from the usage section of the docs there's a third parameter that you can specify for additional options:

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)

The options are specified here and you are specifically interest in --custom-header <name> <value>. Unfortunately they don't say how to pass an option that takes multiple parameters but since the command line wants a space between the two and looking at the code they don't appear to be changing the value parameter I'd try just passing the name and value as the value of the option with a space between the two.

options = {
    'custom-header': 'X-Proxy-REMOTE-USER STEVE'
}

pdfkit.from_url('http://google.com', 'out.pdf', options=options)
Chris Haas
  • 53,986
  • 12
  • 141
  • 274
  • Now I get this error `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` – station Jan 18 '16 at 14:54
  • You might need to inspect the actual HTTP headers that are being sent and received, maybe test on a local server and just dump them to disk. – Chris Haas Jan 18 '16 at 15:21
  • @ChrisHaas, the format you suggest results in the error reported by @station. The correct format is `'custom-header': [('x-header-name', 'header-value')]`. From here: https://github.com/JazzCore/python-pdfkit/issues/45 – John Feb 08 '21 at 17:41
  • Thanks @John! Support for that was added 9 months after I wrote this answer. If that is indeed the way to do it (which it definitely looks like it is) it might be valuable to have a dedicated answer written for it. – Chris Haas Feb 08 '21 at 17:53