Features

URL to PDF

The best way to prepare a URL for printing.

Turning a URL into a PDF is easy with Urlbox.

The most basic request is simply to form a URL like the following:

https://api.urlbox.io/v1/[API_KEY]/pdf?url=example.com

Linking to a dynamic PDF

Yes you can literally create a link to that URL and your users will be able to view the PDF:

<a href="https://api.urlbox.io/v1/[API_KEY]/pdf?url=example.com" />View PDF</a>

Which would result in this:

View PDF

Maybe you want users to download the PDF with a particular filename? Easy, just add one parameter:

<a href="https://api.urlbox.io/v1/[API_KEY]/pdf?url=example.com&download=my-document.pdf" />Download PDF</a>

Which would result in this:

Download PDF

Authentication

You'll notice your API key is embedded in the URLs above. Anyone could potentially start using your API key to make requests against the Urlbox API - and use up your quota. So, if your Urlbox URLs are used publicly, you should prevent anonymous usage with an authenticated request format. See how to do that in our docs.

If want to generate your PDF links for turning URLs into PDFs with code we've included examples of how you can do it in different languages below.

URL to PDF in Node.js

// npm install urlbox --save
 
import Urlbox from "urlbox";
 
// Plugin your API key and secret
const urlbox = Urlbox(YOUR_API_KEY, YOUR_API_SECRET);
 
// Set your options
const options = {
  url: "example.com",
  format: "pdf",
};
 
const imgUrl = urlbox.generateRenderLink(options);
// https://api.urlbox.io/v1/YOUR_API_KEY/TOKEN/pdf?url=example.com
 
// Now set it as the src in an img tag to render the screenshot
<img src={imgUrl} />;

URL to PDF in Ruby

# ruby gem coming soon
require 'openssl'
require 'open-uri'
 
def encodeURIComponent(val)
  URI.escape(val, Regexp.new("[^#{URI::PATTERN::UNRESERVED}]"))
end
 
def urlbox(url, options={}, format='pdf')
  urlbox_apikey = 'YOUR_API_KEY'
  urlbox_secret = 'YOUR_API_SECRET'
 
  query = {
    url: url
  }
 
  query_string = query.
    sort_by {|s| s[0].to_s }.
    select {|s| s[1] }.
    map {|s| s.map {|v| encodeURIComponent(v.to_s) }.join('=') }.
    join('&')
 
  token = OpenSSL::HMAC.hexdigest('sha256', urlbox_secret, query_string)
 
  "https://api.urlbox.io/v1/#{urlbox_apikey}/#{token}/#{format}?#{query_string}"
end
 
url = urlbox("example.com", {}, 'pdf')
puts url
# url: "https://api.urlbox.io/v1/YOUR_API_KEY/TOKEN/pdf?url=www.google.com"

URL to PDF in PHP

// run this on the command line to install the urlbox php package:
// composer require urlbox/screenshots
 
use Urlbox\Screenshots\Urlbox;
 
$urlbox = Urlbox::fromCredentials('API_KEY', 'API_SECRET');
 
// only required option is a url:
$options['url'] = 'example.com';
 
// specify any other options to augment the screenshot...
$options['width'] = 320;
 
// Create the Urlbox URL
$urlboxUrl = $urlbox->generateSignedUrl($options);
 
// $urlboxUrl is now 'https://api.urlbox.io/v1/API_KEY/TOKEN/pdf?url=example.com&width=320'
 
// Generate a screenshot by loading the Urlbox URL in an img tag:
echo '<img src="'.$urlboxUrl.'" alt="Test screenshot generated by Urlbox">'

URL to PDF in Python

# PyPi package coming soon!
#!/usr/bin/python
 
import hmac
from hashlib import sha256
 
try:
  from urllib import urlencode
except ImportError:
  from urllib.parse import urlencode
 
