html2pdf-rails 0.6.0 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 0f36633c9696c0a36149bf8037f20cfcb2c6df4c7d81bbfc5352954126d594e6
4
- data.tar.gz: a4ae4281240e6bd471fe2f1cdbb99a8b027b3be33d85fb109d05f1855df80002
3
+ metadata.gz: fdb4c6c41f2cf9c0b780aba5dbdecc3c47b658a79241247746b8be48a0b4c947
4
+ data.tar.gz: 3b2dc888c30b92815dbf2834bfb6d9ec48f035a10e97870251ee2b4614f54b2b
5
5
  SHA512:
6
- metadata.gz: 17f3d2b6d2ccf67e17c0975f7c5fa8cb6b1ddc667af0ac72a2e7675d60da987fc1e82a8c2f3c9ce7d73dd6a32c54e64ff8f5f49b99e7399e4617594e5e358af5
7
- data.tar.gz: 8faccbadc668806d4c57209c5a374fc57709169f8999802ce907464c841ea9990733e33ae5b822b12c112a605ed88b038def6eea42bdfe223a2e99c0082b5fda
6
+ metadata.gz: 2fd542442975af190846df080ea2a55a5c5d7cb883774f0a75fe5f1aa48804cb1468002a6acb9cbe51084e3a263eac3f3e1167fcc492ea0133bcbea0225542ae
7
+ data.tar.gz: 0db1aef20b4907f76d404fac2331c9588d2b6ab0e9b8c850b446684cf712607097e4b644b9955acefdf4f67972adb56dd812947a36db83e1e1df7bcf8ed7539b
data/README.md CHANGED
@@ -61,6 +61,40 @@ You can get signed url of Cloud Storage if your Cloud Funciton code support it.
61
61
  redirect_to pdf_url
62
62
  ```
63
63
 
64
+ ### Attach PDF to an email (ActionMailer)
65
+
66
+ `render_to_pdf_string` is available in all mailers. It renders a template, converts it to PDF, and returns the PDF binary.
67
+
68
+ ```ruby
69
+ class OrderMailer < ApplicationMailer
70
+ def receipt(order)
71
+ @order = order
72
+ attachments['receipt.pdf'] = render_to_pdf_string
73
+ mail(to: order.user.email)
74
+ end
75
+ end
76
+ ```
77
+
78
+ By default, the template is inferred from `<mailer_name>/<action_name>` and `formats: [:pdf]` is used. So the example above renders `order_mailer/receipt.pdf.erb`. You can override these defaults:
79
+
80
+ ```ruby
81
+ attachments['receipt.pdf'] = render_to_pdf_string(
82
+ template: 'order_mailer/receipt_pdf',
83
+ layout: 'pdf',
84
+ pdf_options: { margin: { top: '30px' } }
85
+ )
86
+ ```
87
+
88
+ ### Generate PDF from arbitrary HTML
89
+
90
+ If you already have an HTML string (for example, in a background job or PORO), use the low-level API:
91
+
92
+ ```ruby
93
+ html = ApplicationController.render(template: 'invoices/show', assigns: { invoice: invoice })
94
+ pdf = Html2Pdf::Rails.generate(html: html, pdf_options: { margin: { top: '30px' } })
95
+ File.binwrite('invoice.pdf', pdf)
96
+ ```
97
+
64
98
  ### Advanced Usage with all available options
65
99
 
66
100
  ```ruby
@@ -132,6 +166,46 @@ Html2Pdf.configure do |config|
132
166
  end
