HomeDocsAPI Reference › Code Examples

Code Examples

Complete working examples for integrating the PDF Hub API in your applications.

Overview

The examples below demonstrate how to convert a Word document to PDF using the POST /api/pdf/word-to-pdf endpoint. Each example covers the full workflow:

  1. Setting up authentication headers (X-Api-Key and X-Api-Secret)
  2. Uploading a file using multipart/form-data
  3. Handling the HTTP response and checking for errors
  4. Saving the output file to disk
Tip
These examples use the Word-to-PDF endpoint, but the same pattern applies to all API endpoints. Simply change the URL and parameters to match the endpoint you want to use.

curl

The simplest way to test the API from the command line. This example converts a Word document and saves the resulting PDF to a file.

#!/bin/bash

# Configuration
API_KEY="pk_live_abc123def456"
API_SECRET="sk_live_789ghi012jkl"
API_URL="https://pdf.mapsoft.com/api/pdf/word-to-pdf"
INPUT_FILE="report.docx"
OUTPUT_FILE="report.pdf"

# Make the API request
HTTP_CODE=$(curl -s -o "$OUTPUT_FILE" -w "%{http_code}" \
  -X POST "$API_URL" \
  -H "X-Api-Key: $API_KEY" \
  -H "X-Api-Secret: $API_SECRET" \
  -F "file=@$INPUT_FILE" \
  -F "outputFileName=$OUTPUT_FILE")

# Check the response
if [ "$HTTP_CODE" -eq 200 ]; then
  echo "Success! Converted file saved to $OUTPUT_FILE"
  echo "File size: $(wc -c < "$OUTPUT_FILE") bytes"
else
  echo "Error: HTTP $HTTP_CODE"
  # The output file contains the error JSON, display it
  cat "$OUTPUT_FILE"
  rm -f "$OUTPUT_FILE"
fi

Python

Uses the requests library for a clean, readable implementation. Install with pip install requests.

import requests
import sys
import os

# Configuration
API_KEY = "pk_live_abc123def456"
API_SECRET = "sk_live_789ghi012jkl"
API_URL = "https://pdf.mapsoft.com/api/pdf/word-to-pdf"

def convert_word_to_pdf(input_path, output_path=None):
    """Convert a Word document to PDF using the Mapsoft PDF Hub API."""

    if output_path is None:
        base_name = os.path.splitext(input_path)[0]
        output_path = f"{base_name}.pdf"

    # Set up authentication headers
    headers = {
        "X-Api-Key": API_KEY,
        "X-Api-Secret": API_SECRET
    }

    # Open the file and send the request
    with open(input_path, "rb") as f:
        files = {
            "file": (os.path.basename(input_path), f, "application/octet-stream")
        }
        data = {
            "outputFileName": os.path.basename(output_path)
        }

        print(f"Converting {input_path}...")
        response = requests.post(API_URL, headers=headers, files=files, data=data)

    # Handle the response
    if response.status_code == 200:
        with open(output_path, "wb") as out:
            out.write(response.content)
        file_size = os.path.getsize(output_path)
        print(f"Success! Saved to {output_path} ({file_size:,} bytes)")
        return output_path
    else:
        error = response.json()
        print(f"Error {response.status_code}: {error.get('message', 'Unknown error')}")
        return None


if __name__ == "__main__":
    if len(sys.argv) < 2:
        print("Usage: python convert.py input.docx [output.pdf]")
        sys.exit(1)

    input_file = sys.argv[1]
    output_file = sys.argv[2] if len(sys.argv) > 2 else None
    convert_word_to_pdf(input_file, output_file)

JavaScript / Node.js

Uses the built-in fetch API (Node.js 18+) with the form-data package for file uploads. Install with npm install form-data.

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

// Configuration
const API_KEY = "pk_live_abc123def456";
const API_SECRET = "sk_live_789ghi012jkl";
const API_URL = "https://pdf.mapsoft.com/api/pdf/word-to-pdf";

async function convertWordToPdf(inputPath, outputPath) {
    // Default output path: same name with .pdf extension
    if (!outputPath) {
        const baseName = path.basename(inputPath, path.extname(inputPath));
        outputPath = path.join(path.dirname(inputPath), `${baseName}.pdf`);
    }

    // Build the multipart form data
    const form = new FormData();
    form.append("file", fs.createReadStream(inputPath));
    form.append("outputFileName", path.basename(outputPath));

    console.log(`Converting ${inputPath}...`);

    // Send the request with authentication headers
    const response = await fetch(API_URL, {
        method: "POST",
        headers: {
            "X-Api-Key": API_KEY,
            "X-Api-Secret": API_SECRET,
            ...form.getHeaders()
        },
        body: form
    });

    // Handle the response
    if (response.ok) {
        const buffer = Buffer.from(await response.arrayBuffer());
        fs.writeFileSync(outputPath, buffer);
        console.log(`Success! Saved to ${outputPath} (${buffer.length.toLocaleString()} bytes)`);
        return outputPath;
    } else {
        const error = await response.json();
        console.error(`Error ${response.status}: ${error.message || "Unknown error"}`);
        return null;
    }
}

// Run from command line: node convert.js input.docx [output.pdf]
const args = process.argv.slice(2);
if (args.length === 0) {
    console.log("Usage: node convert.js input.docx [output.pdf]");
    process.exit(1);
}

convertWordToPdf(args[0], args[1])
    .catch(err => {
        console.error("Unexpected error:", err.message);
        process.exit(1);
    });

PHP

Uses PHP's built-in curl extension. No additional libraries are required.

<?php

