Getting Started

Our API allows you to convert DOCX files to PDF programmatically. Subscribe to get your API key. You can find your API key in your account settings.

  • Base URL: https://office-to-pdf.com/api/v3/
  • Authentication: API Key via header { Authorization: Bearer {your_bearer_token} }

Endpoints

POST /convert/pdf

Convert a Office formatted file to PDF.

Request Body: Multipart form with "file" (.docx file)

Response: PDF file binary or JSON response with a short lived download link

curl -X POST https://office-to-pdf.com/api/v3/convert/pdf \-H "Authorization: Bearer {your_bearer_token}"-F "file=@path/to/yourfile.docx"

POST /convert/batch

Convert a zipped batch of office formatted files to PDF.

Coming soon...

Response

Standard response:

{
    "converted":"base64 encoded file contents"
}

Error Handling

Common errors and status codes:

  • 400: Invalid file format
  • 401: Unauthorized (invalid API key)
  • 429: Rate limit exceeded
  • 500: Internal server error

Code Examples

React (JSX)

import React, { useState } from 'react';

function DocxToPdfConverter() {
  const [file, setFile] = useState(null);
  const [returnType, setReturnType] = useState('base64file');
  const [error, setError] = useState(null);
  const [loading, setLoading] = useState(false);
  const [base64Result, setBase64Result] = useState(null);

  const apiToken = 'your_api_token_here'; // Replace with your actual API token

  const handleFileChange = (event) => {
    setFile(event.target.files[0]);
    setError(null);
  };

  const handleReturnTypeChange = (event) => {
    setReturnType(event.target.value);
  };

  const handleSubmit = async (event) => {
    event.preventDefault();
    if (!file) {
      setError('Please select a file.');
      return;
    }

    setLoading(true);
    setBase64Result(null);
    const formData = new FormData();
    formData.append('file', file);
    formData.append('return_type', returnType);

    try {
      const response = await fetch('https://office-to-pdf.com/api/v3/convert/pdf', {
        method: 'POST',
        headers: {
          Authorization: `Bearer ${apiToken}`,
        },
        body: formData,
      });

      if (!response.ok) {
        throw new Error('Conversion failed.');
      }

      if (returnType === 'base64file') {
        const blob = await response.blob();
        const url = window.URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = 'converted.pdf';
        document.body.appendChild(a);
        a.click();
        a.remove();
        window.URL.revokeObjectURL(url);
      } else if (returnType === 'temporary-link') {
        const data = await response.json();
        setBase64Result(data.pdf); // Display or use the base64 string as needed
      }
    } catch (err) {
      setError(err.message);
    } finally {
      setLoading(false);
    }
  };
}

export default DocxToPdfConverter;
        

Javascript

const fs = require('fs');
const axios = require('axios');
const FormData = require('form-data');
const path = require('path');

// 'base64file' is the default and not a required field, 'temporary-link' option coming soon...
async function convertDocxToPdf(inputFilePath, returnType = 'base64file') {
  const apiToken = 'your_api_token_here'; // Replace with your actual API token

  const form = new FormData();
  form.append('file', fs.createReadStream(inputFilePath));
  form.append('return_type', returnType);

  try {
    const response = await axios.post('https://office-to-pdf.com/api/v3/convert/pdf', form, {
      headers: {
        ...form.getHeaders(),
        Authorization: `Bearer ${apiToken}`,
      },
      responseType: returnType === 'base64file' ? 'stream' : 'json',
    });

    if (returnType === 'base64file') {
      const outputFilePath = path.join(path.dirname(inputFilePath), 'converted.pdf');
      response.data.pipe(fs.createWriteStream(outputFilePath));
      console.log(`PDF saved to ${outputFilePath}`);
    } else if (returnType === 'temporary-link') {
      console.log('coming soon');
    }
  } catch (error) {
    console.error('Error during conversion:', error.message);
  }
}

// Usage: node this-script.js /path/to/your.docx [return_type]
const args = process.argv.slice(2);
if (args.length < 1) {
  console.log('Usage: node convert.js input.docx [return_type]');
  process.exit(1);
}
convertDocxToPdf(args[0], args[1]);
        

Python

import requests

url = "https://office-to-pdf.com/api/v3/convert/pdf"
headers = {"Authorization": "Bearer your_api_key"}
files = {"file": open("yourfile.docx", "rb")}
response = requests.post(url, headers=headers, files=files)
with open("output.pdf", "wb") as f:
    f.write(response.content)
        

PHP

use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;

$inputFilePath = 'path/to/yourfile.docx'; // Replace with your file path
$returnType = 'base64file'; // 'base64file' is the default and not a required field, 'temporary-link' option coming soon...
$outputFilePath = 'converted.pdf';
$apiToken = 'your_api_token_here'; // Replace with your actual API token

$client = new Client();

try {
   $response = $client->post('https://office-to-pdf.com/api/v3/convert/pdf', [
       'headers' => [
           'Authorization' => 'Bearer ' . $apiToken,
       ],
       'multipart' => [
           [
               'name' => 'file',
               'contents' => fopen($inputFilePath, 'r'),
               'filename' => basename($inputFilePath),
           ],
           [
               'name' => 'return_type',
               'contents' => $returnType,
           ],
       ],
   ]);

   $httpCode = $response->getStatusCode();

   if ($httpCode === 200) {
       $body = $response->getBody()->getContents();
       if ($returnType === 'base64file') {
           file_put_contents($outputFilePath, base64_decode($body));
           echo "PDF saved to $outputFilePath" . PHP_EOL;
       } elseif ($returnType === 'temporary-link') {
           $data = json_decode($body, true);
           echo 'coming soon';
       }
   } else {
       echo "Conversion failed with HTTP code $httpCode" . PHP_EOL;
   }
} catch (RequestException $e) {
   echo 'Error: ' . $e->getMessage() . PHP_EOL;
}