133
167
  ```
134
168
 
169
+ ### API key
170
+
171
+ If your endpoint requires an API key, set `api_key`. It is sent as `Authorization: Bearer <api_key>`.
172
+ When `api_key` is not set, `ENV['HTML2PDF_API_KEY']` is used, so in most cases you only need to set the environment variable.
173
+ Surrounding whitespace (such as a trailing newline) is removed, and a blank `api_key` (`nil`, `''` or only whitespace) is treated as not set.
174
+ A key that contains whitespace raises `Html2Pdf::Rails::InvalidApiKeyError` before any request is sent; the key itself is not included in the message.
175
+
176
+ ```ruby
177
+ Html2Pdf.configure do |config|
178
+ config.endpoint = 'YOUR_HTTP_TRIGGER_ENDPOINT'
179
+ config.api_key = Rails.application.credentials.html2pdf_api_key # optional; defaults to ENV['HTML2PDF_API_KEY']
180
+ end
181
+ ```
182
+
183
+ If the endpoint rejects the key (HTTP 401), `Html2Pdf::Rails::UnauthorizedError` (a subclass of `Html2Pdf::Rails::RequestError`) is raised. It is not retried.
184
+
185
+ ### `html2pdf_base_tag` in mailers / jobs
186
+
187
+ `html2pdf_base_tag` resolves the base URL in this order (matches Rails `url_for`):
188
+
189
+ 1. Explicit `host:` / `protocol:` argument
190
+ 2. `HTTP_X_ORIGINAL_HOST` request header (host only, for Ngrok-style proxying)
191
+ 3. View-context `url_options[:host]` / `[:protocol]`:
192
+ - In a controller view: `config.action_controller.default_url_options` merged over `request.host` / `request.protocol` (config wins, request as fallback — same behavior as Rails `url_for`)
193
+ - In a mailer view: `config.action_mailer.default_url_options`
194
+ 4. `Rails.application.routes.default_url_options[:host]` / `[:protocol]` (final fallback)
195
+
196
+ Most Rails apps already configure `config.action_mailer.default_url_options` for mailer URL helpers, so no extra setup is usually required:
197
+
198
+ ```ruby
199
+ # config/environments/production.rb
200
+ config.action_mailer.default_url_options = { host: 'example.com', protocol: 'https' }
201
+ ```
202
+
203
+ If you want to override per-call (e.g. multi-tenant), pass arguments:
204
+
205
+ ```erb
206
+ <%= html2pdf_base_tag host: 'tenant.example.com', protocol: 'https' %>
207
+ ```
208
+
135
209
  ## Contributing
136
210
 
137
211
  Bug reports and pull requests are welcome on GitHub at https://github.com/SonicGarden/html2pdf-rails. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [Contributor Covenant](http://contributor-covenant.org) code of conduct.
@@ -0,0 +1,21 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'html2pdf/rails/errors'
4
+
5
+ module Html2Pdf
6
+ module Rails
7
+ module ApiKey
8
+ # Returns the key with surrounding whitespace removed, or nil when it is blank
9
+ # (nil, '' or only whitespace), so that callers can treat blank as "not set".
10
+ def self.normalize(value)
11
+ key = value.to_s.strip
12
+ return nil if key.empty?
13
+ # NOTE: Never include the key in the message. Net::HTTP would otherwise raise its own
14
+ # ArgumentError for a CR/LF inside the header value, and that message contains the value.
15
+ raise InvalidApiKeyError, 'html2pdf api_key must not contain whitespace' if key.match?(/\s/)
16
+
17
+ key
18
+ end
19
+ end
20
+ end
21
+ end
@@ -1,17 +1,19 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  require 'html2pdf/rails/errors'
4
+ require 'html2pdf/rails/api_key'
4
5
 
5
6
  module Html2Pdf
6
7
  module Rails
7
8
  class Client
8
9
  def self.post(**options)
9
- self.new(Html2Pdf.config.endpoint, Html2Pdf.config.app).post(**options)
10
+ self.new(Html2Pdf.config.endpoint, Html2Pdf.config.app, api_key: Html2Pdf.config.api_key).post(**options)
10
11
  end
11
12
 
12
- def initialize(endpoint, app)
13
+ def initialize(endpoint, app, api_key: nil)
13
14
  @uri = URI.parse(endpoint)
14
15
  @app = app
16
+ @api_key = Html2Pdf::Rails::ApiKey.normalize(api_key)
15
17
  end
16
18
 
17
19
  def post(html:, put_to_storage: false, file_name: nil, disposition: nil, pdf_options: {})
@@ -30,6 +32,8 @@ module Html2Pdf
30
32
  case response.code
31
33
  when '200'
32
34
  response.body
35
+ when '401'
36
+ raise Html2Pdf::Rails::UnauthorizedError.new(response)
33
37
  when '503'
34
38
  raise Html2Pdf::Rails::ServiceUnavailableError.new(response)
35
39
  else
@@ -42,7 +46,9 @@ module Html2Pdf
42
46
  private
43
47
 
44
48
  def headers
45
- { 'Content-Type' => 'application/json' }
49
+ headers = { 'Content-Type' => 'application/json' }
50
+ headers['Authorization'] = "Bearer #{@api_key}" if @api_key
51
+ headers
46
52
  end
47
53
  end
48
54
  end
@@ -3,6 +3,10 @@ module Html2Pdf
3
3
  class NetworkError < StandardError
4
4
  end
5
5
 
6
+ # Raised when the configured API key cannot be sent as a header value.
7
+ class InvalidApiKeyError < ArgumentError
8
+ end
9
+
6
10
  class RequestError < StandardError
7
11
  attr_reader :response
8
12
 
@@ -15,5 +19,14 @@ module Html2Pdf
15
19
 
16
20
  class ServiceUnavailableError < RequestError
17
21
  end
22
+
23
+ # Raised on HTTP 401. Not retried, because sending the same API key again cannot succeed.
24
+ class UnauthorizedError < RequestError
25
+ def initialize(response, msg = nil)
26
+ msg ||= 'html2pdf request was rejected with HTTP status 401. ' \
27
+ 'Check that Html2Pdf.config.api_key (or ENV["HTML2PDF_API_KEY"]) is set to a valid key.'
28
+ super(response, msg)
29
+ end
30
+ end
18
31
  end
19
32
  end
@@ -3,11 +3,64 @@
3
3
  module Html2Pdf
4
4
  module Rails
5
5
  module Helper
6
- def html2pdf_base_tag
7
- # NOTE: for Ngrok
8
- host = request.headers['HTTP_X_ORIGINAL_HOST'] || request.host
9
- base_url = "#{request.protocol}#{host}"
10
- tag.base href: base_url
6
+ # Resolves the base URL in the same order as Rails' `url_for`, with one
7
+ # gem-specific addition (HTTP_X_ORIGINAL_HOST). See `_html2pdf_default_url_options`
8
+ # for the source of `options`.
9
+ def html2pdf_base_tag(host: nil, protocol: nil)
10
+ req = _html2pdf_request
11
+ options = _html2pdf_default_url_options
12
+
13
+ # HTTP_X_ORIGINAL_HOST overrides options because dev tunneling (Ngrok) sets
14
+ # this header to the externally-visible host that puppeteer must reach,
15
+ # which doesn't match request.host or any configured default.
16
+ host ||= req && req.headers['HTTP_X_ORIGINAL_HOST']
17
+ host ||= options[:host]
18
+ if host.blank?
19
+ raise ArgumentError,
20
+ 'html2pdf_base_tag: host is not available. Pass `host:` or configure default_url_options (e.g. config.action_mailer.default_url_options).'
21
+ end
22
+
23
+ # options[:protocol] from controller's url_options is "https://" (with trailing
24
+ # "://" — request.protocol convention), while config and mailer values are
25
+ # bare "https". Normalize.
26
+ protocol ||= options[:protocol]&.to_s&.delete_suffix('://')
27
+ protocol ||= 'https'
28
+
29
+ tag.base href: "#{protocol}://#{host}"
30
+ end
31
+
32
+ private
33
+
34
+ def _html2pdf_request
35
+ respond_to?(:request) ? request : nil
36
+ end
37
+
38
+ # Mirrors how Rails' `url_for` resolves URL options, so this helper produces
39
+ # the same host/protocol as `url_for` would in the same context.
40
+ #
41
+ # `view.url_options` delegates to `controller.url_options`:
42
+ # https://github.com/rails/rails/blob/v8.1.2/actionview/lib/action_view/routing_url_for.rb#L124
43
+ #
44
+ # In a controller this returns
45
+ # `{ host: request.host, protocol: request.protocol, ... }.merge!(super)`:
46
+ # https://github.com/rails/rails/blob/v8.1.2/actionpack/lib/action_controller/metal/url_for.rb#L37
47
+ # `merge!` lets class-level `default_url_options` win over request info.
48
+ # In a mailer it returns the class-level `default_url_options` directly
49
+ # (no request to merge in).
50
+ #
51
+ # `RouteSet#url_for` then does `default_url_options.merge(options)`, so
52
+ # routes' default is the base under everything else. We replicate that here:
53
+ # https://github.com/rails/rails/blob/v8.1.2/actionpack/lib/action_dispatch/routing/route_set.rb#L856
54
+ #
55
+ # Note: `config.action_mailer.default_url_options` and
56
+ # `config.action_controller.default_url_options` populate the *class*
57
+ # `default_url_options`, NOT `Rails.application.routes.default_url_options` —
58
+ # they are three separate hashes. Reading only the routes hash would miss the
59
+ # typical mailer setup.
60
+ def _html2pdf_default_url_options
61
+ routes_options = ::Rails.application&.routes&.default_url_options || {}
62
+ context_options = respond_to?(:url_options) ? url_options : {}
63
+ routes_options.merge(context_options)
11
64
  end
