Pass cookies at the renderer boundary. Ruby libraries such as PDFKit and Wicked PDF do not render HTML themselves; they start wkhtmltopdf. Give that process the cookie values it needs, or point it at a cookie-jar file. Use inline cookies for one conversion with a small, known set of values, and a jar when authentication must persist across several pages or runs.
How cookie handling works in a Ruby PDF conversion
When a Ruby application converts a URL to PDF with PDFKit or Wicked PDF, the request chain is:
- Ruby creates or obtains authentication state, usually through an HTTP client or Rails session.
- The wrapper builds a
wkhtmltopdfcommand. - The separate renderer requests the target URL and its assets.
wkhtmltopdfsends cookies supplied as command-line options or loaded from a jar.
A cookie stored in your Rails process is not automatically visible to the renderer. The renderer is a separate process, so it must receive the cookie name, value, domain-compatible URL, and any required jar explicitly.
Choose inline cookies or a cookie jar
| Method | Best for | Ruby shape | Trade-off |
|---|---|---|---|
| Inline cookie | One page or a small, known set of values | PDFKit hash; Wicked PDF name/value array | Easy to audit, but you must pass every value on each conversion |
| Cookie jar | Several pages, redirects, or state that must persist between loads | Pass a file path through the underlying renderer | Convenient persistence, but the file contains bearer credentials and needs strict permissions |
Cookie scope still applies. The target URL must match the cookie’s domain and path; a Secure cookie requires HTTPS. A cookie copied from a browser for one host may not authenticate a different subdomain.
Recommended Free Tools
#1 Best Overall
PDFKit: pass cookies as a hash
PDFKit wraps wkhtmltopdf and accepts a cookie hash. The following converts an authenticated account page:
require 'pdfkit'
url = 'https://example.test/account'
kit = PDFKit.new(
url,
cookie: { session_id: 'REDACTED_SESSION_VALUE' }
)
pdf = kit.to_pdf
File.binwrite('account.pdf', pdf)
For more than one cookie, add more hash entries:
kit = PDFKit.new(
'https://example.test/account',
cookie: {
session_id: 'REDACTED_SESSION_VALUE',
csrf_token: 'REDACTED_CSRF_VALUE'
}
)
File.binwrite('account.pdf', kit.to_pdf)
PDFKit’s README documents this hash form and lists Ruby 2.5, 2.6, 2.7, 3.0 and 3.1 in its supported-version section. Confirm your installed gem and renderer versions separately; the wrapper’s support statement does not guarantee that every application dependency supports the same Ruby release.
Obtaining a cookie in Ruby
Authenticate with your normal HTTP client, then pass only the values needed by the target host. Do not log the response headers or cookie value.
require 'net/http'
require 'uri'
require 'pdfkit'
login_uri = URI('https://example.test/login')
http = Net::HTTP.new(login_uri.host, login_uri.port)
http.use_ssl = true
response = http.post(
login_uri.request_uri,
URI.encode_www_form(email: ENV.fetch('PDF_USER'), password: ENV.fetch('PDF_PASSWORD')),
'Content-Type' => 'application/x-www-form-urlencoded'
)
set_cookie = response['set-cookie']
raise 'Authentication did not return a cookie' unless set_cookie
session_id = set_cookie[/Asession_id=([^;]+)/, 1]
raise 'Session cookie was not found' unless session_id
kit = PDFKit.new(
'https://example.test/account',
cookie: { session_id: session_id }
)
File.binwrite('account.pdf', kit.to_pdf)
Production authentication often involves redirects, CSRF tokens, OAuth, or multiple Set-Cookie headers. Use your application’s established client and cookie parser rather than assuming a single regular expression is sufficient.
What’s actually slowing this PC down?
Pick the symptom - the matching free tool is one click away.
Wicked PDF: pass a name/value array
Wicked PDF exposes the cookie option in its Rails render call. Its documented format is an array containing a cookie name, a space, and its value:
# In a controller action or render call
render pdf: 'account', cookie: ['session_id REDACTED_SESSION_VALUE']
Several cookies can be supplied as separate array elements:
Rank #2
render pdf: 'account', cookie: [
'session_id REDACTED_SESSION_VALUE',
'feature_flag enabled'
]
Wicked PDF runs wkhtmltopdf outside the Rails application. Ensure the renderer can resolve the URL and every stylesheet, image, font, and script referenced by the page. Prefer absolute HTTPS asset URLs when the PDF process cannot access Rails’ internal hostnames.
Passing options from a Rails view
Keep authentication state short-lived and provide it only for the render that needs it:
The Tool Desk
Outbyte Driver Updater FREEFix the driver behind crashes, sound loss and screen glitchesFind Drivers →Outbyte PC Repair FREEClear out junk files and repair common Windows errorsFree Scan →def account_pdf
session_value = current_user.pdf_session_cookie
render pdf: 'account',
template: 'accounts/show',
cookie: ["session_id #{session_value}"],
javascript_delay: 1000
end
The delay gives client-side code time to run; it does not repair an invalid cookie or an unreachable asset.
Use wkhtmltopdf directly
For debugging, or when a wrapper does not expose an option you need, call the renderer directly:
wkhtmltopdf --cookie session_id REDACTED_SESSION_VALUE
https://example.test/account account.pdf
--cookie is repeatable:
wkhtmltopdf
--cookie session_id REDACTED_SESSION_VALUE
--cookie feature_flag enabled
https://example.test/account account.pdf
To read and write persistent state, use a jar:
wkhtmltopdf --cookie-jar /secure/path/cookies.txt
https://example.test/account account.pdf
The corresponding library setting is named load.cookieJar. A jar can be useful when the first page sets a session cookie that later pages must reuse.
Create and protect a jar
install -m 600 /dev/null /secure/path/cookies.txt
# Populate the jar through your authenticated workflow, then render:
wkhtmltopdf --cookie-jar /secure/path/cookies.txt
https://example.test/account account.pdf
rm -f /secure/path/cookies.txt
Restrict ownership and permissions, avoid committing the file, and delete temporary jars after the job. Treat the file as a bearer credential: anyone who can read it may be able to act as the user until the cookies expire or are revoked.
Rank #3
Authentication and cookie-scope checklist
- Host: use the same registrable domain and subdomain covered by the cookie’s Domain attribute.
- Path: a cookie limited to
/appwill not be sent to an unrelated path. - Protocol: Secure cookies require HTTPS.
- Expiry: an expired session cannot be revived by copying its old value.
- SameSite: redirects or cross-site requests may change whether a browser would send the cookie; test the renderer’s actual navigation.
- Assets: authentication may be needed for images, CSS, fonts, and API calls as well as the initial HTML.
- Redirects: verify that the final URL remains within the cookie’s scope.
JavaScript pages and rendering timing
Cookies only establish state; they do not guarantee that the page is finished. If content is inserted by JavaScript, allow enough execution time with the wrapper’s delay option or the equivalent wkhtmltopdf setting. Diagnose the two layers separately:
- Request the URL with the cookie and verify that the server returns authenticated HTML.
- Run
wkhtmltopdfagainst that URL and inspect whether scripts, fonts, and images load. - Increase the delay only after network access and cookie scope are confirmed.
A blank PDF after a successful authenticated response usually indicates a renderer, JavaScript, or asset problem rather than a missing cookie.
Security and version boundaries
The stable wkhtmltopdf 0.12.6 series was released in June 2020. Pin and patch the binary deliberately in your deployment; a Ruby gem upgrade does not necessarily upgrade the executable.
The wkhtmltopdf project warns: “Do not use wkhtmltopdf with any untrusted HTML.” Sanitize user-supplied HTML and JavaScript before rendering. A page can execute scripts with access to the renderer’s network environment, and cookies passed to the process can expose privileged accounts.
Wicked PDF’s README says it has been verified with Ruby 2.2 through 3.2 and Rails 4 through 7.0. These are project statements, not a guarantee for every operating-system package or patched binary.
PDFKit versus Wicked PDF
| Question | PDFKit | Wicked PDF |
|---|---|---|
| Integration layer | Plain Ruby wrapper | Rails-oriented rendering integration |
| Cookie API | cookie: { name: value } |
cookie: ['name value'] |
| Underlying engine | wkhtmltopdf |
wkhtmltopdf |
| Raw flag control | Use PDFKit options or invoke the binary directly | Use Wicked PDF options or invoke the binary directly |
| Best fit | A Ruby service or script needing a small, explicit option set | A Rails controller, view, and response pipeline |
Choose based on your integration layer, not on different browser behavior: both ultimately depend on the same renderer’s cookie semantics.
Rank #4
Troubleshooting cookie-based PDFs
Login page appears instead of the account page
The cookie was not sent, is expired, or does not match the host/path. Confirm the exact cookie name and value, use the final HTTPS URL, and test with one inline cookie before introducing a jar.
Only some images or styles are missing
Those asset requests may require their own authentication or may use relative URLs unavailable to the renderer. Change assets to reachable absolute URLs and provide the required cookie scope.
The cookie works in a browser but not in PDFKit
Browser extensions, local storage, JavaScript login flows, or anti-bot checks may be involved. Export the server cookie actually created by authentication, then pass it explicitly; local-storage tokens are not cookies.
Wicked PDF raises an option or command error
Check the generated command and the installed binary path. Confirm the array format is exactly 'name value', with no accidental newline or shell quoting characters.
A cookie jar leaks between users
Never use one shared writable jar for concurrent jobs. Create a per-job file with mode 600, pass it to that job only, and remove it in an ensure/finally cleanup block.
Conversion hangs or times out
Check DNS, firewall rules, certificate validation, redirects, and JavaScript requests from the renderer host. A longer JavaScript delay cannot fix a blocked network connection.
Quick wins for a faster PC:
Scan for outdated or missing drivers - takes under a minuteDriver Scan →Repair Windows errors before they cause bigger problemsFix Now →Fix the driver behind crashes, sound loss and screen glitchesFind Drivers →Best Value
Or skip the browser setup
For a hosted capture rather than a local Ruby renderer, ScreenshotNeo accepts a URL and returns a PDF through one request. It removes cookie-consent banners, newsletter popups, and chat widgets before capture; bot checks, blank pages, failed loads, timeouts, and cache hits are not billed. Its MCP server provides take_screenshot, get_page_info, and capture_pdf tools for Claude, Cursor, and other MCP clients. Every plan includes the features, with 1,000 screenshots per month free without a card and paid plans starting at $5 for 3,000 shots.
See the ScreenshotNeo API documentation for options such as cookies, custom headers, JavaScript, waiting conditions, PDF page ranges, and signed webhooks.
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
Use the same endpoint from Ruby when you want your application to remain in control of the request:
require 'net/http'
require 'uri'
uri = URI('https://api.screenshotneo.com/v1/shot')
uri.query = URI.encode_www_form(
access_key: ENV.fetch('SCREENSHOTNEO_KEY'),
url: 'https://stripe.com'
)
response = Net::HTTP.get_response(uri)
raise "Screenshot failed: #{response.code}" unless response.is_a?(Net::HTTPSuccess)
File.binwrite('shot.webp', response.body)
Start with the free ScreenshotNeo account: 1,000 screenshots each month, no card required.
Crashes, No Sound, or Screen Glitches?
Random freezes, missing sound and display glitches usually trace back to one bad driver. Find and replace yours safely.Free scan · under a minutePC Slower Than It Used to Be?
A free scan shows the junk files, broken settings and background clutter dragging Windows down - then fixes them in one click.Free scan · Windows 10 & 11FAQ
Can I pass a Rails session object directly to wkhtmltopdf?
No. Convert the relevant session state into cookie name/value pairs or a cookie jar that the separate renderer can read.
Should I use a jar for every conversion?
No. Inline cookies are easier to audit for a single request. Use a protected jar when state must persist across pages or conversions.
Does changing PDFKit to Wicked PDF change cookie behavior?
No. Their option syntax differs, but both delegate page loading to wkhtmltopdf.
Frequently Asked Questions
Can I pass a Rails session object directly to wkhtmltopdf?
No. Convert the relevant session state into cookie name/value pairs or a cookie jar that the separate renderer can read.
Free tools Windows power users keep installed
One-click scans. No signup required.
Should I use a jar for every conversion?
No. Inline cookies are easier to audit for a single request. Use a protected jar when state must persist across pages or conversions.
Does changing PDFKit to Wicked PDF change cookie behavior?
No. Their option syntax differs, but both delegate page loading to wkhtmltopdf.
Quick Recap
Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

