Convert HTML to PDF in Ruby

Convert HTML to PDF in Ruby using the HTML2PDFAPI REST API. Works with Ruby on Rails, Sinatra, and plain Ruby scripts.

Quick Start

require 'net/http'
require 'json'
require 'uri'

uri = URI('https://html2pdfapi.com/render')
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true

request = Net::HTTP::Post.new(uri)
request['Authorization'] = 'Bearer YOUR_API_KEY'
request['Content-Type'] = 'application/json'
request.body = {
  html: '<h1>Hello World</h1>',
  format: 'pdf'
}.to_json

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

Ruby on Rails Integration

# app/controllers/pdfs_controller.rb
class PdfsController < ApplicationController
  def generate
    html = render_to_string(
      template: 'invoices/show',
      layout: 'pdf',
      locals: { invoice: @invoice }
    )

    response = HTTParty.post(
      'https://html2pdfapi.com/render',
      headers: {
        'Authorization' => "Bearer #{ENV['HTML2PDFAPI_KEY']}",
        'Content-Type' => 'application/json'
      },
      body: {
        html: html,
        format: 'pdf',
        options: { format: 'A4' }
      }.to_json
    )

    send_data response.body,
      filename: 'invoice.pdf',
      type: 'application/pdf',
      disposition: 'attachment'
  end
end

Available Options

OptionTypeDescription
formatStringOutput format: 'pdf', 'png', 'jpeg', 'webp'
htmlStringHTML content to convert
urlStringURL to convert
options[:format]StringPage size: 'A4', 'Letter', etc.
options[:landscape]BooleanLandscape orientation
options[:printBackground]BooleanInclude background colors/images

Other Integrations

Node.js Python PHP Go cURL n8n

See Use Cases

PDF generation for Rails and Ruby

Use Net::HTTP, HTTParty, or Faraday. Your choice.