Doc Converter Pro - REST API Documentation for Developers

Programmatically convert DOCX, DOC, PDF, RTF, ODT, TXT, and HTML files.


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 Call

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 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.
  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.

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.

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 IP.

You can convert a maximum of 2 documents per second, 40 documents per minute, 1000 per hour and 20000 per day. 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

In order to prevent exceeded server CPU usage, DCP Web API will throw an error if the given input document caused a conversion error or it was already converted with the same template and it took more than 30 seconds to convert it within the last 1 hour.


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. 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.


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.


Questions? Contact us anytime...