Office2PDF · Blog

Office to PDF in 5 Minutes: A Next.js and Node.js Integration Guide

Stop wrestling with complex libraries. Learn how to integrate high-fidelity document conversion into your Next.js app using office2pdf.

Office2PDF
Office to PDF in 5 Minutes: A Next.js and Node.js Integration Guide

As a developer, you don’t want to spend days configuring LibreOffice clusters or debugging font issues on a Linux server. You want a solution that works with a simple API call.

In this guide, we’ll show you how to build a complete Office-to-PDF upload feature in a Next.js application using office2pdf—the optimized API for high-speed, high-fidelity conversion.


Prerequisites

  1. A Next.js project (App Router preferred).
  2. An office2pdf API Key (Get your key here).
  3. axios installed for handling requests: npm install axios

Step 1: Create the Backend API Route

We’ll create a secure server-side route to handle the conversion. This prevents exposing your API key to the frontend.

// app/api/convert/route.ts
import { NextResponse } from "next/server";
import axios from "axios";

const OFFICE2PDF_API_URL =
  "[https://api.office2pdf.com/api/pdf/preview](https://api.office2pdf.com/api/pdf/preview)";
const API_KEY = process.env.OFFICE2PDF_API_KEY;

export async function POST(req: Request) {
  try {
    const formData = await req.formData();
    const file = formData.get("file");

    if (!file) {
      return NextResponse.json({ error: "No file uploaded" }, { status: 400 });
    }

    // Forward the file to office2pdf highly-optimized engine
    const response = await axios.post(OFFICE2PDF_API_URL, formData, {
      headers: {
        "x-api-key": `${API_KEY}`,
        "Content-Type": "multipart/form-data",
      },
      responseType: "arraybuffer", // Get the PDF as a buffer
    });

    return new NextResponse(response.data, {
      headers: {
        "Content-Type": "application/pdf",
        "Content-Disposition": 'attachment; filename="converted.pdf"',
      },
    });
  } catch (error) {
    console.error("Conversion error:", error);
    return NextResponse.json({ error: "Conversion failed" }, { status: 500 });
  }
}

Step 2: Build the Frontend Upload Component

// components/FileConverter.tsx
"use client";

import { useState } from "react";

export default function FileConverter() {
  const [loading, setLoading] = useState(false);

  const handleUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
    if (!e.target.files?.[0]) return;

    setLoading(true);
    const formData = new FormData();
    formData.append("file", e.target.files[0]);

    try {
      const response = await fetch("/api/convert", {
        method: "POST",
        body: formData,
      });

      if (!response.ok) throw new Error("Conversion failed");

      // Download the PDF automatically
      const blob = await response.blob();
      const url = window.URL.createObjectURL(blob);
      const a = document.createElement("a");
      a.href = url;
      a.download = "converted_document.pdf";
      document.body.appendChild(a);
      a.click();
      a.remove();
    } catch (err) {
      alert("Something went wrong!");
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="p-6 border-2 border-dashed border-gray-300 rounded-xl text-center">
      <h3 className="text-lg font-semibold mb-2">Convert Office to PDF</h3>
      <input
        type="file"
        accept=".docx,.xlsx,.pptx"
        onChange={handleUpload}
        disabled={loading}
        className="block w-full text-sm text-gray-500 file:mr-4 file:py-2 file:px-4 file:rounded-full file:border-0 file:text-sm file:font-semibold file:bg-blue-50 file:text-blue-700 hover:file:bg-blue-100"
      />
      {loading && (
        <p className="mt-4 text-blue-600 animate-pulse">
          Processing with office2pdf...
        </p>
      )}
    </div>
  );
}

Why use office2pdf for this?

Choosing the right engine is a critical business decision. As we compared in our Open-Source vs. Paid API analysis, office2pdf offers a unique “Goldilocks” solution:

  • High fidelity
    Unlike standard Gotenberg, our engine is tuned to handle complex Microsoft Office layouts perfectly.

  • Zero server management
    Forget about OOM errors, font installations, or maintaining conversion workers.

  • Blazing fast
    Our infrastructure is optimized for sub-second conversions on most standard documents.

  • Cost-effective
    Pay only for what you use, with rates far below legacy enterprise APIs.


Wrapping up

In just a few lines of code, you’ve integrated a robust document conversion pipeline into your Next.js app.
Whether you’re building a Slack alternative or a specialized SaaS tool, office2pdf takes the heavy lifting out of document processing.

Convert Office → PDF securely

Low-cost API with security-first defaults for production pipelines.