Programmatically convert DOCX, DOC, PDF, RTF, ODT, TXT, and HTML files.
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.
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 emailpassword
- set your DocConverterPro passwordgrant_type
- set to 'password'
valueAuthorization
header as Bearer YOUR_ACCESS_TOKEN
for subsequent API calls.
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();
}
}
}
To successfully use our API endpoint methods, you must include an Authorization
header in your HTTPS request.
The value of this header must be prefixed with Bearer
(note the space after "Bearer") followed by the access token obtained from https://api.docconverter.pro/token
API call.
Format: Authorization: Bearer YOUR_ACCESS_TOKEN
Example: Authorization: Bearer eyJhbGciOiJIUzI1NiIsI...exampletoken...0987abc
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:
file
- (Required) Send a file in a FormData (JavaScript) or as MultipartFormDataContent. Please see the sample page or other samples for implementation details.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.
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
.
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
.
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.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.
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.
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:
file1
, file2
, ... (Required) Send at least two files (named file1
, file2
, etc.) in a FormData (JavaScript) or as MultipartFormDataContent. See the sample page.outputformat
- (Optional) Merged output format type: DOCX
(default), PDF
, RTF
, TXT
.outputfilename
- (Optional) Output file name without extension.pdfcompliance
- (Optional) PDF compliance (only if PDF
output format is set): PDF17
(default), PDFA1A
, PDFA1B
.pdfimagestype
- (Optional) PDF image type (only if PDF
output format is set): AUTO
(default), JPEG
.pdfjpgquality
- (Optional) PDF JPEG image quality (only if PDF
output format and JPEG
image type is set): 10
~100
values, default is 90
.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.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.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
}
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.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.
We have created a sample page that demonstrates how the API conversion works in JavaScript.
How to use the sample page:
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.
Please check out the jQuery example code that demonstrates how to get API token and convert or merge files.
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.
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.
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.
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.
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
.
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.
A common scenario involves these Make.com modules:
https://api.docconverter.pro/token
to get an access token.https://api.docconverter.pro/api/converter/convertdoc
with the file to convert.Add an "HTTP" module with the "Make a request" action.
https://api.docconverter.pro/token
POST
Content-Type
application/x-www-form-urlencoded
application/x-www-form-urlencoded
grant_type
password
username
YOUR_DOCCONVERTER_PRO_EMAIL
(Replace with your actual email)password
YOUR_DOCCONVERTER_PRO_PASSWORD
(Replace with your actual password. Consider using Make.com connections or variables for sensitive data.)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.
Add another "HTTP" module with the "Make a request" action after the token module.
https://api.docconverter.pro/api/converter/convertdoc
POST
Authorization
Bearer {{MAP_ACCESS_TOKEN_FROM_PREVIOUS_STEP}}
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.)
Multipart/form-data
file
template
Convert to HTML5
(Or your desired template name)returnJson
true
(If you want a JSON response with file URLs)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:
returnData=true
and not returnJson=true
).[Trigger: New File in Google Drive] -> [HTTP: Get Bearer Token] -> [HTTP: Convert Document (mapping file from GDrive & token)] -> [Action: Upload Converted File to Dropbox]
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.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.
A typical n8n workflow for document conversion will consist of at least two main steps (nodes):
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.
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.
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:
|
When you execute this node, it will return a JSON object containing your access_token
, which is valid for 14 days. [1]
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": {}
}
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.
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:
|
Options (Optional) |
You can add more parameters to the body to control the output. For example: [1]
|
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\"]}}"
}
}
}
}
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.