def urlbox(args):
  apiKey = "xxx-xxx"
  apiSecret = "xxx-xxx"
  queryString = urlencode(args, True)
  hmacToken = hmac.new(str.encode(apiSecret), str.encode(queryString), sha256)
  token = hmacToken.hexdigest().rstrip('\n')
  return "https://api.urlbox.io/v1/%s/%s/pdf?%s" % (apiKey, token, queryString)
 
argsDict = {'url' : "twitter.com", 'thumb_width': 400}
print(urlbox (argsDict))

URL to PDF in Java

import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.net.URLEncoder;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Map;
import java.util.HashMap;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
 
public class Urlbox {
 
  private String key;
  private String secret;
 
  Urlbox(String api_key, String api_secret) {
    this.key = api_key;
    this.secret = api_secret;
  }
 
  // main method demos Example Usage
  public static void main(String[] args) {
    String urlboxKey = "your-urlbox-api-key";
    String urlboxSecret = "your-urlbox-secret";
 
    // Set request options
    Map<String, Object> options = new HashMap<String, Object>();
    options.put("width", 1280);
    options.put("height", 1024);
    options.put("thumb_width", 240);
    options.put("full_page", "false");
    options.put("force", "false");
 
    // Create urlbox object with api key and secret
    Urlbox urlbox = new Urlbox(urlboxKey, urlboxSecret);
    try {
      // Call generateUrl function of urlbox object
      String urlboxUrl = urlbox.generateUrl("bbc.co.uk", options);
      // Now do something with urlboxUrl.. put in img tag, etc..
    } catch (UnsupportedEncodingException ex) {
      throw new RuntimeException("Problem with url encoding", ex);
    }
  }
 
  public String generateUrl(String url, Map<String,Object> options) throws UnsupportedEncodingException {
 
    String encodedUrl = URLEncoder.encode(url, "UTF-8");
    String queryString = String.format("url=%s", encodedUrl);
 
    for (Map.Entry<String, Object> entry : options.entrySet()) {
      String queryParam = "&"+entry.getKey()+"="+entry.getValue();
      queryString += queryParam;
    }
 
    String token = generateToken(queryString, this.secret);
    String result = String.format("https://api.urlbox.io/v1/%s/%s/pdf?%s", this.key, token, queryString);
    System.out.println(result);
    return result;
  }
 
  private String generateToken(String input, String key) {
    String lSignature = "None";
    try {
      final Mac lMac = Mac.getInstance("HmacSHA256")
      final SecretKeySpec lSecret = new SecretKeySpec(apiSecret.getBytes(), "HmacSHA256")
      lMac.init(lSecret)
      final byte[] lDigest = lMac.doFinal(input.getBytes())
      final StringBuilder lSignature = new StringBuilder();
      for (byte b : lDigest) {
        lSignature.append(String.format("%02x", b));
      }
      return lSignature.toString().toLowerCase()
    } catch (NoSuchAlgorithmException lEx) {
      throw new RuntimeException("Problems calculating HMAC", lEx)
    } catch (InvalidKeyException lEx) {
      throw new RuntimeException("Problems calculating HMAC", lEx)
    }
    return lSignature;
  }
}

URL to PDF in C#

 
using UrlboxMain;
 
namespace Screenshot
{
  public class Screenshotter
  {
    Urlbox urlbox = new Urlbox("YOUR_URLBOX_API_KEY", "YOUR_URLBOX_API_SECRET");
 
    public void GetScreenshotUrl()
    {
      dynamic options = new ExpandoObject();
      options.Width = 1280;
      options.Thumb_Width = 500;
      options.Full_Page = true;
 
      var output = urlbox.GenerateUrl("bbc.co.uk", options);
      // output is now https://api.urlbox.io/v1/YOUR_URLBOX_API_KEY/d6b5068716c19ba4556648ad9df047d5847cda0c/pdf?url=bbc.co.uk&width=1280&thumb_width=500&full_page=true
      // to generate a screenshot image you would make a simple GET request to this URL, for example putting it inside an <img> tag.
    }
  }
}
 // ================================================================
// UrlboxMain project/package:
using System;
using System.Collections.Generic;
using System.Dynamic;
using System.Linq;
using System.Text;
using PCLCrypto;
 
