Ruby Integration

Learn how to generate PDFs from your Ruby application using Net::HTTP or the popular Faraday gem.

Why use PixelToPdf with Ruby?

Ruby's elegant syntax and Rails' convention over configuration philosophy make PDF generation a breeze with PixelToPdf. Whether you're building a Rails application, a Sinatra API, or a standalone Ruby script, our API fits naturally into your workflow. Perfect for invoices, reports, tickets, and any document your users need.

Prerequisites

  • Ruby 2.7+ (3.x recommended for best performance)
  • A PixelToPdf API key from your dashboard (free tier available)

Basic Example

This example uses Ruby's built-in Net::HTTP library to convert a webpage to PDF. We read the API key from environment variables using ENV.

convert_url.rb
require 'net/http'
require 'uri'
require 'json'

uri = URI('https://api.pixeltopdf.com/convert/pdf')

http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true

request = Net::HTTP::Post.new(uri)
request['X-API-Key'] = ENV['PIXELTOPDF_API_KEY']
request['Content-Type'] = 'application/json'
request.body = { source: 'https://example.com' }.to_json

response = http.request(request)

if response.code == '200'
  File.open('output.pdf', 'wb') { |f| f.write(response.body) }
  puts 'PDF saved to output.pdf'
else
  puts "Error: #{response.code}"
end

How it works: We create an HTTPS connection with use_ssl = true, set the headers, and convert our Ruby hash to JSON using .to_json. The response body contains the raw PDF bytes, which we write in binary mode ('wb').

Convert HTML String

For dynamic documents, pass your HTML directly as a string. Ruby's heredoc syntax (<<~HTML) with the squiggly variant strips leading whitespace for cleaner code.

convert_html.rb
require 'net/http'
require 'uri'
require 'json'

html = <<~HTML
  <!DOCTYPE html>
  <html>
  <head>
    <style>
      body { font-family: Arial, sans-serif; padding: 40px; }
      h1 { color: #333; }
    </style>
  </head>
  <body>
    <h1>Hello, PixelToPdf!</h1>
    <p>This PDF was generated from HTML.</p>
  </body>
  </html>
HTML

uri = URI('https://api.pixeltopdf.com/convert/pdf')

http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true

request = Net::HTTP::Post.new(uri)
request['X-API-Key'] = ENV['PIXELTOPDF_API_KEY']
request['Content-Type'] = 'application/json'
request.body = {
  source: html,
  format: 'A4',
  margin: { top: '20mm', bottom: '20mm', left: '20mm', right: '20mm' }
}.to_json

response = http.request(request)
File.open('output.pdf', 'wb') { |f| f.write(response.body) }

Tip: You can use ERB templates or any Ruby templating engine to generate your HTML dynamically before sending it to PixelToPdf. The margin option accepts values in mm, cm, in, or px.

With Rails

This Rails controller action renders a view to HTML, converts it to PDF, and streams it to the browser for download. The render_to_string method captures the rendered HTML without sending it to the client.

invoices_controller.rb
class InvoicesController < ApplicationController
  require 'net/http'
  require 'uri'
  require 'json'

  def download
    html = render_to_string(template: 'invoices/show', layout: 'pdf')

    uri = URI('https://api.pixeltopdf.com/convert/pdf')
    http = Net::HTTP.new(uri.host, uri.port)
    http.use_ssl = true

    request = Net::HTTP::Post.new(uri)
    request['X-API-Key'] = ENV['PIXELTOPDF_API_KEY']
    request['Content-Type'] = 'application/json'
    request.body = { source: html, format: 'A4' }.to_json

    response = http.request(request)

    if response.code == '200'
      send_data response.body,
                filename: "invoice-#{params[:id]}.pdf",
                type: 'application/pdf',
                disposition: 'attachment'
    else
      render plain: 'PDF generation failed', status: :internal_server_error
    end
  end
end

Best practice: Store your API key in Rails credentials (rails credentials:edit) and access it via Rails.application.credentials.pixeltopdf_api_key. Use a dedicated PDF layout without JavaScript or navigation elements.

With Faraday

Faraday is a popular HTTP client gem that provides a cleaner API than Net::HTTP. Install it with: gem install faraday

convert_faraday.rb
require 'faraday'
require 'json'

# First: gem install faraday

conn = Faraday.new(url: 'https://api.pixeltopdf.com') do |f|
  f.request :json
  f.response :raise_error
end

response = conn.post('/convert/pdf') do |req|
  req.headers['X-API-Key'] = ENV['PIXELTOPDF_API_KEY']
  req.body = { source: 'https://example.com' }
end

File.open('output.pdf', 'wb') { |f| f.write(response.body) }

How it works: Faraday's middleware system handles JSON serialization automatically with f.request :json. The raise_error middleware raises exceptions for 4xx/5xx responses, making error handling more Ruby-like.

Error Handling

This reusable client class wraps the API call with proper error handling. Custom exceptions inherit from StandardError, making them easy to rescue in your application.

pixeltopdf_client.rb
require 'net/http'
require 'uri'
require 'json'

class PixelToPdfError < StandardError; end

class PixelToPdfClient
  def initialize(api_key)
    @api_key = api_key
    @uri = URI('https://api.pixeltopdf.com/convert/pdf')
  end

  def generate_pdf(source)
    http = Net::HTTP.new(@uri.host, @uri.port)
    http.use_ssl = true

    request = Net::HTTP::Post.new(@uri)
    request['X-API-Key'] = @api_key
    request['Content-Type'] = 'application/json'
    request.body = { source: source }.to_json

    response = http.request(request)

    case response.code
    when '200'
      response.body
    when '401'
      raise PixelToPdfError, 'Invalid API key'
    when '402'
      raise PixelToPdfError, 'No credits remaining'
    when '429'
      raise PixelToPdfError, 'Rate limit exceeded'
    else
      raise PixelToPdfError, "PDF generation failed: #{response.body}"
    end
  end
end

# Usage
client = PixelToPdfClient.new(ENV['PIXELTOPDF_API_KEY'])
pdf = client.generate_pdf('https://example.com')
File.open('output.pdf', 'wb') { |f| f.write(pdf) }

Important: The API returns different status codes for different error types: 401 for authentication issues, 402 when you need more credits, and 429 when you've hit the rate limit. Handle each appropriately in production.

Next steps

You've mastered the basics! Learn about headers, footers, page breaks, and advanced styling in our API documentation.