DocRaptor HTML TO PDF API

How to Convert HTML-to-PDF with Ruby

DocRaptor's HTML to PDF API is the easiest way to generate high-quality PDFs with Ruby. Our API handles the infrastructure and scalability, while our partnership with the Prince PDF engine lets you create more complex PDFs than with open-source HTML-to-PDF libraries. We're huge Ruby fans and created DocRaptor with Ruby on Rails back in 2010.

No Signup Required

You can get started in only a few minutes with the DocRaptor Ruby gem and our public, testing API key (YOUR_API_KEY_HERE). Signing up for a free account lets you remove the watermark and get access to our support team for debugging assistance. Paid accounts start at $15/month and don't have any document size limits.

Gem Installation

Install or require the docraptor gem to your project:

gem install docraptor

Hello World! Example

Here's an example of the minimum code necessary:

docraptor-hello.rb
Download
require "docraptor"

DocRaptor.configure do |config|
  config.username = "YOUR_API_KEY_HERE" # this key works in test mode!
end

docraptor = DocRaptor::DocApi.new

begin
  response = docraptor.create_doc(
    test: true, # test documents are free but watermarked
    document_type: "pdf",
    document_content: "<html><body>Hello World!</body></html>",
    # document_url: "https://docraptor.com/examples/invoice.html",
    # javascript: true,
    # prince_options: {
    #   media: "print", # @media 'screen' or 'print' CSS
    #   baseurl: "https://yoursite.com", # the base URL for any relative URLs
    # }
  )

  # create_doc() returns a binary string
  File.write("docraptor-hello.pdf", response, mode: "wb")
  puts "Successfully created docraptor-hello.pdf!"
rescue DocRaptor::ApiError => error
  puts "#{error.class}: #{error.message}"
  puts error.code
  puts error.response_body
  puts error.backtrace[0..3].join("\n")
end

To generate a PDF, simply download or copy the above Ruby file and run:

ruby docraptor-hello.rb

Advanced HTML Example

Now that you've seen the Ruby agent and API working in action, let's get into some HTML and unique-to-DocRaptor CSS. This example document includes repeating headers, table of contents with leaders, footnotes, and a title page without a header:

docraptor-advanced-content.html
Download
<html>
  <head>
    <style>
      /* Create a running element */
      #header-and-footer {
        position: running(header-and-footer);
        text-align: right;
      }

      /* Add that running element to the top and bottom of every page */
      @page {
        @top {
          content: element(header-and-footer);
        }
        @bottom {
          content: element(header-and-footer);
        }
      }

      /* Add a page number */
      #page-number {
        content: "Page " counter(page);
      }

      /* Create a title page with a full-bleed background and no header */
      #title-page {
        page: title-page;
      }

      @page title-page {
        background: url('https://docraptor-production-cdn.s3.amazonaws.com/tutorials/raptor.svg') 50% 50px / 80% no-repeat #DDE4F3;
        @top {
          content: "";
        }
      }

      #title-page h1 {
        padding: 500px 0 40px 0;
        font-size: 75px;
      }

      /* Dynamically create a table of contents with leaders */
      #table-of-contents a {
        content: target-content(attr(href)) leader('.') target-counter(attr(href), page);
        color: #135697;
        text-decoration: none;
        display: block;
        padding-top: 5px;
      }

      /* Float the footnote to a footnotes area on the page */
      .footnote {
        float: footnote;
        font-size: small;
      }

      .page {
        page-break-after: always;
      }

      body {
        counter-reset: chapter;
        font-family: 'Open Sans';
        color: #135697;
      }
    </style>
    <link href="https://fonts.googleapis.com/css2?family=Open+Sans:wght@400;600;800&display=swap" rel="stylesheet">
  </head>
  <body>
    <div id="title-page" class="page">
      <h1>The Official DocRaptor eBook</h1>
      <div id="table-of-contents">
        <a href="#chapter-1"></a>
        <a href="#chapter-2"></a>
        <a href="#chapter-3"></a>
      </div>
      <div id="header-and-footer">
        <span id="page-number"></span> | The Official DocRaptor eBook
      </div>
    </div>
    <div class="page">
      <h2 id="chapter-1">What is DocRaptor?</h2>
      <p>DocRaptor is an HTML to PDF API!</p>
    </div>
    <div class="page">
      <h2 id="chapter-2">Why should I use DocRaptor?</h2>
      <p>It's super easy and also has the most powerful conversion capabilities!</p>
    </div>
    <div class="page">
      <h2 id="chapter-3">How much does it cost?</h2>
      <p>
        We have a free plan!<span class="footnote">Includes five documents a month</span>
      </p>
    </div>
  </body>
</html>
docraptor-advanced.rb
Download
require "docraptor"

DocRaptor.configure do |config|
  config.username = "YOUR_API_KEY_HERE" # this key works in test mode!
end

docraptor = DocRaptor::DocApi.new

begin
  response = docraptor.create_doc(
    test: true, # test documents are free but watermarked
    document_type: "pdf",
    document_content: File.read("docraptor-advanced-content.html"),
    # document_url: "https://docraptor.com/examples/invoice.html",
    # javascript: true,
    # prince_options: {
    #   media: "print", # @media 'screen' or 'print' CSS
    #   baseurl: "https://yoursite.com", # the base URL for any relative URLs
    # }
  )

  # create_doc() returns a binary string
  File.write("docraptor-advanced.pdf", response, mode: "wb")
  puts "Successfully created docraptor-advanced.pdf!"
