Link Search Menu Expand Document

PDF from URL (URL to PDF)

Description: Create PDF from URL. POST request.

Status Errors

CodeDescription
200The request has succeeded
400bad input parameters
401unauthorized
403not enough credits
405Timeout error. To process large documents or files please use asynchronous mode ( set async parameter to true) and then check the status using /job/check endpoint. If file contains many pages then specify a page range using pages parameter. The number of pages of the document can be obtained using the endpoint /pdf/info

Available methods

[POST] /pdf/convert/from/url

Generate PDF from URL or link to HTML page. You can set the following params:

  • url required. Link to input HTML file or website page to be converted. You can pass link to file from Google Drive, Dropbox or another online file service that can generate shareable links. You can also use built-in PDF.co cloud storage located at https://app.pdf.co/files or upload your file as temporary file right before making this API call (see Upload and Manage Files section for more details on uploading files via API).
  • async optional. Set to true to run as async job in background (recommended for heavy documents).
  • margins optional. set to css style margins like 10px, 5mm, 5in for all sides or 5px 5px 5px 5px (the order of margins is top, right, bottom, left).
  • paperSize optional. Letter is set by default. Can be Letter, Legal, Tabloid, Ledger, A0, A1, A2, A3, A4, A5, A6 or a custom size. Custom size can be set in px (pixels), mm or in (inches) with width and height separated by space like this: 200 300, 200px 300px, 200mm 300mm, 20cm 30cm or 6in 8in.
  • orientation optional. set to Portrait or Landscape. Portrait by default.
  • printBackground optional. true by default. Set to false to disable printing of background.
  • DoNotWaitFullLoad optional. false by default. Set to true to skip waiting for full load (like full video load etc that may affect the total conversion time).
  • templateData optional. You can also use Handlebars & Mustache style html templates. Set templateData to the string representsation of input JSON data for your template

Sample template: https://bytescout-com.s3-us-west-2.amazonaws.com/files/cloudapi-templates/template-invoice-1.html

Example input data for this template:

{
        "invoice": {
            "id": "0021",
            "date": "August 29, 2041",
            "dateDue": "September 29, 2041"
        },
        "issuer": {
            "name": "Sarah Connor",
            "company": "T-800 Research Lab",
            "address": "435 South La Fayette Park Place, Los Angeles, CA 90057",
            "website": "www.example.com",
            "email": "info@example.com"
        },
        "client": {
            "name": "Cyberdyne Systems",
            "company": "Cyberdyne Systems",
            "address": "18144 El Camino Real, Sunnyvale, California"
        }
}

Note: you should set templateData to the escaped version (use JSON.stringify(object) or similar). For a sample on using templates please check PDF from HTML Template set of samples below.

  • header optional. Set to HTML for header to be applied on every page at the header.
  • footer optional. Set to HTML for footer to be applied on every page at the bottom.

The header and footer params should contain valid HTML markup with the following classes used to inject printing values into them:

date: formatted print date title: document title url: document location pageNumber: current page number totalPages: total pages in the document

For example, the following markup will generate Page N of NN page numbering:

<span style='font-size:10px'>Page <span class='pageNumber'></span> of <span class='totalPages'></span>.</span>

Sample JSON for PDF generation with more advanced header and footer. Note that the top and bottom page margins are important because the page content may overlap the footer or header.

{
 "url": "https://wikipedia.org",
  "async": false,
  "encrypt": false,
  "name": "result.pdf",
  "margins": "40px 5px 40px 5px",
  "paperSize": "Letter",
  "orientation": "Portrait",
  "printBackground": true,
  "header": "<div style='width:100%'><span style='font-size:10px;margin-left:20px;width:50%;float:left'>LEFT SUBHEADER</span><span style='font-size:8px;width:30%;float:right'>RIGHT SUBHEADER</span></div>",
  "footer": "<div style='width:100%;text-align:right'><span style='font-size:10px;margin-right:20px'>Page <span class='pageNumber'></span> of <span class='totalPages'></span>.</span></div>"
}
  • profiles optional. Must be a Strings containing JSON profile. You can set additional and extra options using this parameter that allows you to set custom configuration. See profiles samples for examples.

