Pdf Merge API

SelectPdf Pdf Merge REST API is an online solution that lets you merge local or remote PDFs into a final PDF document. The API is easy to use, the integration can be done in a few minutes with only a few lines of code.

GET A DEMO LICENSE KEY NOW

The free trial key for the online API is valid for 7 days and it includes 200 conversions.

Features

  • Merge local PDF document.
  • Merge remote PDF from public url.
  • Set PDF viewer options and PDF document information.
  • Secure generated PDF with a password.
  • Works in all programming languages.

Usage

It’s very easy to use SelectPdf Pdf Merge REST API. All you need is a license key and you will be able to merge your PDFs in an instant. If you want to see how to do this in PHP, Java, Ruby, Python, Perl, Node.JS, C# or VB.net, click here to go directly to the coding examples.

Here is a basic usage example using a POST request:

API endpoint: https://selectpdf.com/api2/pdfmerge/
Method: POST
Content Type: multipart/form-data

POST /api2/pdfmerge/ HTTP/1.1
Content-Type: multipart/form-data; boundary=—011000010111000001101001
Host: selectpdf.com
Content-Length: 543

—–011000010111000001101001
Content-Disposition: form-data; name=”key”

_put___your___license___key___here__
—–011000010111000001101001
Content-Disposition: form-data; name=”files_no”

2
—–011000010111000001101001
Content-Disposition: form-data; name=”url_1″

https://selectpdf.com/demo/files/selectpdf.pdf
—–011000010111000001101001
Content-Disposition: form-data; name=”url_2″

https://selectpdf.com/demo/files/selectpdf.pdf
—–011000010111000001101001–

Options

Mandatory Parameters

SelectPdf Pdf Merge REST API has only 2 mandatory parameters. The rest of the parameters are optional. When they are missing, the default value is used.

Parameter Description
key Your API license key
files_no Number of PDF files that will be merged

Merged PDF documents

PDF documents that will be merged can be specified using public urls or local files can be uploaded. There is a naming convention for these files:

– url_{idx} (used for remote urls)

  –or–

– file_{idx} (used for uploaded files)
 

{idx} will be a number from 1 to the value specified in files_no parameter.
An additional password_{idx} parameter can be specified for each file, if a password is needed to access the PDF.

For example, if 4 files are merged, the parameters sent to the API should look like this:

url_1 – remote url
(optional password_1)

file_2 – local uploaded file
(optional password_2)

url_3 – remote url
(optional password_3)

file_4 – local uploaded file
(optional password_4)

Pdf Options

Use the following parameters to control the PDF document information, security and the look when the document is opened in a client PDF viewer.

Parameter Description
doc_title Specifies the pdf document title.
doc_subject Specifies the subject of the pdf document.
doc_keywords Specifies the pdf document keywords.
doc_author Specifies the name of the pdf document author.
doc_add_creation_date If this is set, the date and time when the pdf document was created is saved in pdf document information. All possible values are: True, False. The default value is False.
   
viewer_page_layout Sets the page layout to be used when the document is opened. All possible values:
  0 – Single Page (displays one page at a time),
  1 – One Column (displays the pages in one column),
  2 – Two Column Left (displays the pages in two columns, with odd-numbered pages on the left),
  3 – Two Column Right (displays the pages in two columns, with odd-numbered pages on the right).
The default value is 1 – One Column.
viewer_page_mode Sets the document page mode when the pdf document is opened in a pdf viewer. All possible values:
  0 – Use None (neither document outline / bookmarks nor thumbnail images are visible)
  1 – Use Outlines (document outline / bookmarks are visible)
  2 – Use Thumbs (page thumbnail images are visible)
  3 – Full Screen (full-screen mode, with no menu bar, window controls or any other window visible)
  4 – Use OC (optional content group panel is visible)
  5 – Use Attachments (document attachments are visible)
The default value is 0 – Use None.
viewer_center_window Sets a flag specifying whether to position the document’s window in the center of the screen. All possible values are: True, False. The default value is False.
viewer_display_doc_title Sets a flag specifying whether the window’s title bar should display the document title taken from document information. All possible values are: True, False. The default value is False.
viewer_fit_window Sets a flag specifying whether to resize the document’s window to fit the size of the first displayed page. All possible values are: True, False. The default value is False.
viewer_hide_menu_bar Sets a flag specifying whether to hide the pdf viewer application’s menu bar when the document is active. All possible values are: True, False. The default value is False.
viewer_hide_toolbar Sets a flag specifying whether to hide the pdf viewer application’s tool bars when the document is active. All possible values are: True, False. The default value is False.
viewer_hide_window_ui Sets a flag specifying whether to hide user interface elements in the document’s window (such as scroll bars and navigation controls), leaving only the document’s contents displayed. All possible values are: True, False. The default value is False.
   
