Developer Docs

Web Integrations

HTML to PDF – API Docs

Web Integrations

Integrate your website with our PDF tools

Open your files with our web tools

Here are some use-cases:

  1. Your partners fill out your PDF forms, using our editor.
  2. Your vendors sign your PDF docs and you receive it automatically by email.
  3. You provide a simple way for your customers to crop your PDF templates.

How it Works

The edited document will be sent back to this email address

Copy code Click to try

Copy the above integration link and use it in your website or emails.
Need help setting it up? Please contact support.

Developer Setup

Pass input files as GET parameters, in JSON format:

https://www.sejda.com/pdf-editor?files=[{"downloadUrl":"https://www.example.com/download/sample.pdf"}]

Don't forget to URL encode the JSON value:

?files=%5B%7B%22downloadUrl%22%3A%22https%3A%2F%2Fwww.example.com%2Fdownload%2Fsample.pdf%22%7D%5D

An array of files is accepted for certain tools (eg: merge, compress).

To receive the edited documents back by email add a returnEmail parameter to the URL:

https://www.sejda.com/pdf-editor?files=[{"downloadUrl":"https://www.example.com/download/sample.pdf"}]&returnEmail=your@email.address

Remember to URL encode the email address value passed in:

&returnEmail=your%40email.address

'Save to PDF' link for your web page

Let your visitors save pages from your website to PDF. Convert URLs to PDF.

How it works

The URL is optional, we'll automatically convert the page where the link was clicked.

<a href="https://www.sejda.com/html-to-pdf?save-link">Save to PDF</a>

More options can be specified:

https://www.sejda.com/html-to-pdf?save-link=https://fs.blog&viewportWidth=1440&pageSize=A3
Name Description
save-link Web page URL to convert to PDF. Eg: https://fs.blog. Defaults to the referring page.
pageSize One of the standard page sizes: a0, a1, a2, a3, a4, a5, letter, legal. Defaults to one long page.
viewportWidth The width, in pixels, for the rendered HTML page. Eg: 1440. Defaults to browser's window.innerWidth
pageOrientation One of portrait, landscape or auto (default). Eg: auto
pageMargin Size of page margin, including units (px, in, cm or mm). Eg: 100px. Defaults to no margin.
usePrintMedia Use the print stylesheet. Eg: true. Defaults to false.
delay Seconds (0 to 5) to wait before starting to convert. Eg: 2. Defaults to 0.


HTML to PDF – API Docs

Pricing & Limits

Get started for free, no credit card required.
Unlimited documents, rate limited per hour. HTML to PDF API — Pricing

Authentication

Provide your API key in the Authorization header of each request:

Authorization: Token: api_Y0URAP1K3YH3R3

Want to use in the browser/client side javascript? Use the publishable key instead: see CORS sample code.


Create a free account to get started and get an API key.

Get started

Run this CURL command in your console:

$> curl -i https://api.sejda.com/v2/html-pdf\
  --fail --silent --show-error \
  --header "Content-Type: application/json" \
  --header "Authorization: Token: api_Y0URAP1K3YH3R3" \
  --data '{"url": "https://stripe.com", "viewportWidth":1200 }' > stripe_com.pdf

Endpoint URL

The API is organized around REST.

https://api.sejda.com/v2/html-pdf

Request

Make a POST request with JSON body:

Content-Type: application/json

Examples:

{"url":"stripe.com"}

Converting HTML code (instead of an URL) to PDF:

{"htmlCode":"<strong>HTML<\/strong>"}

HTML to PDF Options

Name Type Default Description
url string optional Web page URL to convert to PDF. Eg: https://stripe.com
htmlCode string optional HTML source code to convert to PDF. Eg: <strong>HTML</strong>
pageSize string one_long_page one_long_page or one of the standard page sizes: a0, a1, a2, a3, a4, a5, letter, legal.
pageOrientation string auto landscape, portrait or auto.
viewportWidth integer optional The width in pixels for the rendered web page. Eg: 1600
pageMargin double optional Specifies the size of the margin around the PDF page. To be used together with pageMarginUnits. Eg: 2.2
pageMarginUnits string optional Specifies the units to be used for the margin size. One of px, in, cm or mm. To be used together with pageMargin. Eg: px for a margin size specified in pixels.
hideNotices boolean false Attempt to automatically hide cookie notices and similar overlays. Eg: true
usePrintMedia boolean false Use the print stylesheet. Eg: true
delay int 0 Seconds (0 to 5) to wait before starting to convert. Useful if your website has an intro animation, etc.
scrollPage boolean false Lazy loading of resources. Scroll page all the way down before converting. Eg: true
authUsername string optional Username for HTTP authentication. Eg: Admin
authPassword string optional Password for HTTP authentication. Eg: !S3cr3t

CSS Options

Hide elements in PDF

Add the CSS class --hide-from-pdf to remove that element from the PDF.

<div class="--hide-from-pdf">Hide me</div>
Show elements only in PDF

Use the CSS class --show-in-pdf and the inline CSS style="display: none" to show in PDF an element that is hidden in HTML. When rendering the PDF the inline style will be changed to display: block.

<div class="--show-in-pdf" style="display:none">Show me</div>
Page breaks

Try this CSS style to force page breaks:

<style>
  .with-page-break {
    page-break-before: always;
    page-break-after: always;
  }
</style>
              

HTTP Response Codes

200 All OK. Response contents will be the PDF document stream.
400 Invalid request.
403 Account unconfirmed, no api key provided, CORS origin not allowed etc. Details provided in the response body.
413 Request size too large. Current limit is 50MB. Try converting by URL instead of providing the HTML body.
429 Rate limit reached (per hour or concurrency limit). You should retry the request. Details provided in the response body.
500 An error on our side. You should retry the request.
550 Failed to convert (Eg: Web page was not reachable, could not be loaded).