Description

  • Method: POST
  • URL: /v1/pdf/convert/from/url

Query parameters

No query parameters accepted.

Body payload

{
    "url": "https://wikipedia.org/wiki/Wikipedia:Contact_us",
    "margins": "5mm",
    "paperSize": "Letter",
    "orientation": "Portrait",
    "printBackground": true,
    "header": "",
    "footer": "",
    "async": false,
    "encrypt": false,
    "profiles": "{ \"CustomScript\": \";; // put some custom js script here \"}"
}

Example responses

JSON POST /pdf/convert/from/url
{
    "url": "https://pdf-temp-files.s3.amazonaws.com/980bc13f061344809c75e83ce181851c/Contact_us.pdf",
    "pageCount": 3,
    "error": false,
    "status": 200,
    "name": "Contact_us.pdf",
    "remainingCredits": 60637
}

Code Snippets

CURL
curl --location --request POST 'https://api.pdf.co/v1/pdf/convert/from/url' \
--header 'x-api-key: ' \
--header 'Content-Type: application/json' \
--data-raw '{
    "url": "https://wikipedia.org/wiki/Wikipedia:Contact_us",
    "margins": "5mm",
    "paperSize": "Letter",
    "orientation": "Portrait",
    "printBackground": true,
    "header": "",
    "footer": "",
    "async": false,
    "encrypt": false,
    "profiles": "{ \"CustomScript\": \";; // put some custom js script here \"}"
}'
JavaScript
var myHeaders = new Headers();
myHeaders.append("x-api-key", "");
myHeaders.append("Content-Type", "application/json");

var raw = JSON.stringify({
 "url": "https://wikipedia.org/wiki/Wikipedia:Contact_us",
 "margins": "5mm",
 "paperSize": "Letter",
 "orientation": "Portrait",
 "printBackground": true,
 "header": "",
 "footer": "",
 "async": false,
 "encrypt": false,
 "profiles": "{ \"CustomScript\": \";; // put some custom js script here \"}"
});

var requestOptions = {
	method: 'POST',
	headers: myHeaders,
	body: raw,
	redirect: 'follow'
};

fetch("https://api.pdf.co/v1/pdf/convert/from/url", requestOptions)
	.then(response => response.text())
	.then(result => console.log(result))
	.catch(error => console.log('error', error));
NodeJs
var request = require('request');
var options = {
	'method': 'POST',
	'url': 'https://api.pdf.co/v1/pdf/convert/from/url',
	'headers': {
		'x-api-key': '',
		'Content-Type': 'application/json'
	},
	body: JSON.stringify({
	 "url": "https://wikipedia.org/wiki/Wikipedia:Contact_us",
	 "margins": "5mm",
	 "paperSize": "Letter",
	 "orientation": "Portrait",
	 "printBackground": true,
	 "header": "",
	 "footer": "",
	 "async": false,
	 "encrypt": false,
	 "profiles": "{ \"CustomScript\": \";; // put some custom js script here \"}"
	})

};
request(options, function (error, response) {
	if (error) throw new Error(error);
	console.log(response.body);
});

PHP
<?php

$curl = curl_init();

curl_setopt_array($curl, array(
	CURLOPT_URL => 'https://api.pdf.co/v1/pdf/convert/from/url',
	CURLOPT_RETURNTRANSFER => true,
	CURLOPT_ENCODING => '',
	CURLOPT_MAXREDIRS => 10,
	CURLOPT_TIMEOUT => 0,
	CURLOPT_FOLLOWLOCATION => true,
	CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
	CURLOPT_CUSTOMREQUEST => 'POST',
	CURLOPT_POSTFIELDS =>'{
    "url": "https://wikipedia.org/wiki/Wikipedia:Contact_us",
    "margins": "5mm",
    "paperSize": "Letter",
    "orientation": "Portrait",
    "printBackground": true,
    "header": "",
    "footer": "",
    "async": false,
    "encrypt": false,
    "profiles": "{ \\"CustomScript\\": \\";; // put some custom js script here \\"}"
}',
	CURLOPT_HTTPHEADER => array(
		'x-api-key: ',
		'Content-Type: application/json'
	),
));