user_password Specifies a password needed to be able to view the generated pdf document.
owner_password Specifies a password needed to be able to view or modify the generated pdf document.
   
pdf_name Specifies the name of the pdf document that will be created. The default value is Document.pdf.

Return Codes

Our API returns HTTP response codes, which you can check to see if the conversion was successful or not. Here is the list of HTTP codes used by SelectPdf REST API:

Code Description
200 OK The API call succeeded.
400 Bad Request Uploaded PDF files or urls do not match the specified number of files or naming conventions. The body of the response contains an explanation in plain text.
401 Authorization Required License key not specified or invalid. The body of the response contains an explanation in plain text.
415 Unsupported Media Type The PDF Merge API requires data to be posted as multipart/form-data.
499 Custom Conversion error. The body of the response contains an explanation in plain text.

Remarks

  • Concurrency: depending on payment plan, the following number of concurrent requests can be sent to the API:
      Free Trial – 1 request
      Entry Level – 2 requests
      Standard Level – 4 requests
      Advanced Level – 8 requests
      Premium Level – 8 requests
      Ultra Level – 16 requests
      Dedicated Level – 16 requests.

    If more requests are sent, they are either queued or rejected with a Too Many Requests error.

  • PDF file size: The API accepts files up to 100Mb. Each 50 pages is counted as 1 conversion credit.

Code Examples

Pdf Merge in PHP

<?php
require("SelectPdf.Api.php");

$testUrl = "https://selectpdf.com/demo/files/selectpdf.pdf";
$testPdf = "Input.pdf";
$localFile = "Result.pdf";
$apiKey = "Your API key here";

echo ("This is SelectPdf-" . SelectPdf\Api\ApiClient::CLIENT_VERSION . ".\n");

try {
    $client = new SelectPdf\Api\PdfMergeClient($apiKey);

    // specify the pdf files that will be merged (order is preserved in the final pdf)
    $client
        ->addFile($testPdf)        // add PDF from local file
        ->addUrlFile($testUrl)     // add PDF from public url
        // ->addFile($testPdf, "pdf_password")     // protected PDF from local file
        // ->addUrlFile($testUrl, "pdf_password")  // protected PDF from public url
    ;

    echo ("Starting pdf merge ...\n");

    // merge pdfs to local file
    $client->saveToFile($localFile);

    // merge pdfs to memory
    // $pdf = $client->save();

    echo ("Finished! Number of pages: " . $client->getNumberOfPages() . ".\n");

    // get API usage
    $usageClient = new \SelectPdf\Api\UsageClient($apiKey);
    $usage = $usageClient->getUsage(false);
    echo ("Conversions remained this month: " . $usage["available"] . ".\n");
}
catch (Exception $ex) {
    echo ("An error occurred: " . $ex . ".\n");
}
?>

// Code snippet uses the SelectPdf API Client library for PHP.

Pdf Merge in Java

package com.selectpdf;

public class PdfMerge {
    public static void main(String[] args) throws Exception {
        String testUrl = "https://selectpdf.com/demo/files/selectpdf.pdf";
        String testPdf = "Input.pdf";
        String localFile = "Result.pdf";
        String apiKey = "Your API key here";

        System.out.println(String.format("This is SelectPdf-%s.", ApiClient.CLIENT_VERSION));

        try {
            PdfMergeClient client = new PdfMergeClient(apiKey);

            // specify the pdf files that will be merged (order is preserved in the final pdf)
            client
                .addFile(testPdf)         // add PDF from local file
                .addUrlFile(testUrl)      // add PDF from public url
                // .addFile(testPdf, "pdf_password")    // protected PDF from local file
                // .addUrlFile(testUrl, "pdf_password") // protected PDF from public url
            ;

            System.out.println("Starting pdf merge...");

            // merge pdfs to local file
            client.saveToFile(localFile);

            // merge pdfs to memory
            // byte[] pdf = client.save();

            System.out.println(String.format("Finished! Number of pages: %d.", client.getNumberOfPages()));

            // get API usage
            UsageClient usageClient = new UsageClient(apiKey);
            String usage = usageClient.getUsage(false);
            System.out.printf("Usage details: %s.%n", usage);
        }
        catch (Exception ex) {
            System.out.println("An error occurred: " + ex.getMessage());
        }
    }
}

// Code snippet uses the SelectPdf API Client library for Java.

Pdf Merge in Ruby

require 'selectpdf'

$stdout.sync = true

print "This is SelectPdf-#{SelectPdf::CLIENT_VERSION}\n"