12
65
  end
13
66
  end
@@ -0,0 +1,16 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Html2Pdf
4
+ module Rails
5
+ module MailerRendering
6
+ def render_to_pdf_string(template: nil, layout: false, formats: [:pdf], handlers: nil, pdf_options: {})
7
+ # When :template is omitted, Rails resolves the template from `_prefixes`
8
+ # (= [mailer_name]) and `action_name` via `_process_render_template_options`:
9
+ # https://github.com/rails/rails/blob/v8.1.2/actionview/lib/action_view/rendering.rb#L177
10
+ render_opts = { template: template, layout: layout, formats: formats, handlers: handlers }.compact
11
+ html = render_to_string(**render_opts)
12
+ Html2Pdf::Rails.generate(html: html, pdf_options: pdf_options)
13
+ end
14
+ end
15
+ end
16
+ end
@@ -2,6 +2,7 @@
2
2
 
3
3
  require 'rails'
4
4
  require 'html2pdf/rails/rendering'
5
+ require 'html2pdf/rails/mailer_rendering'
5
6
  require 'html2pdf/rails/helper'
6
7
 
7
8
  module Html2Pdf
@@ -11,6 +12,10 @@ module Html2Pdf
11
12
  ActionController::Base.prepend Rendering
12
13
  end
13
14
 