$response = curl_exec($curl);

curl_close($curl);
echo $response;

Java
import java.io.*;
import okhttp3.*;
public class main {
	public static void main(String []args) throws IOException{
		OkHttpClient client = new OkHttpClient().newBuilder()
			.build();
		MediaType mediaType = MediaType.parse("application/json");
		RequestBody body = RequestBody.create(mediaType, "{\n    \"url\": \"https://wikipedia.org/wiki/Wikipedia:Contact_us\",\n    \"margins\": \"5mm\",\n    \"paperSize\": \"Letter\",\n    \"orientation\": \"Portrait\",\n    \"printBackground\": true,\n    \"header\": \"\",\n    \"footer\": \"\",\n    \"async\": false,\n    \"encrypt\": false,\n    \"profiles\": \"{ \\\"CustomScript\\\": \\\";; // put some custom js script here \\\"}\"\n}");
		Request request = new Request.Builder()
			.url("https://api.pdf.co/v1/pdf/convert/from/url")
			.method("POST", body)
			.addHeader("x-api-key", "")
			.addHeader("Content-Type", "application/json")
			.build();
		Response response = client.newCall(request).execute();
		System.out.println(response.body().string());
	}
}

C#
using System;
using RestSharp;
namespace HelloWorldApplication {
	class HelloWorld {
		static void Main(string[] args) {
			var client = new RestClient("https://api.pdf.co/v1/pdf/convert/from/url");
			client.Timeout = -1;
			var request = new RestRequest(Method.POST);
			request.AddHeader("x-api-key", "");
			request.AddHeader("Content-Type", "application/json");
			var body = @"{" + "\n" +
			@"    ""url"": ""https://wikipedia.org/wiki/Wikipedia:Contact_us""," + "\n" +
			@"    ""margins"": ""5mm""," + "\n" +
			@"    ""paperSize"": ""Letter""," + "\n" +
			@"    ""orientation"": ""Portrait""," + "\n" +
			@"    ""printBackground"": true," + "\n" +
			@"    ""header"": """"," + "\n" +
			@"    ""footer"": """"," + "\n" +
			@"    ""async"": false," + "\n" +
			@"    ""encrypt"": false," + "\n" +
			@"    ""profiles"": ""{ \""CustomScript\"": \"";; // put some custom js script here \""}""" + "\n" +
			@"}";
			request.AddParameter("application/json", body,  ParameterType.RequestBody);
			IRestResponse response = client.Execute(request);
			Console.WriteLine(response.Content);
		}
	}
}

Python
import requests
import json

url = "https://api.pdf.co/v1/pdf/convert/from/url"

payload = json.dumps({
 "url": "https://wikipedia.org/wiki/Wikipedia:Contact_us",
 "margins": "5mm",
 "paperSize": "Letter",
 "orientation": "Portrait",
 "printBackground": True,
 "header": "",
 "footer": "",
 "async": False,
 "encrypt": False,
 "profiles": "{ \"CustomScript\": \";; // put some custom js script here \"}"
})
headers = {
	'x-api-key': '',
	'Content-Type': 'application/json'
}

response = requests.request("POST", url, headers=headers, data=payload)

print(response.text)

Powershell
$headers = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
$headers.Add("x-api-key", "")
$headers.Add("Content-Type", "application/json")

$body = "{`n    `"url`": `"https://wikipedia.org/wiki/Wikipedia:Contact_us`",`n    `"margins`": `"5mm`",`n    `"paperSize`": `"Letter`",`n    `"orientation`": `"Portrait`",`n    `"printBackground`": true,`n    `"header`": `"`",`n    `"footer`": `"`",`n    `"async`": false,`n    `"encrypt`": false,`n    `"profiles`": `"{ `\`"CustomScript`\`": `\`";; // put some custom js script here `\`"}`"`n}"

$response = Invoke-RestMethod 'https://api.pdf.co/v1/pdf/convert/from/url' -Method 'POST' -Headers $headers -Body $body
$response | ConvertTo-Json