test_url = 'https://selectpdf.com/demo/files/selectpdf.pdf'
test_pdf = 'Input.pdf'
local_file = 'Result.pdf'
api_key = 'Your API key here'

begin
  client = SelectPdf::PdfMergeClient.new(api_key)

  # specify the pdf files that will be merged (order is preserved in the final pdf)
  client.add_file(test_pdf)        # add PDF from local file
  client.add_url_file(test_url)    # add PDF from public url
  # client.add_file(test_pdf, 'pdf_password')     # protected PDF from local file
  # client.add_url_file(test_url, 'pdf_password') # protected PDF from public url

  print "Starting pdf merge ...\n"

  # merge pdfs to local file
  client.save_to_file(local_file)

  # merge pdfs to memory
  # pdf = client.save

  print "Finished! Number of pages: #{client.number_of_pages}.\n"

  # get API usage
  usage_client = SelectPdf::UsageClient.new(api_key)
  usage = usage_client.get_usage(false)
  print('Conversions remained this month: ', usage['available'], "\n")
rescue SelectPdf::ApiException => e
  print("An error occurred: #{e}")
end

# Code snippet uses the SelectPdf API Client library for Ruby.

Pdf Merge in Python

# -*- coding: utf-8 -*-

import selectpdf

testUrl = "https://selectpdf.com/demo/files/selectpdf.pdf"
testPdf = "Input.pdf"
localFile = "Result.pdf"
apiKey = "Your API key here"

print ("This is SelectPdf-{0}.".format(selectpdf.CLIENT_VERSION))

try:
    client = selectpdf.PdfMergeClient(apiKey)

    # specify the pdf files that will be merged (order is preserved in the final pdf)
    client.addFile(testPdf)        # add PDF from local file
    client.addUrlFile(testUrl)     # add PDF from public url
    # client.addFileWithPassword(testPdf, "pdf_password")     # protected PDF from local file
    # client.addUrlFileWithPassword(testUrl, "pdf_password")  # protected PDF from public url

    print ("Starting pdf merge ...")

    # merge pdfs to local file
    client.saveToFile(localFile)

    # merge pdfs to memory
    # pdf = client.save()

    print ("Finished! Number of pages: {0}.".format(client.getNumberOfPages()))

    # get API usage
    usageClient = selectpdf.UsageClient(apiKey)
    usage = usageClient.getUsage()
    print ("Conversions remained this month: {0}.".format(usage["available"]))

except selectpdf.ApiException as ex:
    print ("An error occurred: {0}.".format(ex.getMessage()))

# Code snippet uses the SelectPdf API Client library for Python.

Pdf Merge in C#

using System;
using SelectPdf.Api;

namespace Samples
{
    public class PdfMerge
    {
        public static void Main()
        {
            string testUrl = "https://selectpdf.com/demo/files/selectpdf.pdf";
            string testPdf = "Input.pdf";
            string localFile = "Result.pdf";
            string apiKey = "Your API key here";

            Console.WriteLine("This is SelectPdf-{0}.", ApiClient.CLIENT_VERSION);

            try
            {
                PdfMergeClient client = new PdfMergeClient(apiKey);

                // specify the pdf files that will be merged (order is preserved in the final pdf)
                client
                    .addFile(testPdf)         // add PDF from local file
                    .addUrlFile(testUrl)      // add PDF from public url
                    // .addFile(testPdf, "pdf_password")    // protected PDF from local file
                    // .addUrlFile(testUrl, "pdf_password") // protected PDF from public url
                ;

                Console.WriteLine("Starting pdf merge ...");

                // merge pdfs to local file
                client.saveToFile(localFile);

                // merge pdfs to memory
                // byte[] pdf = client.save();

                Console.WriteLine("Finished! Number of pages: {0}.", client.getNumberOfPages());

                // response telemetry (SDK 1.5.0+)
                Console.WriteLine("Mode: {0}, Execution: {1}.", client.Mode, client.ExecutionMode);
                Console.WriteLine("Credits remaining: {0} / {1}.",
                    client.CreditsRemaining, client.CreditsTotal);

                // get API usage
                UsageClient usageClient = new UsageClient(apiKey);
                UsageInformation usage = usageClient.getUsage(false);
                Console.WriteLine("Conversions remained this month: {0}.", usage.Available);
            }
            catch (ApiException ex)
            {
                Console.WriteLine("API error: {0}", ex.Message);
            }
            catch (Exception ex)
            {
                Console.WriteLine("An error occurred: " + ex.Message);
            }
        }
    }
}

// Code snippet uses the SelectPdf API Client library for .NET.

Pdf Merge in Go

