Skip to content

Latest commit

 

History

6 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 

Repository files navigation

LaTeX Service

A lightweight Express.js microservice that compiles LaTeX documents to PDF format. This service provides a simple REST API for converting LaTeX source code into PDF files.

Features

  • ✅ RESTful API for LaTeX to PDF compilation
  • ✅ Docker containerized with all LaTeX dependencies included
  • ✅ Error handling with detailed compilation logs
  • ✅ Temporary file cleanup
  • ✅ JSON request/response format

Prerequisites

Local Development

  • Node.js 14.x or higher
  • npm or yarn
  • LaTeX distribution (texlive-latex-base, texlive-latex-extra, etc.)

Docker

  • Docker installed

Installation

Local Setup

  1. Clone the repository:
git clone <repository-url>
cd latex-service
  1. Install dependencies:
npm install
  1. Install LaTeX dependencies (Ubuntu/Debian):
sudo apt-get update
sudo apt-get install -y \
    texlive-latex-base \
    texlive-latex-extra \
    texlive-fonts-recommended \
    texlive-latex-recommended
  1. Start the server:
npm start
# or
node server.js

The service will be available at http://localhost:3000

Docker Setup

  1. Build the Docker image:
docker build -t latex-service .
  1. Run the container:
docker run -p 3000:3000 latex-service

The service will be available at http://localhost:3000

API Endpoints

POST /compile

Compiles LaTeX code to PDF.

Request:

curl -X POST http://localhost:3000/compile \
  -H "Content-Type: application/json" \
  -d '{"latex":"\\documentclass{article}\\begin{document}Hello World\\end{document}"}'

Request Body:

{
  "latex": "\\documentclass{article}\n\\begin{document}\nHello World\n\\end{document}"
}

Success Response (200):

  • Returns the compiled PDF file with Content-Type: application/pdf

Error Response (500):

{
  "error": "PDF not generated",
  "log": "<pdflatex compilation log>"
}

Usage Example

JavaScript/Node.js

const axios = require("axios");
const fs = require("fs");

const latexCode = `
\\documentclass{article}
\\usepackage[utf-8]{inputenc}
\\title{Sample Document}
\\author{Author Name}
\\date{\\today}
\\begin{document}
\\maketitle
\\section{Introduction}
This is a sample document.
\\end{document}
`;

axios
  .post(
    "http://localhost:3000/compile",
    { latex: latexCode },
    { responseType: "arraybuffer" },
  )
  .then((response) => {
    fs.writeFileSync("output.pdf", response.data);
    console.log("PDF generated successfully!");
  })
  .catch((error) => {
    console.error("Compilation error:", error.response.data);
  });

Python

import requests
import json

latex_code = r"""
\documentclass{article}
\begin{document}
Hello World
\end{document}
"""

response = requests.post(
    'http://localhost:3000/compile',
    json={'latex': latex_code},
    headers={'Content-Type': 'application/json'}
)

if response.status_code == 200:
    with open('output.pdf', 'wb') as f:
        f.write(response.content)
    print('PDF generated successfully!')
else:
    print('Error:', response.json())

Configuration

Environment Variables

Currently, the service uses a hardcoded port (3000). To make this configurable, modify server.js:

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => console.log(`Server running on port ${PORT}`));

Troubleshooting

"PDF not generated" Error

  • Check the returned log field in the error response for LaTeX compilation errors
  • Ensure your LaTeX syntax is correct
  • Verify all required LaTeX packages are included in the Dockerfile

Port Already in Use

# Find the process using port 3000
lsof -i :3000

# Kill the process (replace PID with the actual process ID)
kill -9 <PID>

Docker Build Issues

# Clear Docker cache and rebuild
docker build --no-cache -t latex-service .

LaTeX Package Missing

Add the required package to the Dockerfile:

RUN apt-get install -y texlive-<package-name>

Then rebuild the image.

Project Structure

latex-service/
├── Dockerfile          # Docker configuration
├── package.json        # Node.js dependencies
├── server.js           # Main Express server
└── README.md           # This file

Dependencies

  • express (^4.18.2): Web framework for Node.js
  • pdflatex: LaTeX to PDF compiler (system-level)

Limits

  • Maximum request body size: 1MB
  • PDF generation timeout: Uses system default (pdflatex timeout)
  • Temporary files are stored in /tmp

Security Considerations

⚠️ Warning: This service uses pdflatex --no-shell-escape to prevent shell command injection. However, ensure proper input validation and rate limiting are implemented in production environments.

Support

For issues or questions, please open an issue in the repository.

About

A lightweight Express.js microservice that compiles LaTeX documents to PDF format. This service provides a simple REST API for converting LaTeX source code into PDF files.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Used by

Contributors

Languages