// Configuration
$apiKey    = "pk_live_abc123def456";
$apiSecret = "sk_live_789ghi012jkl";
$apiUrl    = "https://pdf.mapsoft.com/api/pdf/word-to-pdf";

function convertWordToPdf(string $inputPath, ?string $outputPath = null): ?string
{
    global $apiKey, $apiSecret, $apiUrl;

    // Default output path: same name with .pdf extension
    if ($outputPath === null) {
        $outputPath = pathinfo($inputPath, PATHINFO_FILENAME) . ".pdf";
    }

    // Verify the input file exists
    if (!file_exists($inputPath)) {
        echo "Error: File not found: {$inputPath}\n";
        return null;
    }

    // Build the multipart form data
    $postFields = [
        "file"           => new CURLFile($inputPath),
        "outputFileName" => basename($outputPath)
    ];

    // Initialize cURL
    $ch = curl_init();
    curl_setopt_array($ch, [
        CURLOPT_URL            => $apiUrl,
        CURLOPT_POST           => true,
        CURLOPT_POSTFIELDS     => $postFields,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_HTTPHEADER     => [
            "X-Api-Key: {$apiKey}",
            "X-Api-Secret: {$apiSecret}"
        ]
    ]);

    echo "Converting {$inputPath}...\n";

    // Execute the request
    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $error    = curl_error($ch);
    curl_close($ch);

    // Check for cURL errors
    if ($error) {
        echo "cURL error: {$error}\n";
        return null;
    }

    // Handle the response
    if ($httpCode === 200) {
        file_put_contents($outputPath, $response);
        $fileSize = number_format(filesize($outputPath));
        echo "Success! Saved to {$outputPath} ({$fileSize} bytes)\n";
        return $outputPath;
    } else {
        $errorData = json_decode($response, true);
        $message   = $errorData["message"] ?? "Unknown error";
        echo "Error {$httpCode}: {$message}\n";
        return null;
    }
}

// Run from command line: php convert.php input.docx [output.pdf]
if ($argc < 2) {
    echo "Usage: php convert.php input.docx [output.pdf]\n";
    exit(1);
}

$inputFile  = $argv[1];
$outputFile = $argv[2] ?? null;
convertWordToPdf($inputFile, $outputFile);

Java

Uses the java.net.http.HttpClient introduced in Java 11. No external dependencies required.

import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.UUID;

public class PdfConverter {

    private static final String API_KEY    = "pk_live_abc123def456";
    private static final String API_SECRET = "sk_live_789ghi012jkl";
    private static final String API_URL    = "https://pdf.mapsoft.com/api/pdf/word-to-pdf";

    public static Path convertWordToPdf(Path inputPath, Path outputPath)
            throws IOException, InterruptedException {

        // Default output path: same name with .pdf extension
        if (outputPath == null) {
            String baseName = inputPath.getFileName().toString()
                    .replaceFirst("\\.[^.]+$", "");
            outputPath = inputPath.resolveSibling(baseName + ".pdf");
        }

        // Read the input file
        byte[] fileBytes = Files.readAllBytes(inputPath);
        String fileName  = inputPath.getFileName().toString();

        // Build multipart/form-data body
        String boundary = UUID.randomUUID().toString();
        String lineEnd  = "\r\n";

        StringBuilder bodyBuilder = new StringBuilder();
        bodyBuilder.append("--").append(boundary).append(lineEnd);
        bodyBuilder.append("Content-Disposition: form-data; name=\"file\"; filename=\"")
                   .append(fileName).append("\"").append(lineEnd);
        bodyBuilder.append("Content-Type: application/octet-stream").append(lineEnd);
        bodyBuilder.append(lineEnd);

        // Combine text prefix, file bytes, and text suffix
        byte[] prefix = bodyBuilder.toString().getBytes();
        String suffix = lineEnd + "--" + boundary + "--" + lineEnd;
        byte[] suffixBytes = suffix.getBytes();

        byte[] body = new byte[prefix.length + fileBytes.length + suffixBytes.length];
        System.arraycopy(prefix, 0, body, 0, prefix.length);
        System.arraycopy(fileBytes, 0, body, prefix.length, fileBytes.length);
        System.arraycopy(suffixBytes, 0, body, prefix.length + fileBytes.length,
                         suffixBytes.length);

        // Build and send the HTTP request
        HttpClient client = HttpClient.newHttpClient();
        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create(API_URL))
                .header("X-Api-Key", API_KEY)
                .header("X-Api-Secret", API_SECRET)
                .header("Content-Type", "multipart/form-data; boundary=" + boundary)
                .POST(HttpRequest.BodyPublishers.ofByteArray(body))
                .build();

        System.out.println("Converting " + inputPath + "...");

        HttpResponse<byte[]> response = client.send(request,
                HttpResponse.BodyHandlers.ofByteArray());

        // Handle the response
        if (response.statusCode() == 200) {
            Files.write(outputPath, response.body());
            System.out.printf("Success! Saved to %s (%,d bytes)%n",
                    outputPath, response.body().length);
            return outputPath;
        } else {
            String errorBody = new String(response.body());
            System.err.printf("Error %d: %s%n", response.statusCode(), errorBody);
            return null;
        }
    }

    public static void main(String[] args) throws Exception {
        if (args.length == 0) {
            System.out.println("Usage: java PdfConverter input.docx [output.pdf]");
            System.exit(1);
        }

        Path inputPath  = Path.of(args[0]);
        Path outputPath = args.length > 1 ? Path.of(args[1]) : null;
        convertWordToPdf(inputPath, outputPath);
    }
}