rescue DocRaptor::ApiError => error
  puts "#{error.class}: #{error.message}"
  puts error.code
  puts error.response_body
  puts error.backtrace[0..3].join("\n")
end

To generate that PDF, we again download or copy the above Ruby file and run:

ruby docraptor-advanced.rb

There's some important API paramteters you'll want to know about, or you can skip ahead to learn more about DocRaptor's unique HTML and CSS functionality.

Important API Parameters

DocRaptor has one primary API endpoint, Create Document, but it has many parameters. They are all well documented but we'll highlight the most important parameters here:

test

Every DocRaptor account includes unlimited watermarked test documents. This gives you time to fine-tune your design and implementation for free while in development. The public API key only works on test documents. When you're ready to remove the watermark, just set test to false.

javascript

By default, JavaScript is disabled to speed up your document creation. However, if your document uses JavaScript to render content, you'll want to enable it by setting this value to true.

As it's difficult to know precisely when your JavaScript is done executing, you may want to delay rendering until a specific time or a particular element is present. Additionally, DocRaptor has two JavaScript engines. Most users prefer our standard engine, which has more modern JavaScript support, but we also support Prince's JavaScript engine, which supports multiple rendering passes and other advanced PDF-specific functionality.

async

By default, the DocRaptor client operates synchronously and returns a Ruby binary string containing your PDF. There's a 60 second limit for each conversion.

If you have very large or complex documents, you can enable asynchronous conversion. Asynchronous documents have a 10-minute limit. You'll need to supply a callback URL or monitor the status of your document generation.

The Ruby agent asynchronous PDF conversion code looks like this:

docraptor-async.rb
Download
require "docraptor"

DocRaptor.configure do |config|
  config.username = "YOUR_API_KEY_HERE" # this key works in test mode!
end

docraptor = DocRaptor::DocApi.new

begin
  # different method than the synchronous documents
  response = docraptor.create_async_doc(
    test: true, # test documents are free but watermarked
    document_type: "pdf",
    document_content: "<html><body>Hello World!</body></html>",
    # document_url: "https://docraptor.com/examples/invoice.html",
    # javascript: true,
    # prince_options: {
    #   media: "print", # @media 'screen' or 'print' CSS
    #   baseurl: "https://yoursite.com", # the base URL for any relative URLs
    # }
  )

  loop do
    status_response = docraptor.get_async_doc_status(response.status_id)
    puts "status: #{status_response.status}"
    case status_response.status
    when "completed"
      document = docraptor.get_async_doc(status_response.download_id)
      # get_async_doc() returns a binary string
      File.write("docraptor-async.pdf", document, mode: "wb")
      puts "Successfully created docraptor-async.pdf!"
      break
    when "failed"
      puts "FAILED"
      puts status_response
      break
    else
      sleep 1
    end
  end
rescue DocRaptor::ApiError => error
  puts "#{error.class}: #{error.message}"
  puts error.code
  puts error.response_body
  puts error.backtrace[0..3].join("\n")
end

hosted

As a paid add-on, DocRaptor can also host your documents on your behalf on an unbranded URL. It's ideal for no-code apps or repeated document creation and can save you a ton of time. Document hosting can expire after a particular date or number of downloads, which you can control.

When creating a hosted document, you'll need to use a different client method (create_hosted_doc or created_async_hosted_doc, instead of create_doc ). And similar to the asynchronous generation response, we'll return a URL instead of a binary file. Here's an example:

docraptor-hosted.rb
Download
require "docraptor"

DocRaptor.configure do |config|
  config.username = "YOUR_API_KEY_HERE" # this key works in test mode!
end

docraptor = DocRaptor::DocApi.new

begin
  # different method than the non-hosted documents
  response = docraptor.create_hosted_doc(
    test: true, # test documents are free but watermarked
    document_type: "pdf",
    document_content: "<html><body>Hello World!</body></html>",
    # document_url: "https://docraptor.com/examples/invoice.html",
    # javascript: true,
    # prince_options: {
    #   media: "print", # @media 'screen' or 'print' CSS
    #   baseurl: "https://yoursite.com", # the base URL for any relative URLs
    # }
  )

  puts "The PDF is hosted at #{response.download_url}"
rescue DocRaptor::ApiError => error
  puts "#{error.class}: #{error.message}"
  puts error.code
  puts error.response_body
  puts error.backtrace[0..3].join("\n")
end

Advanced HTML & CSS for PDF Creation

Web pages and browsers create long scrolling pages. Conversely, PDF documents contain many smaller pages, often with headers, footers, and page margins that browsers don't have.

Fortunately, the Prince engine developed the CSS Paged Media specifications that allow us to support these concepts with normal CSS and HTML. Some of this CSS may be new to you, but it's easy to implement.

Here are some of our most popular tutorials and reference pages:

All of the above are pure HTML, CSS, and JavaScript and will work in any Ruby or Ruby on Rails application.

Other Resources & Documentation

We understand that creating PDFs from Ruby can be challenging, especially if you've never done it before, or if you're creating a complex document. Our sample documents contain examples of advanced techniques, many exclusive to DocRaptor and Prince. The documentation has many how-tos, tutorials with Ruby HTML-to-PDF source code, and troubleshooting tips.

Moreover, if you're still evaluating whether DocRaptor is the best fit for your project, check out our top Ruby HTML to PDF libraries guide. We've also created more general overviews of open-source HTML-to-PDF tools and online HTML to PDF APIs.

And if you get stuck, contact our support team by opening a Help Request on a document or by emailing support@docraptor.com. We hope this helps!

Ready to get started? Try DocRaptor for free with unlimited test documents.