15
+ ActiveSupport.on_load(:action_mailer) do
16
+ ActionMailer::Base.include MailerRendering
17
+ end
18
+
14
19
  ActiveSupport.on_load(:action_view) do
15
20
  ActionView::Base.include Helper
16
21
  end
@@ -1,8 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
- require 'retryable'
4
- require 'html2pdf/rails/client'
5
-
6
3
  module Html2Pdf
7
4
  module Rails
8
5
  module Rendering
@@ -28,9 +25,15 @@ module Html2Pdf
28
25
 
29
26
  def _html2_pdf_render_pdf_and_get_url(pdf_name, options = {})
30
27
  options = _html2pdf_default_options(pdf_name, options)
31
- options[:put_to_storage] = true
32
- json = JSON.parse(_html2pdf_make_pdf(options))
33
- json['url']
28
+ html = _html2pdf_render_html(options)
29
+ response = Html2Pdf::Rails.generate(
30
+ html: html,
31
+ pdf_options: options[:pdf_options],
32
+ put_to_storage: true,
33
+ file_name: options[:file_name],
34
+ disposition: options[:disposition]
35
+ )
36
+ JSON.parse(response)['url']
34
37
  end
35
38
 
36
39
  def _html2pdf_make_and_send_pdf(pdf_name, options = {})
@@ -40,24 +43,15 @@ module Html2Pdf
40
43
  render_opts = options.slice(:template, :layout, :formats, :handlers)
41
44
  render(render_opts.merge({ content_type: 'text/html' }))
42
45
  else
43
- pdf_content = _html2pdf_make_pdf(options)
46
+ html = _html2pdf_render_html(options)
47
+ pdf_content = Html2Pdf::Rails.generate(html: html, pdf_options: options[:pdf_options])
44
48
  send_data(pdf_content, filename: options[:file_name], type: 'application/pdf', disposition: options[:disposition])
45
49
  end
46
50
  end
47
51
 
48
- def _html2pdf_make_pdf(options = {})
52
+ def _html2pdf_render_html(options)
49
53
  render_opts = options.slice(:template, :layout, :formats, :handlers)