namespace UrlboxMain
{
  public class Urlbox
  {
    String apiKey;
    String apiSecret;
    static List<String> encodedPropertyNames = new List<String> { "user_agent", "bg_color", "hide_selector", "click_selector", "highlight", "highlightbg", "highlightfg" };
    static List<String> booleanPropertyNames = new List<String> { "force", "retina", "full_page", "disable_js" };
 
    public Urlbox(String apiKey, String apiSecret)
    {
      if (String.IsNullOrEmpty(apiKey) || String.IsNullOrEmpty(apiSecret))
      {
        throw new ArgumentException("Please provide your Urlbox.io API Key and API Secret");
      }
      this.apiKey = apiKey;
      this.apiSecret = apiSecret;
    }
 
    public string GenerateUrl(string url)
    {
      return this.GenerateUrl(url, new ExpandoObject());
    }
 
    public string GenerateUrl(string url, ExpandoObject options)
    {
      if (String.IsNullOrEmpty(url))
      {
        throw new ArgumentException("Please provide a url in order to generate a screenshot URL");
      }
      var encodedUrl = urlEncode(url);
      var format = "pdf";
 
      byte[] key = Encoding.UTF8.GetBytes(this.apiSecret);
      var urlString = string.Format("url={0}", encodedUrl);
      StringBuilder sb = new StringBuilder(urlString);
 
      foreach (KeyValuePair<string, object> kvp in options)
      {
        var optionName = kvp.Key.ToLower();
        var optionValue = kvp.Value.ToString();
        if (String.IsNullOrEmpty(optionValue))
        {
          continue;
        }
        if (string.Equals(optionName, "format")){
          format = optionValue;
          continue;
        }
        if (encodedPropertyNames.Contains(optionName))
        {
          optionValue = urlEncode(optionValue);
        }
        if (booleanPropertyNames.Contains(optionName))
        {
          if (!(bool)kvp.Value) { continue; }
          optionValue = optionValue.ToLower();
        }
        sb.Append(string.Format("&{0}={1}", optionName, optionValue));
      }
 
      var queryString = sb.ToString();
      var uniqueToken = generateToken(queryString, key);
      return string.Format("https://api.urlbox.io/v1/{0}/{1}/{2}?{3}", this.apiKey, uniqueToken, format, queryString);
    }
 
    private static string generateToken(String data, byte[] key)
    {
      var algorithm = WinRTCrypto.MacAlgorithmProvider.OpenAlgorithm(MacAlgorithm.HmacSha256);
      CryptographicHash hasher = algorithm.CreateHash(key);
      hasher.Append(Encoding.UTF8.GetBytes(data));
      byte[] mac = hasher.GetValueAndReset();
      var macStr = byteArrayToString(mac);
      return macStr;
    }
 
    private static string byteArrayToString(byte[] ba)
    {
      string hex = BitConverter.ToString(ba).ToLower();
      return hex.Replace("-", "");
    }
 
    private static string urlEncode(string url)
    {
      // make it behave like javascript encodeURIComponent()
      var encoded = Uri.EscapeDataString(url);
      encoded = encoded.Replace("%28", "(");
      encoded = encoded.Replace("%29", ")");
      return encoded;
    }
 
  }
}
 

All the PDF options you need

There are over a dozen PDF-specific options in the Urlbox API.

Set the page size to A4, Letter or one of 9 other alternatives. Change the print margins, scale, background and more.

Full documentation here.

You're not limited to generating PDFs with Urlbox

Urlbox has many output formats beyond PDF. You can also render:

  • PNG
  • JPEG
  • WebP
  • SVG
  • AVIF
  • HTML (after JS has executed)
  • JSON (Coming soon).

More Urlbox Features

Urlbox is powerful with dozens of features for taking screenshots at scale.

If you found this useful you might also want to checkout some of our other popular Urlbox features:

Index

All Features

Free Trial

Designers, law firms and infrastructure engineers trust Urlbox to accurately and securely convert HTML to images at scale. Experience it for yourself.