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
endAvailable Options
| Option | Type | Description |
|---|---|---|
| format | String | Output format: 'pdf', 'png', 'jpeg', 'webp' |
| html | String | HTML content to convert |
| url | String | URL to convert |
| options[:format] | String | Page size: 'A4', 'Letter', etc. |
| options[:landscape] | Boolean | Landscape orientation |
| options[:printBackground] | Boolean | Include background colors/images |
Other Integrations
See Use Cases
PDF generation for Rails and Ruby
Use Net::HTTP, HTTParty, or Faraday. Your choice.