50
- html = render_to_string(**render_opts)
51
-
52
- Retryable.retryable(tries: 3, on: Html2Pdf::Rails::ServiceUnavailableError) do
53
- Client.post(
54
- html: html,
55
- put_to_storage: options[:put_to_storage],
56
- file_name: options[:file_name],
57
- disposition: options[:disposition],
58
- pdf_options: options[:pdf_options]
59
- )
60
- end
54
+ render_to_string(**render_opts)
61
55
  end
62
56
  end
63
57
  end
@@ -2,6 +2,6 @@
2
2
 
3
3
  module Html2Pdf
4
4
  module Rails
5
- VERSION = '0.6.0'
5
+ VERSION = '0.8.0'
6
6
  end
7
7
  end
@@ -1,13 +1,27 @@
1
+ require 'retryable'
1
2
  require 'html2pdf/rails/version'
3
+ require 'html2pdf/rails/errors'
4
+ require 'html2pdf/rails/api_key'
5
+ require 'html2pdf/rails/client'
2
6
  require 'html2pdf/rails/railtie'
3
7
 
4
8
  module Html2Pdf
5
9
  class Config
6
10
  attr_accessor :endpoint, :app
11
+ attr_writer :api_key
7
12
 
8
13
  def initialize
9
14
  @endpoint = nil
10
15
  @app = nil
16
+ @api_key = nil
17
+ end
18
+
19
+ # Falls back to ENV at read time (not in #initialize) so that the key can be
20
+ # set after the config object is built, e.g. by dotenv loading later in boot.
21
+ # A blank value also falls back, because `credentials.xxx.to_s` and the like
22
+ # yield '' when the key is not set.
23
+ def api_key
24
+ Html2Pdf::Rails::ApiKey.normalize(@api_key) || Html2Pdf::Rails::ApiKey.normalize(ENV['HTML2PDF_API_KEY'])
11
25
  end
12
26
  end
13
27
 
@@ -20,4 +34,18 @@ module Html2Pdf
20
34
  @config ||= Config.new
21
35
  end
22
36
  end
37
+
38
+ module Rails
39
+ def self.generate(html:, pdf_options: {}, put_to_storage: false, file_name: nil, disposition: nil)
40
+ Retryable.retryable(tries: 3, on: ServiceUnavailableError) do
41
+ Client.post(
42
+ html: html,
43
+ pdf_options: pdf_options,
44
+ put_to_storage: put_to_storage,
45
+ file_name: file_name,
46
+ disposition: disposition
47
+ )
48
+ end
49
+ end
50
+ end
23
51
  end
metadata CHANGED
@@ -1,13 +1,13 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: html2pdf-rails
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.6.0
4
+ version: 0.8.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - aki77
8
8
  bindir: exe
9
9
  cert_chain: []
10
- date: 2026-02-25 00:00:00.000000000 Z
10
+ date: 1980-01-02 00:00:00.000000000 Z
11
11
  dependencies:
12
12
  - !ruby/object:Gem::Dependency
13
13
  name: rails
@@ -99,9 +99,11 @@ files:
99
99
  - bin/setup
100
100
  - html2pdf-rails.gemspec
101
101
  - lib/html2pdf/rails.rb
102
+ - lib/html2pdf/rails/api_key.rb
102
103
  - lib/html2pdf/rails/client.rb
103
104
  - lib/html2pdf/rails/errors.rb
104
105
  - lib/html2pdf/rails/helper.rb
106
+ - lib/html2pdf/rails/mailer_rendering.rb
105
107
  - lib/html2pdf/rails/railtie.rb
106
108
  - lib/html2pdf/rails/rendering.rb
107
109
  - lib/html2pdf/rails/version.rb
@@ -123,7 +125,7 @@ required_rubygems_version: !ruby/object:Gem::Requirement
123
125
  - !ruby/object:Gem::Version
124
126
  version: '0'
125
127
  requirements: []
126
- rubygems_version: 3.6.2
128
+ rubygems_version: 4.0.3
127
129
  specification_version: 4
128
130
  summary: PDF generator (from HTML) gem for Ruby on Rails
129
131
  test_files: []