Web to PDF API code samples
Choose your favorite language, put in your customer key and you got it!
#!/bin/bash
CUSTOMER_KEY="PUT_YOUR_CUSTOMER_KEY_HERE"
SECRET_PHRASE="" #leave secret phrase empty, if not needed
URL="https://www.google.com"
PAPER="letter"
ORIENTATION="portrait"
MEDIA="print"
BG="nobg"
DELAY="2000"
SCALE="50"
ARGS=(
--data-urlencode "key=$CUSTOMER_KEY" \
--data-urlencode "paper=$PAPER" \
--data-urlencode "orientation=$ORIENTATION" \
--data-urlencode "media=$MEDIA" \
--data-urlencode "bg=$BG" \
--data-urlencode "delay=$DELAY" \
--data-urlencode "scale=$SCALE" \
--data-urlencode "url=$URL"
)
if [[ -n "$SECRET_PHRASE" ]]; then
HASH=$(echo -n $URL$SECRET_PHRASE | md5sum | cut -d ' ' -f 1)
ARGS+=(--data-urlencode "hash=$HASH")
fi
curl -Gs "https://pdfapi.screenshotmachine.com" "${ARGS[@]}" > output.pdf
Complete source code is available on GitHub
string customerKey = "PUT_YOUR_CUSTOMER_KEY_HERE";
string secretPhrase = ""; //leave secret phrase empty, if not needed
var options = new Dictionary();
// mandatory parameter
options.Add("url", "https://www.google.com");
// all next parameters are optional, see our website to PDF API guide for more details
options.Add("paper", "letter");
options.Add("orientation", "portrait");
options.Add("media", "print");
options.Add("bg", "nobg");
options.Add("delay", "2000");
options.Add("scale", "50");
ScreenshotMachine sm = new ScreenshotMachine(customerKey, secretPhrase);
string pdfApiUrl = sm.GeneratePdfApiUrl(options);
//save PDF file
string output = "output.pdf";
new WebClient().DownloadFile(pdfApiUrl, output);
Console.Write("Pdf saved as " + output);
Complete source code is available on GitHub
String customerKey = "PUT_YOUR_CUSTOMER_KEY_HERE";
String secretPhrase = "";//leave secret phrase empty, if not needed
ScreenshoMachine sm = new ScreenshoMachine(customerKey, secretPhrase);
Map options = new HashMap();
// mandatory parameter
options.put("url", "https://www.google.com");
// all next parameters are optional, see our website to PDF API guide for more details
options.put("paper", "letter");
options.put("orientation", "portrait");
options.put("media", "print");
options.put("bg", "nobg");
options.put("delay", "2000");
options.put("scale", "50");
String pdfApiUrl = sm.generatePdfApiUrl(options);
//save PDF file
URLConnection openConnection = new URL(pdfApiUrl).openConnection();
openConnection.addRequestProperty("User-Agent", "Mozilla/4.0");
InputStream in = openConnection.getInputStream();
String output = "out.pdf";
Files.copy(in, Paths.get(output), StandardCopyOption.REPLACE_EXISTING);
System.out.println("Pdf saved as " + output);
See our official npm package. Complete source code is available on GitHub.
// npm install screenshotmachine --save
var screenshotmachine = require('screenshotmachine');
var customerKey = 'PUT_YOUR_CUSTOMER_KEY_HERE';
secretPhrase = ''; //leave secret phrase empty, if not needed
options = {
//mandatory parameter
url : 'https://www.google.com',
// all next parameters are optional, see our website to PDF API guide for more details
paper : 'letter',
orientation : 'portrait',
media: 'print',
bg: 'nobg',
delay: '2000',
scale: '50'
}
var pdfApiUrl = screenshotmachine.generatePdfApiUrl(customerKey, secretPhrase, options);
//save PDF file
var fs = require('fs');
var output = 'output.pdf';
screenshotmachine.readScreenshot(pdfApiUrl).pipe(fs.createWriteStream(output).on('close', function() {
console.log('Pdf saved as ' + output);
}));
Complete source code is available on GitHub
#!/usr/bin/perl
use strict;
use warnings;
use LWP::UserAgent;
use URI::Escape qw(uri_escape);
use Digest::MD5 qw(md5_hex);
my $base_pdf_api_url = 'https://pdfapi.screenshotmachine.com/?';
my $customer_key = 'PUT_YOUR_CUSTOMER_KEY_HERE';
my $secret_phrase = ''; # leave secret phrase empty, if not needed
my %options;
# mandatory parameter
$options{'url'} = 'https://www.google.com';
# all next parameters are optional, see our website to PDF API guide for more details
$options{'paper'} = 'letter';
$options{'orientation'} = 'portrait';
$options{'media'} = 'print';
$options{'bg'} = 'nobg';
$options{'delay'} = '2000';
$options{'scale'} = '50';
my $api_url = $base_pdf_api_url . 'key=' . $customer_key;
if ($secret_phrase ne "")
{
$api_url .= '&hash=' . md5_hex($options{'url'} . $secret_phrase);
}
foreach my $key (keys %options)
{
$api_url .= '&' . $key . '=' . uri_escape($options{$key});
}
#save PDF file
my $lwp = LWP::UserAgent->new(agent=>'perl-client', cookie_jar=>{});
my $output = 'output.pdf';
my $resp = $lwp->mirror($api_url, $output);
unless($resp->is_success) {
print $resp->status_line;
}
print "PDF saved as " . $output . "\n";
See our official Composer package. Complete source code is available on GitHub
<?php
$customer_key = "PUT_YOUR_CUSTOMER_KEY_HERE";
$secret_phrase = ""; //leave secret phrase empty, if not needed
$machine = new ScreenshotMachine($customer_key, $secret_phrase);
//mandatory parameter
$options['url'] = "https://www.google.com";
// all next parameters are optional, see our website to PDF API guide for more details
$options['paper'] = "letter";
$options['orientation'] = "portrait";
$options['media'] = "print";
$options['bg'] = "nobg";
$options['delay'] = "2000";
$options['scale'] = "50";
$pdf_api_url = $machine->generate_pdf_api_url($options);
//save PDF file
$output_file = 'output.pdf';
file_put_contents($output_file, file_get_contents($pdf_api_url));
echo 'PDF saved as ' . $output_file . PHP_EOL;
Complete source code is available on GitHub
customer_key = 'PUT_YOUR_CUSTOMER_KEY_HERE'
secret_phrase = '' # leave secret phrase empty, if not needed
options = {
'url': 'https://www.google.com', # mandatory parameter
# all next parameters are optional, see our website to PDF API guide for more details
'paper': 'letter',
'orientation': 'portrait',
'media': 'print',
'bg' : 'nobg',
'delay' : '2000',
'scale' : '50'
}
pdf_api_url = generate_pdf_api_url(customer_key, secret_phrase, options)
#save PDF file
opener = urllib.request.build_opener()
opener.addheaders = [('User-agent', '-')]
urllib.request.install_opener(opener)
output = 'output.pdf'
urllib.request.urlretrieve(pdf_api_url, output)
print('PDF saved as ' + output);
Complete source code is available on GitHub
Dim customerKey As String = "PUT_YOUR_CUSTOMER_KEY_HERE"
Dim secretPhrase As String = "" REM leave secret phrase empty, If Not needed
Dim options As New Dictionary(Of String, String)
REM mandatory parameter
options.Add("url", "https://www.google.com")
REM all next parameters are optional, see our website to PDF API guide for more details
options.Add("paper", "letter")
options.Add("orientation", "portrait")
options.Add("media", "print")
options.Add("bg", "nobg")
options.Add("delay", "2000")
options.Add("scale", "50")
Dim sm As ScreenshotMachine = New ScreenshotMachine(customerKey, secretPhrase)
Dim pdfApiUrl As String = sm.GeneratePdfApiUrl(options)
REM save PDF file
Dim client As New WebClient()
Dim output As String = "output.pdf"
client.DownloadFile(pdfApiUrl, output)
Console.WriteLine("PDF saved as " + output)
Detailed website to PDF API description
Our online webpage to PDF API is based on HTTP GET requests.
All API calls must start with https://pdfapi.screenshotmachine.com/?
followed by query parameters (field-value pairs) described in the table below. Parameters are separated by an ampersand (&
).
Parameter | Description |
---|---|
key
|
Unique customer key is required for using our service. You will get your key after sign up. |
url
|
The web page URL you want to capture. Url percent-encoding is recommended and http(s):// protocol prefix is optional.
|
paper
|
Default value is letter .Size of the pages in PDF. Available values are: letter (8.5in x 11in)legal (8.5in x 14in)ledger (11in x 17in)tabloid (17in x 11in)A0 (841mm × 1189mm)A1 (594mm × 841mm)A2 (420mm × 594mm)A3 (297mm × 420mm)A4 (210mm × 297mm)A5 (148mm × 210mm)A6 (105mm × 148mm)
|
orientation
|
Default value is portrait .Orientation of the pages in PDF. Available values are: portrait , landscape .
|
media
|
Default value is screen .Webpage can be converted into PDF as it looks in the browser, or optimized for printing. If you want to save webpage into PDF as it looks in the browser use screen parameter. But if you plan to print created PDF, use the print parameter. Using print value will produce PDF without web-specific graphics and elements which are not needed for printing. |
bg
|
Default value is bg .Flag indicate if website background should be added into PDF. Available values are: bg (add background), nobg (no background).
|
delay
|
Default value is 200 .Allowed values are: ( 0, 200,400, 600, 800, 1000, 2000, 3000, 4000, 5000, 6000, 7000, 8000, 9000, 10000 )Using delay parameter, you can manage how long converting engine should wait before the webpage is converted into PDF file. This parameter is useful when you want to capture a webpage with some fancy animation and you want to wait until the animation finish.Examples: delay=0 : convert website immediatelydelay=200 : wait 200ms before convertingdelay=400 : wait 400ms before convertingetc... |
scale
|
Default value is 100 percent.Allowed values are: ( 10 - 200 )Using scale parameter, you can manage zoom scale of the webpage content before website is converted int PDF file. This parameter is useful when you want to save website to PDF with smaller number of pages.Examples: scale=100 : default scale factor, original website sizescale=50 : half-size website, 50% of its original sizescale=200 : website is zoomed to double size
|
hash
|
If you are calling our service directly from the public HTML pages, we suggest you to safeguard your account with hash parameter. The hash parameter value is calculated using MD5 algorithm from url parameter value and secret phrase.
PHP code example:
Result is: ac502de622959ae5f59a6bdc2346771e
Your secret phrase can be set in your account settings and when you set your secret phrase, all requests with missing or incorrect |
click
|
Allowed values: Any valid CSS selector. More info about selectors can be found in CSS Selector Reference. Using click parameter you can trigger the "click" event on any HTML element before webpage is saved as PDF document. Useful for accepting annoying GDPR or cookie banners.Examples:
# character or any others reserved characters.
|
hide
|
Allowed values: Any valid CSS selectors separated by comma. More info about selectors can be found in CSS Selector Reference. Using hide parameter you can hide/remove any HTML element before website is saved as PDF document. Useful for hiding various GDPR/cookie banners, popup dialogs or any other web page elements.Examples:
# character or any others reserved characters.
|
cookies
|
Allowed values: A semicolon [ ; ] separated list of cookies which should be used for screenshot capturing. Each cookie contains a name-value pair. Multiple pairs must be separated by a semicolon. Percent-encoding is required.Example: Cookies data name1=value1;name2=value2 must be encoded into format name1%3Dvalue1%3Bname2%3Dvalue2 .
|
accept-language
|
Sets the Accept-Language header on request to the web page you want to capture. Using this parameter you can capture screenshot of webpage with a specific language. Percent-encoding is required when using reserved characters.Example: en-US
|
user-agent
|
Sets the User-Agent header on request to the web page you want to capture. Using this parameter you can emulate a specific device. Percent-encoding is required when using reserved characters.Example: Mozilla/5.0 (Linux; Android 10; SM-G981B) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.162 Mobile Safari/537.36 will emulate Samsung Galaxy S20 mobile phone.
|
Error Handling
Oops, sometimes bad things happens in the universe.
If your API call is invalid or incomplete, you got a JSON response with text error message. All these error responses also contains our custom HTTP response header field, named X-Screenshotmachine-Response
which contains specific error code.
Example:
X-Screenshotmachine-Response: invalid_url