Class: PDFify::Client

Inherits:
Object
  • Object
show all
Includes:
HTTParty
Defined in:
lib/pdfify/client.rb

Instance Method Summary collapse

Constructor Details

#initialize(config = nil) ⇒ Client

Returns a new instance of Client.



7
8
9
10
11
12
13
# File 'lib/pdfify/client.rb', line 7

def initialize(config = nil)
  @config = config || PDFify.configuration
  @config.validate!

  self.class.base_uri(@config.base_url)
  self.class.default_timeout(@config.timeout)
end

Instance Method Details

#convert(html:, **options) ⇒ String

Generate a PDF from HTML

Parameters:

  • html (String) —

    The HTML content to convert

  • options (Hash) —

    Optional parameters

Options Hash (**options):

  • :test (Boolean) —

    Enable test/sandbox mode (doesn't count against quota)

  • :sandbox (Boolean) —

    Alias for :test

  • :profile (String) —

    CSS profile to use

  • :css (String) —

    Additional CSS to inject

  • :auto_compat (Boolean) —

    Enable automatic compatibility mode detection

  • :template_engine (String) —

    Specify template engine (docraptor, pdfshift, etc.)

Returns:

  • (String) —

    Binary PDF data



25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
# File 'lib/pdfify/client.rb', line 25

def convert(html:, **options)
  raise ArgumentError, "HTML content is required" if html.nil? || html.empty?

  # Build request body
  body = { html: html }

  # Add optional parameters
  body[:test] = options[:test] if options.key?(:test)
  body[:sandbox] = options[:sandbox] if options.key?(:sandbox)
  body[:profile] = options[:profile] if options.key?(:profile)
  body[:css] = options[:css] if options.key?(:css)
  body[:auto_compat] = options[:auto_compat] if options.key?(:auto_compat)
  body[:template_engine] = options[:template_engine] if options.key?(:template_engine)

  # Make API request
  response = self.class.post(
    "/api/v1/convert",
    body: body,
    headers: {
      "Authorization" => "Bearer #{@config.api_key}",
      "User-Agent" => "PDFify Ruby Gem v#{PDFify::VERSION}"
    }
  )

  # Handle response
  case response.code
  when 200
    response.body # Return binary PDF data
  when 400
    error = parse_error(response)
    raise ValidationError, error
  when 403
    error = parse_error(response)
    raise QuotaExceededError, error
  when 413
    error = parse_error(response)
    raise ContentTooLargeError, error
  when 401
    raise AuthenticationError, "Invalid API key"
  when 500
    error = parse_error(response)
    raise ServerError, error
  else
    raise APIError, "Unexpected response code: #{response.code}"
  end
rescue HTTParty::Error, Timeout::Error, Errno::ECONNREFUSED => e
  raise NetworkError, "Failed to connect to PDFify API: #{e.message}"
end