There is no dedicated Go client library for the SelectPdf API. The example below uses Go’s standard library to POST a multipart/form-data request directly to the API endpoint.

package main

import (
    "bytes"
    "fmt"
    "io"
    "mime/multipart"
    "net/http"
    "os"
)

func main() {
    apiEndpoint := "https://selectpdf.com/api2/pdfmerge/"
    apiKey := "Your API key here"
    localPdf := "Input.pdf"
    remotePdf := "https://selectpdf.com/demo/files/selectpdf.pdf"
    outFile := "Result.pdf"

    body := &bytes.Buffer{}
    writer := multipart.NewWriter(body)

    // mandatory parameters
    _ = writer.WriteField("key", apiKey)
    _ = writer.WriteField("files_no", "2")

    // file 1 - local upload via file_1
    f, err := os.Open(localPdf)
    if err != nil { panic(err) }
    defer f.Close()
    part, err := writer.CreateFormFile("file_1", localPdf)
    if err != nil { panic(err) }
    if _, err := io.Copy(part, f); err != nil { panic(err) }

    // file 2 - remote pdf via url_2
    _ = writer.WriteField("url_2", remotePdf)

    // optional: pdf options
    _ = writer.WriteField("doc_title", "Merged document")
    // _ = writer.WriteField("password_1", "pdf_password") // password for file_1 if required
    // _ = writer.WriteField("user_password", "open_pass") // protect output PDF

    if err := writer.Close(); err != nil { panic(err) }

    req, err := http.NewRequest("POST", apiEndpoint, body)
    if err != nil { panic(err) }
    req.Header.Set("Content-Type", writer.FormDataContentType())

    resp, err := http.DefaultClient.Do(req)
    if err != nil { panic(err) }
    defer resp.Body.Close()

    if resp.StatusCode != http.StatusOK {
        msg, _ := io.ReadAll(resp.Body)
        fmt.Printf("API error %d: %s\n", resp.StatusCode, string(msg))
        return
    }

    out, err := os.Create(outFile)
    if err != nil { panic(err) }
    defer out.Close()
    if _, err := io.Copy(out, resp.Body); err != nil { panic(err) }

    fmt.Printf("Finished! Pages: %s. Saved to %s.\n",
        resp.Header.Get("X-SelectPdf-Pages"), outFile)
}

Pdf Merge in Node.js

var selectpdf = require('selectpdf');

console.log("This is SelectPdf-%s.", selectpdf.CLIENT_VERSION);

try {
    var testUrl = 'https://selectpdf.com/demo/files/selectpdf.pdf';
    var testPdf = 'Input.pdf';
    var localFile = 'Result.pdf';
    var apiKey = 'Your API key here';

    var client = new selectpdf.PdfMergeClient(apiKey);

    // specify the pdf files that will be merged (order is preserved in the final pdf)
    client
        .addFile(testPdf)         // add PDF from local file
        .addUrlFile(testUrl)      // add PDF from public url
        // .addFile(testPdf, "pdf_password")    // protected PDF from local file
        // .addUrlFile(testUrl, "pdf_password") // protected PDF from public url
    ;

    console.log('Starting pdf merge ...');

    // merge pdfs to local file
    client.saveToFile(localFile,
        function(err, fileName) {
            if (err) return console.error("An error occurred: " + err);
            console.log("Finished! Result is in file '" + fileName +
                "'. Number of pages: " + client.getNumberOfPages());

            var usageClient = new selectpdf.UsageClient(apiKey);
            usageClient.getUsage(false, function(err2, data) {
                if (err2) return console.error("Usage error: " + err2);
                console.log("Conversions remained this month: " + data["available"]);
            });
        }
    );

    // merge pdfs to memory
    /*
    client.save(function(err, pdf) {
        if (err) return console.error("An error occurred: " + err);
        console.log("Finished! Result is in variable 'pdf'. Pages: " + client.getNumberOfPages());
    });
    */
}
catch (ex) {
    console.log("An error occurred: " + ex);
}

// Code snippet uses the SelectPdf API Client library for Node.js.

Test SelectPdf PDF Merge online RESTful API Now

Request a Demo License Key for SelectPdf REST API right now. Feel free to ask any questions if needed.
The free trial key for the online API is valid for 7 days and it includes 200 conversions.

SelectPdf for Cloud’s platform independent Pdf Merge API is a true REST API that can be used with any language: .NET, Java, PHP, Ruby, Rails, Python, jQuery and many more. You can use it with any language or platform that supports REST. Almost all platforms and languages support REST and provide native REST clients to work with REST APIs. You do not need to worry about language or platform limitations. You can use it with any platform – web, desktop, mobile, and cloud. Try now for free the best API to Merge PDFs.