Skip to content

Commit 113e247

Browse files
committed
Add wicked_pdf_url_base64.
Using URLs to reference images can cause a lot of problems with wkhtmltopdf, particularly when used in the header and footer. It produces errors such as "Too many open files" as well as buffer/stack overflows. A good solution to this is providing the image encoded as base64. This helper method takes a URL of an image, opens the URL, reads the image data and encodes it to base64. If the URL does not have a successful response (`response.is_a?(Net::HTTPSuccess) == false`), it will log a warning and return `nil`. We could optionally make this raise but that should be a project-wide change. TODO: - [ ] Better placement (since this is not technically part of the asset pipeline)? - [ ] Better naming? - [ ] Tests.
1 parent ee6a5e1 commit 113e247

File tree

1 file changed

+14
-0
lines changed

1 file changed

+14
-0
lines changed

lib/wicked_pdf/wicked_pdf_helper/assets.rb

+14
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,20 @@ def wicked_pdf_asset_base64(path)
1515
"data:#{asset.content_type};base64,#{Rack::Utils.escape(base64)}"
1616
end
1717

18+
# Using `image_tag` with URLs when generating PDFs (specifically large PDFs with lots of pages) can cause buffer/stack overflows.
19+
#
20+
def wicked_pdf_url_base64(url)
21+
response = Net::HTTP.get_response(URI(url))
22+
23+
if response.is_a?(Net::HTTPSuccess)
24+
base64 = Base64.encode64(response.body).gsub(/\s+/, '')
25+
"data:#{response.content_type};base64,#{Rack::Utils.escape(base64)}"
26+
else
27+
Rails.logger.warn("[wicked_pdf] #{response.code} #{response.message}: #{url}")
28+
nil
29+
end
30+
end
31+
1832
def wicked_pdf_stylesheet_link_tag(*sources)
1933
stylesheet_contents = sources.collect do |source|
2034
source = WickedPdfHelper.add_extension(source, 'css')

0 commit comments

Comments
 (0)