Skip to content

Instantly share code, notes, and snippets.

@costa
Created October 1, 2021 19:20
Show Gist options
  • Save costa/82dd49e370e0185b462e80c48a728bb4 to your computer and use it in GitHub Desktop.
Save costa/82dd49e370e0185b462e80c48a728bb4 to your computer and use it in GitHub Desktop.
Workaround setup for: https://github.com/mileszs/wicked_pdf/issues/860 (see my comment there)
# ./config/initializers/wicked_pdf.rb
WICKED_PDF_HELPER_SERVER_PORT = 28601 # NOTE no reason
WickedPdf.config = {
# Layout file to be used for all PDFs
# (but can be overridden in `render :pdf` calls)
# layout: 'pdf.html',
}.tap do |config|
rack_up = caller.map(&:to_s).grep(/rack.*server/i).any? # SEE https://stackoverflow.com/a/49598328/714287
if rack_up && Rails.configuration.asset_host.blank?
# NOTE otherwise, all the assets/packs will just load from `...asset_host`
# NOTE we rely on another process with wh2p anyway, so this checks out
spawn Rails.root.join(
'app/assets/helpers/wkhtmltopdf_asset_pack_locating_server'
).to_s, '-p', WICKED_PDF_HELPER_SERVER_PORT.to_s,
chdir: Dir.tmpdir
# NOTE this requires the rails server to support concurrent requests
class WickedPdf
def pdf_from_html_file(filepath, options)
pdf_from_url("http://localhost:#{WICKED_PDF_HELPER_SERVER_PORT}#{filepath}", options)
end
end
# SEE https://github.com/mileszs/wicked_pdf/issues/779#issuecomment-932406821 : config[:disable_smart_shrinking] = true
ENV['XDG_RUNTIME_DIR'] = '/tmp/runtime-root' # NOTE (default) stupid wkhtmltopdf
config[:log_level] = :warn
config[:raise_on_all_errors] = true
else
config[:enable_local_file_access] = true
end
end
#!/usr/bin/env ruby
# ./app/assets/helpers/wkhtmltopdf_asset_pack_locating_server
require 'net/http'
require 'uri'
require 'sinatra'
# NOTE the whole setup is only useful if the assets are served by
# the web app server (which runs on the local port 80)
ASSET_PACK_SVC_URI = 'http://localhost'
get '*' do |path_s|
if path_s.end_with? '.html'
content_type 'text/html'
File.read path_s
else
asset_pack_url = "#{ASSET_PACK_SVC_URI}#{path_s}"
begin
res = Net::HTTP.get_response(URI.parse asset_pack_url)
content_type res.content_type
status res.code
res.body
rescue Net::ReadTimeout
502
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment