Doc Converter Pro - REST API Documentation for Developers

Convert files programmatically from and to Word DOCX, DOC, PDF, RTF, ODT, TXT, JPG/PNG and HTML.


How to call our API to convert documents from within your own application

Before you begin, you need to have an account with our Doc Converter Pro Online Web App. If you do not, please register for an account now. You can test the service for free, but for production, you will need to sign up for one of our paid plans.


API Authorization

The Doc Converter Pro REST API supports two authorization methods. You can use either one — pick the method that best fits your integration.

Method 1: API Key Authentication Recommended

Header X-Api-Key: YOUR_API_KEY

An API key is a long-lived static credential that does not expire (unless you set an expiry date or revoke it). It is the simplest way to authenticate — there is no need to exchange a token first. Simply include your API key in the X-Api-Key request header (or pass it as an apikey query string parameter) on every API call.

How to get an API Key

  1. Log in to your Doc Converter Pro Online account.
  2. Open the API Keys page.
  3. Enter a name (e.g. "CI Pipeline", "My Web App") and click Create API Key.
  4. Copy the generated key immediately — for security it is shown only once. If you lose it, you can regenerate it.
Optional restrictions: Each API key can be restricted to a list of allowed IP addresses / CIDR ranges and can have an optional expiry date. You can also create multiple named keys (e.g. one per environment) and monitor usage per key from the API Keys page.
Important: Keep your API key secret. Do not embed it in client-side (browser or mobile) code, and never commit it to source control. Prefer environment variables or a secrets store. If a key is ever exposed, regenerate or delete it immediately.

Send the API Key with your requests

Header format: X-Api-Key: YOUR_API_KEY

Command line example.


curl -X GET "https://api.docconverter.pro/api/converter/conversionsinfo" \
     -H "X-Api-Key: YOUR_API_KEY"
                                

Uses the native fetch API.


const apiURL = 'https://api.docconverter.pro';
const apiKey = 'YOUR_API_KEY';

async function getConversionsInfo() {
  const response = await fetch(apiURL + '/api/converter/conversionsinfo', {
    method: 'GET',
    headers: {
      'X-Api-Key': apiKey
    },
    cache: 'no-cache',
  });

  if (!response.ok) {
    throw new Error(`HTTP error ${response.status}: ${response.statusText}`);
  }

  const result = await response.json();
  console.log('Current conversions:', result.Conversions, 'Max:', result.MaxConversions);
}

getConversionsInfo().catch(err => console.error(err.message));
                                

Requires the requests library (pip install requests).


import requests

api_url = 'https://api.docconverter.pro/api/converter/conversionsinfo'
api_key = 'YOUR_API_KEY'

headers = {
    'X-Api-Key': api_key
}

try:
    response = requests.get(api_url, headers=headers)
    response.raise_for_status()
    data = response.json()
    print(f"Current conversions: {data.get('Conversions')}, max: {data.get('MaxConversions')}")
except requests.exceptions.HTTPError as errh:
    print(f"Http Error: {errh}")
except requests.exceptions.RequestException as err:
    print(f"Request Error: {err}")
                                

Uses the cURL extension (usually enabled by default).


<?php

$apiUrl = 'https://api.docconverter.pro/api/converter/conversionsinfo';
$apiKey = 'YOUR_API_KEY';

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, $apiUrl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'X-Api-Key: ' . $apiKey,
]);

$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

if (curl_errno($ch)) {
    echo 'cURL Error: ' . curl_error($ch);
} else {
    if ($httpCode == 200) {
        $data = json_decode($response, true);
        echo "Current conversions: " . $data['Conversions'] . ", max: " . $data['MaxConversions'] . "\n";
    } else {
        echo "HTTP Error: " . $httpCode . "\nResponse: " . $response . "\n";
    }
}

curl_close($ch);

?>
                                

Uses HttpClient. Add the header once on the client, then reuse it for all calls.


using System;
using System.Net.Http;
using System.Threading.Tasks;

public class ApiKeyClient
{
    private static readonly HttpClient client = new HttpClient();

    public static async Task GetConversionsInfoAsync()
    {
        var apiUrl = "https://api.docconverter.pro/api/converter/conversionsinfo";
        var apiKey = "YOUR_API_KEY";

        using (var request = new HttpRequestMessage(HttpMethod.Get, apiUrl))
        {
            request.Headers.Add("X-Api-Key", apiKey);

            try
            {
                HttpResponseMessage response = await client.SendAsync(request);
                response.EnsureSuccessStatusCode();
                string responseBody = await response.Content.ReadAsStringAsync();
                Console.WriteLine(responseBody);
            }
            catch (HttpRequestException e)
            {
                Console.WriteLine($"Request error: {e.Message}");
            }
        }
    }
}
                                

Method 2: Bearer Token Authentication

POST https://api.docconverter.pro/token

This API call will return an access token valid for 14 days. The method requires 3 parameters (sent as application/x-www-form-urlencoded):

  • username - set your DocConverterPro email
  • password - set your DocConverterPro password
  • grant_type - set to 'password' value
Important: We strongly recommend storing the token and expiration date in some cache or database and reusing it for each conversion call. Refresh the token just before it expires. Please check the code examples on how to get and use the bearer token. The token should be sent in the Authorization header as Bearer YOUR_ACCESS_TOKEN for subsequent API calls.

Get Bearer Token - Code Examples

The following examples show how to obtain an OAuth 2.0 bearer token from the /token endpoint. Replace your@email.com and your_password with your actual Doc Converter Pro credentials.

Command line example.


curl -X POST "https://api.docconverter.pro/token" \
     -H "Content-Type: application/x-www-form-urlencoded" \
     -d "grant_type=password" \
     -d "username=your@email.com" \
     -d "password=your_password"
                

Uses the native fetch API. Ensure you handle errors appropriately in production.


const apiURL = 'https://api.docconverter.pro';

async function fetchTokenData() {
  const body = new URLSearchParams({
    grant_type: 'password',
    username: 'your@email.com',
    password: 'your_password',
  });

  const response = await fetch(apiURL + '/token', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded',
    },
    body: body,
  });

  if (!response.ok) {
    let errorData;
    try {
      errorData = await response.json();
    } catch (e) {
      errorData = { message: response.statusText };
    }
    throw new Error(`HTTP error ${response.status}: ${errorData.error_description || errorData.message || 'Failed to fetch token'}`);
  }

  const tokenData = await response.json();
  return tokenData;
}

// Example usage
async function main() {
  try {
    const tokenData = await fetchTokenData();
    console.log('Access Token:', tokenData.access_token);
    // Store and use tokenData.access_token
  } catch (error) {
    console.error('Error fetching token:', error.message);
  }
}

main();
                

Requires the requests library (pip install requests).


import requests

api_url = 'https://api.docconverter.pro/token'
username = 'your@email.com'  # Replace with your email
password = 'your_password'    # Replace with your password

payload = {
    'grant_type': 'password',
    'username': username,
    'password': password
}

headers = {
    'Content-Type': 'application/x-www-form-urlencoded'
}

try:
    response = requests.post(api_url, data=payload, headers=headers)
    response.raise_for_status()  # Raises an HTTPError for bad responses
    token_data = response.json()
    access_token = token_data.get('access_token')
    print(f"Access Token: {access_token}")
except requests.exceptions.HTTPError as errh:
    print(f"Http Error: {errh}")
    # print(f"Response content: {response.text}") # For debugging
except requests.exceptions.RequestException as err:
    print(f"Request Error: {err}")
                

Uses the cURL extension (usually enabled by default).


<?php

$apiUrl = 'https://api.docconverter.pro/token';
$username = 'your@email.com'; // Replace with your email
$password = 'your_password';   // Replace with your password

$postData = http_build_query([
    'grant_type' => 'password',
    'username'   => $username,
    'password'   => $password,
]);

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, $apiUrl);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Content-Type: application/x-www-form-urlencoded',
]);

$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

if (curl_errno($ch)) {
    echo 'cURL Error: ' . curl_error($ch);
} else {
    if ($httpCode == 200) {
        $tokenData = json_decode($response, true);
        if (isset($tokenData['access_token'])) {
            echo "Access Token: " . $tokenData['access_token'] . "\n";
        } else {
            echo "Error: Could not parse token.\nResponse: " . $response . "\n";
        }
    } else {
        echo "HTTP Error: " . $httpCode . "\nResponse: " . $response . "\n";
    }
}

curl_close($ch);

?>
                

Uses HttpClient and System.Text.Json (for .NET Core 3.0+ / .NET 5+). For older versions, consider Newtonsoft.Json.


using System;
using System.Net.Http;
using System.Threading.Tasks;
using System.Collections.Generic;
using System.Text.Json;

public class TokenFetcher
{
    private static readonly HttpClient client = new HttpClient();

    public static async Task GetAccessTokenAsync()
    {
        var apiUrl = "https://api.docconverter.pro/token";
        var username = "your@email.com";
        var password = "your_password";

        var values = new Dictionary
        {
            { "grant_type", "password" },
            { "username", username },
            { "password", password }
        };
        var content = new FormUrlEncodedContent(values);

        try
        {
            HttpResponseMessage response = await client.PostAsync(apiUrl, content);
            response.EnsureSuccessStatusCode(); 
            string responseBody = await response.Content.ReadAsStringAsync();
            
            using (JsonDocument doc = JsonDocument.Parse(responseBody))
            {
                JsonElement root = doc.RootElement;
                if (root.TryGetProperty("access_token", out JsonElement accessTokenElement))
                {
                    return accessTokenElement.GetString();
                }
            }
            return null;
        }
        catch (HttpRequestException e)
        {
            Console.WriteLine($"Request error: {e.Message}");
            // Consider logging e.InnerException or response content if available
            return null;
        }
    }

    public static async Task Main(string[] args)
    {
        string accessToken = await GetAccessTokenAsync();
        if (!string.IsNullOrEmpty(accessToken))
        {
            Console.WriteLine($"Access Token: {accessToken}");
        }
        else
        {
            Console.WriteLine("Failed to retrieve access token.");
        }
    }
}
                

Uses built-in HttpURLConnection. For production, consider libraries like OkHttp, Apache HttpClient, or Spring RestTemplate. For JSON parsing, libraries like Jackson, Gson, or org.json are recommended (example uses org.json in comments).


import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.StringJoiner;
// import org.json.JSONObject; // Add dependency: e.g., org.json:json:20231013

public class TokenFetcher {
    public static void main(String[] args) {
        String apiUrl = "https://api.docconverter.pro/token";
        String username = "your@email.com";
        String password = "your_password";

        try {
            URL url = new URL(apiUrl);
            HttpURLConnection con = (HttpURLConnection) url.openConnection();
            con.setRequestMethod("POST");
            con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            con.setDoOutput(true);

            Map parameters = new HashMap<>();
            parameters.put("grant_type", "password");
            parameters.put("username", username);
            parameters.put("password", password);

            StringJoiner sj = new StringJoiner("&");
            for (Map.Entry entry : parameters.entrySet()) {
                sj.add(URLEncoder.encode(entry.getKey(), StandardCharsets.UTF_8.name()) + "=" +
                       URLEncoder.encode(entry.getValue(), StandardCharsets.UTF_8.name()));
            }
            byte[] postDataBytes = sj.toString().getBytes(StandardCharsets.UTF_8);

            try (OutputStream os = con.getOutputStream()) {
                os.write(postDataBytes);
            }

            int responseCode = con.getResponseCode();
            System.out.println("Response Code: " + responseCode);

            if (responseCode == HttpURLConnection.HTTP_OK) {
                BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
                StringBuilder response = new StringBuilder();
                String inputLine;
                while ((inputLine = in.readLine()) != null) {
                    response.append(inputLine);
                }
                in.close();
                System.out.println("Raw Response: " + response.toString());
                // JSONObject tokenData = new JSONObject(response.toString());
                // String accessToken = tokenData.getString("access_token");
                // System.out.println("Access Token: " + accessToken);
            } else {
                System.out.println("POST request failed. Response: " + con.getResponseMessage());
                 try(BufferedReader errorReader = new BufferedReader(new InputStreamReader(con.getErrorStream()))){
                    StringBuilder errorResponse = new StringBuilder(); String errorLine;
                    while((errorLine = errorReader.readLine()) != null) { errorResponse.append(errorLine); }
                    System.out.println("Error Details: " + errorResponse.toString());
                } catch (Exception ex) {/* no error stream */}
            }
            con.disconnect();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
                


Convert Document API Call

POST https://api.docconverter.pro/api/converter/convertdoc

This API call will convert files sent via POST (as multipart/form-data) and will return URL/JSON/RawData or post back to a given URL the converted zip or output file.

⚠ View required authorization header details

Input Parameters:

  1. file - (Required) Send a Word DOCX, DOC, PDF, RTF, ODT, TXT, JPG/PNG or HTML file in a FormData (JavaScript) or as MultipartFormDataContent. Please see the sample page or other samples for implementation details.
  2. template - (Optional) Optionally specify a template name parameter, for instance: 'Convert to HTML5'. This template is used by default if a parameter is not specified. The template name has to be exactly as on your Doc Converter Pro Online templates list. You can create your own custom templates and use it. Read our conversion templates guide.
  3. returnJson - (Optional) Option to return JSON with a list of converted output file URLs. Attention: do not set returnHtml or returnData options if you want to use returnJson. Default: false.
  4. returnHtml - (Optional) Option to return either a zip file (set it to false) with all the conversion files in it or a single output file (set it to true). By default, it's set to false - return a zip file. To return only a single output file (HTML, DOCX, PDF, etc - output file format depends on the conversion template you use) set this option to true.
    • Note 1: if you set it to true then only the HTML file is returned; other files like images or CSS files are not sent. Only the zip file contains all the converted files.
    • Note 2: if you split your document into pages or use split by tag feature in the conversion template then API will return a zip file anyway.
  5. returnData - (Optional) Option to return raw octet-stream data. Default is false, and it returns a URL to the converted file on the Doc Converter Pro Web API server.
  6. backUrl - (Optional) If specified, the API method will convert the input file and will POST it back to that specified URL. Please note that you need a web server to process POST requests. Check out ASP.NET C# sample app that receives files sent via POST or this PHP sample code.

Send a document for conversion

POST a multipart/form-data body with the input document in a file part and your API key in the X-Api-Key header. The examples below also pass template and returnJson. With returnJson=true the response is a JSON array of converted file URLs. Without it, the API returns the URL of a zip archive holding all the converted files, as plain text.

Command line example that uploads mydocument.docx.


curl -X POST "https://api.docconverter.pro/api/converter/convertdoc" \
     -H "X-Api-Key: YOUR_API_KEY" \
     -F "file=@mydocument.docx" \
     -F "template=Convert to HTML5" \
     -F "returnJson=true"
                                

Browser example using the native fetch API and a file input.


const apiURL = 'https://api.docconverter.pro';
const apiKey = 'YOUR_API_KEY';

async function convertDocument(file) {
  const formData = new FormData();
  formData.append('file', file);
  formData.append('template', 'Convert to HTML5');
  formData.append('returnJson', 'true');

  const response = await fetch(apiURL + '/api/converter/convertdoc', {
    method: 'POST',
    headers: {
      'X-Api-Key': apiKey
    },
    body: formData
  });

  if (!response.ok) {
    throw new Error(`HTTP error ${response.status}: ${await response.text()}`);
  }

  const fileUrls = await response.json();
  console.log('Converted files:', fileUrls);
  return fileUrls;
}

convertDocument(document.querySelector('#fileInput').files[0])
  .catch(err => console.error(err.message));
                                

Requires the requests library (pip install requests).


import requests

api_url = 'https://api.docconverter.pro/api/converter/convertdoc'
api_key = 'YOUR_API_KEY'

headers = {
    'X-Api-Key': api_key
}

form_data = {
    'template': 'Convert to HTML5',
    'returnJson': 'true'
}

with open('mydocument.docx', 'rb') as document:
    files = {'file': ('mydocument.docx', document)}
    response = requests.post(api_url, headers=headers, data=form_data, files=files)

if response.ok:
    for file_url in response.json():
        print('Converted file:', file_url)
else:
    print(f'HTTP Error {response.status_code}: {response.text}')
                                

Uses the cURL extension with CURLFile for the multipart upload.


<?php

$apiUrl = 'https://api.docconverter.pro/api/converter/convertdoc';
$apiKey = 'YOUR_API_KEY';
$filePath = 'mydocument.docx';

$postFields = [
    'file' => new CURLFile($filePath),
    'template' => 'Convert to HTML5',
    'returnJson' => 'true',
];

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, $apiUrl);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'X-Api-Key: ' . $apiKey,
]);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields);

$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

if (curl_errno($ch)) {
    echo 'cURL Error: ' . curl_error($ch);
} elseif ($httpCode == 200) {
    foreach (json_decode($response, true) as $fileUrl) {
        echo 'Converted file: ' . $fileUrl . "\n";
    }
} else {
    echo 'HTTP Error: ' . $httpCode . "\nResponse: " . $response . "\n";
}

curl_close($ch);

?>
                                

Uses HttpClient and MultipartFormDataContent.


using System;
using System.IO;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;

public class DocumentConverter
{
    private static readonly HttpClient client = new HttpClient
    {
        BaseAddress = new Uri("https://api.docconverter.pro")
    };

    public static async Task ConvertDocumentAsync(string filePath)
    {
        using (var form = new MultipartFormDataContent())
        using (var fileStream = File.OpenRead(filePath))
        {
            var fileContent = new StreamContent(fileStream);
            fileContent.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
            form.Add(fileContent, "file", Path.GetFileName(filePath));
            form.Add(new StringContent("Convert to HTML5"), "template");
            form.Add(new StringContent("true"), "returnJson");

            using (var request = new HttpRequestMessage(HttpMethod.Post, "/api/converter/convertdoc"))
            {
                request.Headers.Add("X-Api-Key", "YOUR_API_KEY");
                request.Content = form;

                using (var response = await client.SendAsync(request))
                {
                    var body = await response.Content.ReadAsStringAsync();

                    if (!response.IsSuccessStatusCode)
                        throw new Exception($"HTTP error {(int)response.StatusCode}: {response.ReasonPhrase}");
                    else
                        Console.WriteLine("Converted files: " + body);
                }
            }
        }
    }
}
                                

Example JSON response (with returnJson=true):


[
    "https://api.docconverter.pro/convertedfiles/6f1c2f0e9b8a4d3c/mydocument.html",
    "https://api.docconverter.pro/convertedfiles/6f1c2f0e9b8a4d3c/images/logo.png"
]
                        

Java, Ruby and complete application samples that also demonstrate token authentication are available for download in the Test Page & Examples section.


Merge Documents API Call

POST https://api.docconverter.pro/api/merge/mergedocuments

This API call will merge input files (sent via POST as multipart/form-data) and will return URL/Raw file data or post back to a given URL the merged file.

⚠ View required authorization header details

Input Parameters:

  1. file1, file2, ... (Required) Send at least two files (named file1, file2, etc.) in a FormData (JavaScript) or as MultipartFormDataContent. See the sample page.
  2. outputformat - (Optional) Merged output format type: DOCX (default), PDF, RTF, TXT.
  3. outputfilename - (Optional) Output file name without extension.
  4. pdfcompliance - (Optional) PDF compliance (only if PDF output format is set): PDF17 (default), PDFA1A, PDFA1B.
  5. pdfimagestype - (Optional) PDF image type (only if PDF output format is set): AUTO (default), JPEG.
  6. pdfjpgquality - (Optional) PDF JPEG image quality (only if PDF output format and JPEG image type is set): 10~100 values, default is 90.
  7. returnData - (Optional) Option to return raw octet-stream data. Default is false, and it returns URL to the merged file on the Doc Converter Pro Web API server.
  8. backUrl - (Optional) If specified, API method will merge input files and will POST merged output file to that specified URL. See convert API for sample receiver code.

Send documents for merging

POST a multipart/form-data body holding at least two input documents in file1, file2, ... parts and your API key in the X-Api-Key header. The examples below also pass outputformat and outputfilename. Without returnData=true the response is the URL of the merged file on the Doc Converter Pro Web API server, as plain text.

Command line example that uploads chapter1.docx and chapter2.docx and merges them into one PDF.


curl -X POST "https://api.docconverter.pro/api/merge/mergedocuments" \
     -H "X-Api-Key: YOUR_API_KEY" \
     -F "file1=@chapter1.docx" \
     -F "file2=@chapter2.docx" \
     -F "outputformat=PDF" \
     -F "outputfilename=merged-document"
                                

Browser example using the native fetch API and two file inputs.


const apiURL = 'https://api.docconverter.pro';
const apiKey = 'YOUR_API_KEY';

async function mergeDocuments(file1, file2) {
  const formData = new FormData();
  formData.append('file1', file1);
  formData.append('file2', file2);
  formData.append('outputformat', 'PDF');
  formData.append('outputfilename', 'merged-document');

  const response = await fetch(apiURL + '/api/merge/mergedocuments', {
    method: 'POST',
    headers: {
      'X-Api-Key': apiKey
    },
    body: formData
  });

  if (!response.ok) {
    throw new Error(`HTTP error ${response.status}: ${await response.text()}`);
  }

  const mergedFileUrl = await response.text();
  console.log('Merged file:', mergedFileUrl);
  return mergedFileUrl;
}

mergeDocuments(
  document.querySelector('#fileInput1').files[0],
  document.querySelector('#fileInput2').files[0]
).catch(err => console.error(err.message));
                                

Requires the requests library (pip install requests).


import requests

api_url = 'https://api.docconverter.pro/api/merge/mergedocuments'
api_key = 'YOUR_API_KEY'

headers = {
    'X-Api-Key': api_key
}

form_data = {
    'outputformat': 'PDF',
    'outputfilename': 'merged-document'
}

with open('chapter1.docx', 'rb') as document1, open('chapter2.docx', 'rb') as document2:
    files = [
        ('file1', ('chapter1.docx', document1)),
        ('file2', ('chapter2.docx', document2))
    ]
    response = requests.post(api_url, headers=headers, data=form_data, files=files)

if response.ok:
    print('Merged file:', response.text)
else:
    print(f'HTTP Error {response.status_code}: {response.text}')
                                

Uses the cURL extension with CURLFile for the multipart upload.


<?php

$apiUrl = 'https://api.docconverter.pro/api/merge/mergedocuments';
$apiKey = 'YOUR_API_KEY';

$postFields = [
    'file1' => new CURLFile('chapter1.docx'),
    'file2' => new CURLFile('chapter2.docx'),
    'outputformat' => 'PDF',
    'outputfilename' => 'merged-document',
];

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, $apiUrl);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'X-Api-Key: ' . $apiKey,
]);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields);

$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

if (curl_errno($ch)) {
    echo 'cURL Error: ' . curl_error($ch);
} elseif ($httpCode == 200) {
    echo 'Merged file: ' . $response . "\n";
} else {
    echo 'HTTP Error: ' . $httpCode . "\nResponse: " . $response . "\n";
}

curl_close($ch);

?>
                                

Uses HttpClient and MultipartFormDataContent.


using System;
using System.IO;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;

public class DocumentMerger
{
    private static readonly HttpClient client = new HttpClient
    {
        BaseAddress = new Uri("https://api.docconverter.pro")
    };

    public static async Task MergeDocumentsAsync(string firstFilePath, string secondFilePath)
    {
        using (var form = new MultipartFormDataContent())
        using (var firstStream = File.OpenRead(firstFilePath))
        using (var secondStream = File.OpenRead(secondFilePath))
        {
            var firstContent = new StreamContent(firstStream);
            firstContent.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
            form.Add(firstContent, "file1", Path.GetFileName(firstFilePath));

            var secondContent = new StreamContent(secondStream);
            secondContent.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
            form.Add(secondContent, "file2", Path.GetFileName(secondFilePath));

            form.Add(new StringContent("PDF"), "outputformat");
            form.Add(new StringContent("merged-document"), "outputfilename");

            using (var request = new HttpRequestMessage(HttpMethod.Post, "/api/merge/mergedocuments"))
            {
                request.Headers.Add("X-Api-Key", "YOUR_API_KEY");
                request.Content = form;

                using (var response = await client.SendAsync(request))
                {
                    var body = await response.Content.ReadAsStringAsync();

                    if (!response.IsSuccessStatusCode)
                        throw new Exception($"HTTP error {(int)response.StatusCode}: {response.ReasonPhrase}");
                    else
                        Console.WriteLine("Merged file: " + body);
                }
            }
        }
    }
}
                                

Example response (URL of the merged file):


https://api.docconverter.pro/convertedfiles/6f1c2f0e9b8a4d3c/merged-document.pdf
                        

Java, Ruby and complete application samples that also demonstrate token authentication are available for download in the Test Page & Examples section.


Get Conversions Info API Call

GET https://api.docconverter.pro/api/convert/conversionsinfo

This API call returns JSON data with two values: Conversions (currently used conversion count) and MaxConversions (maximum conversions count). MaxConversions minus Conversions will give the number of conversions left.

⚠ View required authorization header details

Example JSON Response:

{
    "Conversions": 50,
    "MaxConversions": 1000
}

API Throttling

DCP Web API throttles requests per API call. Every API key has its own request counter, and the number of requests it may make is set by the account type of the user that key belongs to. Callers that do not send an API key are limited at the Standard rate.

Account type Per second Per minute Per hour Per day Per week
Trial and Starter 1 30 1,000 10,000 50,000
Business 2 60 2,000 20,000 100,000
Enterprise 4 120 4,000 40,000 200,000

All of the limits for your account type apply at the same time, so the first one you reach ends the request with an API quota exceeded error. The per second value is a short burst allowance — a sustained conversion rate is capped by the per hour figure, which for a Standard account works out at roughly one document every 3.6 seconds.

Throttling is separate from your plan's conversion allowance, which caps the total number of conversions (for example 100, 2500 or 10000) no matter how slowly you send them. Use the Conversions Info call to see how many you have left.

The best practice is to wait until the conversion of a given document is done then send another API conversion request. When converting lots of small documents, we recommend measuring how many documents you convert per second/minute etc., otherwise you may receive an API quota exceeded error.


API Conversion Bad Request Error Note

To prevent exceeding the server's CPU usage limit, our Web API will throw an error if the input document has already been converted with the same template and took more than 30 seconds to convert within the last hour, and if the conversion failed due to an error in the input document.


Check out the API test web page (JavaScript sample)

We have created a sample page that demonstrates how the API conversion works in JavaScript.

Doc Converter Pro Web API Test Page...

How to use the sample page:

  1. Authenticate using one of the two tabs on the page:
    • API Key (default) — paste an API key you created on the API Keys page and click "Use API Key". This is the quickest option as there is no token to fetch.
    • Bearer Token — enter your login credentials (the same login as your Doc Converter Pro Online account) and click the "Get Bearer Token" button.
    If you don't have a Doc Converter Pro Online account yet, please Register for free.
  2. Select the input document file that you want to convert.
  3. Optionally enter a template name.
  4. Optionally choose whether to return a zip file with all output conversion files or just get the output file back.
  5. Optionally choose whether to return a JSON list of output file URLs, raw data, or URL string to that data file located on our server. Using the raw data option with the return HTML option is useful if you want to use only converted HTML right away.
  6. Also, you can enable sending the file back to a given URL via POST; please specify a URL that will process a POST request.
  7. Click the "Start Converting" button and wait for a response.

Example JavaScript code

Please check out the JavaScript example code or view the HTML and PostJsCode.js file source code of the Web API Test Page to see how you can use this API method in JavaScript.

Example JavaScript/jQuery sample code (old version)

Please check out the jQuery example code that demonstrates how to get API token and convert or merge files.

Example Python code

Please check out the example Python code that demonstrates how to get API token and convert an uploaded file to HTML5. Extract the zip and edit the docconverter_pro_api_sample.py file. Enter your Doc Converter Pro Online email and password at lines 223 and 224.

Example PHP code

Please check out PHP/HTML example code that demonstrates how to get API token and convert an uploaded file. Extract the zip to a PHP web server. Edit the convert.php file and enter your Doc Converter Pro Online email and password on line 28. Set write permissions on the upload/ folder if needed. Go to index.php in a browser, then select a document to convert and click the "Start Converting" button.

Example .NET Winforms C# app

Please check out the .NET Winforms example C# app that converts a document. Based on that sample app C# code, you can write code for ASP.NET MVC web applications as well.

Example Java code

Please check out the example Java code that demonstrates how to get API token and convert an uploaded file. Extract the zip and edit the WordCleanerWebApi.java file. Enter your Doc Converter Pro Online email and password in the GetAccessToken() method. Enter your doc file name and path and run.

Example Ruby code

Please check out the example Ruby code that demonstrates how to get API token and convert a sample doc file. Extract the zip and edit the dcp_web_api_sample.rb file. Enter your Doc Converter Pro Online email and password on line 6 that gets the API token. Make sure to install multipart-post gem: gem install multipart-post and then run this sample with ruby dcp_web_api_sample.rb.

Using DocConverter.Pro API with Make.com (Integromat)

Make.com allows you to connect DocConverter.Pro to hundreds of other apps and services to automate your document conversion workflows. Here’s how you can set up a typical two-step scenario: 1) Obtain a Bearer Token, and 2) Convert a document.

Prerequisites:

  • A DocConverter.Pro account with API access credentials (Email & Password).
  • A Make.com account.

Scenario Overview:

A common scenario involves these Make.com modules:

  1. Trigger: Any Make.com trigger (e.g., "Watch new files in Google Drive," "New email attachment," "HTTP Webhook").
  2. HTTP Module (Get Token): Makes a request to https://api.docconverter.pro/token to get an access token.
  3. HTTP Module (Convert Document): Uses the obtained token to make a request to https://api.docconverter.pro/api/converter/convertdoc with the file to convert.
  4. Action: Subsequent modules to handle the converted file (e.g., "Upload file to Dropbox," "Send an email with attachment").

Step 1: Obtaining the Bearer Token in Make.com

Add an "HTTP" module with the "Make a request" action.

HTTP Module Configuration: Get Token
  • URL: https://api.docconverter.pro/token
  • Method: POST
  • Headers:
    • Name: Content-Type
    • Value: application/x-www-form-urlencoded
  • Body type: application/x-www-form-urlencoded
  • Fields:
    • Item 1:
      • Key: grant_type
      • Value: password
    • Item 2:
      • Key: username
      • Value: YOUR_DOCCONVERTER_PRO_EMAIL (Replace with your actual email)
    • Item 3:
      • Key: password
      • Value: YOUR_DOCCONVERTER_PRO_PASSWORD (Replace with your actual password. Consider using Make.com connections or variables for sensitive data.)
  • Parse response: Yes (Make.com will automatically parse the JSON).

Output: This module will output JSON containing the access_token. For example: {"access_token": "your_bearer_token_here", "token_type": "bearer", ...}. You'll map data.access_token from this module in the next step.


Step 2: Converting the Document in Make.com

Add another "HTTP" module with the "Make a request" action after the token module.

HTTP Module Configuration: Convert Document
  • URL: https://api.docconverter.pro/api/converter/convertdoc
  • Method: POST
  • Headers:
    • Name: Authorization
    • Value: Bearer {{MAP_ACCESS_TOKEN_FROM_PREVIOUS_STEP}}
      (Map the access_token field from the output of the "Get Token" HTTP module. It will look something like Bearer {{1.data.access_token}} where '1' is the module ID of your token request module.)
  • Body type: Multipart/form-data
  • Fields:
    • Item 1 (File):
      • Key: file
      • Value:
        • Source file: Map from a previous module (e.g., the output of a "Google Drive - Download a file" module, or an "HTTP - Get a file" module). You'll map the File data here, not just a URL.
        • File name: (Optional but recommended) Map the original file name.
    • Item 2 (Optional - Template Name):
      • Key: template
      • Value: Convert to HTML5 (Or your desired template name)
    • Item 3 (Optional - Return JSON):
      • Key: returnJson
      • Value: true (If you want a JSON response with file URLs)
  • Parse response: Yes (if you expect JSON, e.g., with returnJson=true). If you expect raw file data (returnData=true and not returnJson=true), you might not parse it as JSON, and subsequent modules will handle the raw data.

Output: Depending on your parameters (returnJson, returnHtml, returnData), this module will output:

  • A JSON structure with URLs to the converted files.
  • The raw data of the converted file (if returnData=true and not returnJson=true).
  • A URL to the converted file (if no specific return type is heavily favored).
You can then use this output in subsequent Make.com modules.


Example Make.com Scenario Flow:

[Trigger: New File in Google Drive] -> [HTTP: Get Bearer Token] -> [HTTP: Convert Document (mapping file from GDrive & token)] -> [Action: Upload Converted File to Dropbox]

Important Considerations:

  • Error Handling: Implement error handling routes in your Make.com scenario to manage API errors (e.g., invalid token, conversion failure). The HTTP modules in Make.com provide ways to handle different status codes.
  • Token Expiration & Caching: Bearer tokens usually have an expiration time. For high-volume scenarios, you might consider caching the token in Make.com's Data Store and only requesting a new one when it's about to expire or has expired. However, for simpler or less frequent tasks, requesting a token for each run is often sufficient.
  • File Handling: Ensure you are mapping the actual file content/data to the file parameter in the "Convert Document" step, not just a URL (unless your trigger itself provides raw file data). Modules like "HTTP - Get a file" or cloud storage "Download a file" modules can fetch the file data.
  • API Rate Limits: Be mindful of any API rate limits imposed by DocConverter.Pro.

Using DocConverter.Pro API with n8n.io

This guide will walk you through connecting to the Doc Converter Pro API using n8n.io, a popular workflow automation tool. By the end of this tutorial, you will be able to build an n8n workflow that can automatically authenticate with our service and convert your documents.

Prerequisites:
  • An active Doc Converter Pro account. If you don't have one, please register here. [1]
  • A running n8n.io instance (either cloud or self-hosted).

Workflow Overview

A typical n8n workflow for document conversion will consist of at least two main steps (nodes):

  1. Get Bearer Token: An HTTP Request node to authenticate with your Doc Converter Pro credentials and receive an access token. [1]
  2. Convert Document: A second HTTP Request node that uses the access token to authorize and send a file for conversion. [1]

You can start your workflow with any n8n trigger, such as "On a schedule," "Webhook," or a trigger that watches for new files in a cloud storage service like Google Drive or Dropbox.


Step 1: Authenticate and Get Access Token

The first step is to get an OAuth 2.0 bearer token from the /token endpoint. [1] We will use an n8n HTTP Request node for this.

HTTP Request Node Configuration (Get Token)

Add an "HTTP Request" node to your workflow and configure it as follows:

Parameter Setting
Method POST
URL https://api.docconverter.pro/token
Authentication None
Send Body On
Body Content Type application/x-www-form-urlencoded
Body Add three parameters:
  • grant_type: password
  • username: your-email@example.com
  • password: your_doc_converter_pro_password

When you execute this node, it will return a JSON object containing your access_token, which is valid for 14 days. [1]

Copyable Node JSON

You can copy the JSON below and paste it directly into your n8n canvas:


{
  "parameters": {
    "method": "POST",
    "url": "https://api.docconverter.pro/token",
    "sendBody": true,
    "body": {
      "grant_type": "password",
      "username": "your-email@example.com",
      "password": "your_doc_converter_pro_password"
    },
    "options": {}
  },
  "name": "Get Bearer Token",
  "type": "n8n-nodes-base.httpRequest",
  "typeVersion": 1,
  "position": [
    620,
    300
  ],
  "credentials": {}
}
    
Security Tip: For better security, consider storing your password in n8n's built-in credential manager and referencing it using an expression.

Step 2: Convert a Document

Now that you have a node that can fetch an access token, add a second HTTP Request node to handle the file conversion. This node will take a file from a previous step (like a trigger) and use the token from the "Get Bearer Token" node to authorize the request.

HTTP Request Node Configuration (Convert Document)

Parameter Setting
Method POST
URL https://api.docconverter.pro/api/converter/convertdoc
Authentication Generic Credential
Generic Credential Type Header Auth
Name (Header) Authorization
Value (Header) (Use an expression to reference the token from the previous node)
Bearer {{$node["Get Bearer Token"].json["access_token"]}}
Send Body On
Body Content Type multipart/form-data
Body Add one parameter:
  • Name: file
  • Value: (Use an expression to reference the incoming file's binary data. This depends on your trigger node, but often looks like {{$binary.data}})
  • Is File: On
Options (Optional) You can add more parameters to the body to control the output. For example: [1]
  • template: Convert to HTML5
  • returnJson: true

Copyable Node JSON

You can copy and paste the JSON for this node. Make sure the input of this node is connected to a node that provides a binary file (e.g., a "Read Binary File" node, or a Google Drive/Dropbox trigger).


{
  "parameters": {
    "method": "POST",
    "url": "https://api.docconverter.pro/api/converter/convertdoc",
    "sendBody": true,
    "bodyContentType": "multipart/form-data",
    "body": {
      "file": "={{$binary.data}}"
    },
    "options": {}
  },
  "name": "Convert Document",
  "type": "n8n-nodes-base.httpRequest",
  "typeVersion": 1,
  "position": [
    840,
    300
  ],
  "credentials": {
    "httpHeaderAuth": {
      "id": "1",
      "name": "DocConverterPro API Key",
      "data": {
        "name": "Authorization",
        "value": "=Bearer {{$node[\"Get Bearer Token\"].json[\"access_token\"]}}"
      }
    }
  }
}
    
Handling Incoming Files: In n8n, files are passed between nodes as binary data. When configuring the file parameter, ensure you are referencing the binary property of your incoming item. For many triggers, this is simply {{$binary.data}}. You may need to use a "Read Binary File" node if your trigger only provides a file path.

With these two nodes configured and connected, you can automate your document conversion workflows with n8n.io and the Doc Converter Pro API.


Using DocConverter.Pro API with Zapier

This guide will walk you through connecting to the Doc Converter Pro API using Zapier, a popular no-code automation platform. You do not need any coding skills — you will use Zapier's built-in Webhooks by Zapier action to call our API.

Prerequisites:
  • An active Doc Converter Pro account. If you don't have one, please register here.
  • A Doc Converter Pro API key (created on the API Keys page).
  • A Zapier account with access to the "Webhooks by Zapier" app (available on all plans).

Workflow Overview

The simplest Zapier workflow uses our API Key authentication, so it needs only a single action — no separate token step:

  1. Trigger: Any Zapier trigger that provides a file (e.g. "New File in Google Drive", "New Attachment in Gmail", "New Form Entry").
  2. Action — Webhooks by Zapier (Custom Request): Send the file to the Doc Converter Pro API together with your API key.

Because the API key never expires (unless you set an expiry date), you can reuse the same key in every Zap without fetching a new token.


Step 1: Set Up Your Trigger

Create a new Zap and choose a trigger that produces a file. For example, "Google Drive → New File in Folder". Continue to the action step once the trigger test data includes the file you want to convert.


Step 2: Add the "Webhooks by Zapier" Action

Add an action and search for Webhooks by Zapier, then choose the event Custom Request. Configure it as follows:

Parameter Setting
Action / Event Custom Request
Method POST
URL https://api.docconverter.pro/api/converter/convertdoc
Payload Type form-data
Data template = Convert to HTML5
file = (map the file from the trigger step)
returnJson = true
Headers X-Api-Key = your API key
Mapping the file: In the file field, choose the file from your trigger step (for example the file's download URL or raw data, depending on the trigger). Zapier sends it as a multipart/form-data file part, which is exactly what our convertdoc endpoint expects.

Step 3: Test and Use the Response

Run a test of the action. When returnJson is set to true, the API returns a JSON object containing the converted output file URL(s). You can then add further Zapier actions to store, email, or upload the converted file.

Handling the API response: Zapier automatically parses JSON responses, so you can map fields from the API response (such as the output file URL) into subsequent actions.

Alternative: Bearer Token Authentication in Zapier

If you prefer (or must) use the bearer token instead of an API key, add an extra "Webhooks by Zapier" action before the conversion step:

  1. Get Bearer Token: a Custom Request with POST to https://api.docconverter.pro/token, Payload Type form, sending grant_type = password, username = your email, password = your password. Map access_token from the response into the next step.
  2. Convert Document: the same configuration as Step 2 above, but instead of the X-Api-Key header add a header Authorization = Bearer <access_token>.

We still recommend the API Key method because it removes the need to fetch and refresh a token on every Zap run.

With the Webhooks by Zapier action configured, you can automate document conversion from thousands of apps using the Doc Converter Pro API. For full parameter details, see the Convert Document API section.


Note: The Web API uses the same template files that you have on your Doc Converter Pro Online account; therefore, you can use the Doc Converter Pro Online version to prepare your template and perform any testing.


Doc Converter Pro API – Frequently Asked Questions

What is the Doc Converter Pro REST API?

The Doc Converter Pro REST API is a cloud-based document conversion service that lets developers programmatically convert and merge files between formats including Word DOCX, DOC, PDF, RTF, ODT, TXT, JPG/PNG, and HTML — directly from within their own applications.

What file formats does the Doc Converter Pro API support?

The API supports conversion between DOCX, DOC (Word), PDF, RTF, ODT, TXT, JPG, PNG, and HTML. You can convert Word documents to PDF, HTML to DOCX, PDFs to HTML5, and many other combinations depending on your chosen conversion template.

How do I authenticate with the Doc Converter Pro API?

Authentication uses OAuth 2.0 bearer tokens. Send a POST request to https://api.docconverter.pro/token with your username, password, and grant_type=password as application/x-www-form-urlencoded. The returned access token is valid for 14 days and must be included in subsequent API calls as an Authorization: Bearer YOUR_TOKEN header. We recommend caching the token and refreshing it just before expiry.

How do I convert a document using the API?

Send a POST request to https://api.docconverter.pro/api/converter/convertdoc with your file attached as multipart/form-data. Optionally specify a template name matching one in your Doc Converter Pro account, and choose how the result is returned: as a URL, zip file, raw data, single output file, a JSON list of URLs, or posted back to your own server via backUrl.

Can the Doc Converter Pro API merge multiple documents into one?

Yes. Send a POST request to https://api.docconverter.pro/api/merge/mergedocuments with two or more files (file1, file2, etc.) as multipart/form-data. The merged output format can be DOCX (default), PDF, RTF, or TXT. PDF output supports compliance levels including PDF/A-1A and PDF/A-1B.

What programming languages does the Doc Converter Pro API support?

Official code samples are provided for JavaScript, Python, PHP, C# (.NET / ASP.NET MVC), Java, and Ruby. The API is a standard REST API so it can be called from any language that supports HTTP requests. It also integrates with no-code automation platforms like Make.com (Integromat) and n8n.io.

What are the API rate limits for Doc Converter Pro?

The API enforces throttling per API key, and the rate is set by your account type: a Standard account (Trial, Starter, Personal) allows up to 1 document per second, 30 per minute, 1,000 per hour, 10,000 per day and 50,000 per week. Business accounts get double those figures and Enterprise accounts four times. Best practice is to wait for each conversion to complete before sending the next request. For high-volume workloads, dedicated API servers without throttling are available.

How can I check how many API conversions I have left?

Make a GET request to https://api.docconverter.pro/api/convert/conversionsinfo with your bearer token. The JSON response returns Conversions (used) and MaxConversions (plan limit). Subtracting the two gives your remaining conversion quota.

Is there a free test plan for the Doc Converter Pro API?

Yes. You can register for a free Doc Converter Pro account and test the API at no cost. For production use a paid plan is required. Pricing details are available at docconverter.pro/Home/Pricing.

Why am I getting a Bad Request error from the Doc Converter Pro API?

To prevent excessive server load, the API returns an error if a document previously caused a conversion failure, or if the same document was converted with the same template within the last 1 hour. Verify your input document format and conversion template to resolve the issue.


Need More Power for Document Conversion?

We are able to offer dedicated API servers with custom CPU number (2/4/8/12) and memory (4/8/16/24GB) configurations to handle high-volume, concurrent document conversions—no throttling.

Choose your preferred server location:
🇺🇸 USA · 🇬🇧 London · 🇩🇪 Frankfurt · 🇳🇱 Amsterdam · 🇦🇺 Melbourne/Sydney · 🇮🇳 India · 🇯🇵 Japan

Servers can be scaled up anytime as your needs grow.

Custom pricing based on your specific server needs. Contact us to discuss your ideal setup.



Questions? Contact us anytime...