HTML to PDF Code Samples

HTML to PDF in Bash Curl
$> curl -i https://api.sejda.com/v2/html-pdf\
  --fail --silent --show-error \
  --header "Content-Type: application/json" \
  --header "Authorization: Token: api_Y0URAP1K3YH3R3" \
  --data '{"url": "https://example.com", "viewportWidth":1200 }' > out.pdf
HTML to PDF in Node.js Javascript
// npm install request
const request = require('request');
const fs = require('fs');

var opts = {
  uri: 'https://api.sejda.com/v2/html-pdf',
  headers: {
    'Authorization' : 'Token: ' + apiKey,
  },
  json: {
    'url': 'https://example.com',
    'viewportWidth': 1200
  }
};

request.post(opts)
  .on('error', function(err){
    return console.error(err);
  })
  .on('response', function(response) {
    if (response.statusCode === 200) {
      response.pipe(fs.createWriteStream('/tmp/out.pdf'))
        .on('finish', function () {
          console.log('PDF saved to disk');
        });
    } else {
      return console.error('Got code: ' + response.statusCode);
    }
  });
HTML to PDF in Python
import requests

url = 'https://api.sejda.com/v2/html-pdf'
r = requests.post(url, json = {
    'url': 'https://example.com',
    'viewportWidth': 1200
  }, headers = {
    'Authorization': 'Token: {}'.format(apiKey)
  })
open('/tmp/out.pdf', 'wb').write(r.content)
HTML to PDF in Javascript with CORS
<script src="//www.sejda.com/js/sejda-js-api.min.js"></script>
<script>
  document.getElementById('downloadPdfBtn')
    .addEventListener('click', function(e){
      SejdaJsApi.htmlToPdf({
        filename: 'out.pdf',
        /* leave blank for one long page */
        pageSize: 'a4',
        publishableKey: 'api_public_y0urap1k3yh3r3',
        htmlCode: document.querySelector('html').innerHTML,
        /* url: window.location.href */
        always: function() {
          // PDF download should have started
        },
        error: function(err) {
          console.error(err);
          alert('An error occurred');
        }
      });
    })
</script>
/* Don't forget to configure your API Allowed domains, on your account page. */
HTML to PDF in Java
<!-- Maven dependency -->
<dependency>
  <groupId>org.apache.httpcomponents</groupId>
  <artifactId>httpclient</artifactId>
	<version>4.5.8</version>
</dependency>

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;

CloseableHttpClient httpClient = HttpClientBuilder.create().build();
HttpPost request = new HttpPost("https://api.sejda.com/v2/html-pdf");
request.setHeader(HttpHeaders.AUTHORIZATION, "Token: " + apiKey);
request.setEntity(new StringEntity(
    "{\"url\": \"https://example.com\", \"viewportWidth\":1200 }",
    ContentType.APPLICATION_JSON));

HttpResponse response = httpClient.execute(request);
if (response.getStatusLine().getStatusCode() == 200) {

    try (InputStream in = response.getEntity().getContent();
         OutputStream out = new FileOutputStream(new File("/tmp/out.pdf"))) {
        byte[] buffer = new byte[8 * 1024];
        int bytesRead;
        while ((bytesRead = in.read(buffer)) != -1) {
            out.write(buffer, 0, bytesRead);
        }
    }
}
HTML to PDF in PHP
$url = "https://api.sejda.com/v2/html-pdf";
$content = json_encode(array('url' => 'https://example.com'));

$curl = curl_init($url);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);

curl_setopt($curl, CURLOPT_HTTPHEADER, array(
  "Content-type: application/json",
  "Authorization: Token: " . $apiKey));

curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $content);

$response = curl_exec($curl);

$status = curl_getinfo($curl, CURLINFO_HTTP_CODE);

if ($status == 200) {
  $fp = fopen("out.pdf", "w");
  fwrite($fp, $response);
  fclose($fp);
  print("PDF saved to disk");
} else {
  print("Error: failed with status $status, response $response, curl_error " . curl_error($curl) . ", curl_errno " . curl_errno($curl));
}
HTML to PDF in C# .NET
using System.Net.Http;
using Newtonsoft.Json.Linq;

var baseUrl = "https://api.sejda.com/v2/html-pdf";

using (var client = new HttpClient())
{
  client.DefaultRequestHeaders.TryAddWithoutValidation(
      "Authorization", "Token: " + apiKey
  );

  var json = new JObject();
  json.Add("url", "https://example.com");
  json.Add("viewportWidth", 1200);
  //json.Add("htmlCode", File.ReadAllText(@"c:\doc.html", Encoding.UTF8));

  var content = new StringContent(json.ToString(), Encoding.UTF8, "application/json");

  using (var res = await client.PostAsync(baseUrl, content))
  {
    var statusCode = (int)res.StatusCode;

    if (statusCode == 200)
    {
      var httpStream = await res.Content.ReadAsStreamAsync();
      var outputFilePath = Path.GetTempFileName();
      using (var fileStream = File.Create(outputFilePath))
      using (var reader = new StreamReader(httpStream))
      {
        httpStream.CopyTo(fileStream);
        fileStream.Flush();
      }
      // outputFilePath contains the PDF output
    }
    else
    {
      // retry, then handle error
      throw new Exception("Unexpected response code: " + statusCode);
    }
  }
}

API access to other PDF tools?

We do not offer API access to other PDF tools at the moment (Eg: merge, compress, etc).