Get your API key
How to convert Excel to PDF (LibreOffice, Python, Node.js, and API)

How to convert Excel to PDF (LibreOffice, Python, Node.js, and API)

Convert XLSX to PDF for free with Excel, LibreOffice CLI, Python, or Node.js. Fix fit-to-page scaling, print areas, and cut-off columns, plus batch conversion.

11 min read

Converting an Excel workbook (.xlsx) to PDF produces a fixed-layout file that opens the same on every device and cannot be edited by mistake. This guide covers five methods: Excel's built-in export, LibreOffice headless CLI, Python automation, Node.js automation, and Google Sheets. It also fixes the problem that trips up most spreadsheet exports: columns cut off by the page edge.

How to convert Excel to PDF in Microsoft Excel

Microsoft Excel has a built-in PDF export under File, Save As. Before exporting, set the scaling, otherwise wide sheets get clipped at the right margin.

Windows:

  1. Open the .xlsx file in Excel.
  2. Go to the Page Layout tab. In the Scale to Fit group, set Width to 1 page (leave Height at Automatic for tall tables).
  3. Click File, then Save As, and choose PDF from the file type dropdown.
  4. Under Options, pick whether to export the active sheet, the entire workbook, or a selection.
  5. Click Save.

macOS:

  1. Open the .xlsx file in Excel.
  2. Set scaling in Page Layout, then click File, Save As, and pick PDF.
  3. Choose Workbook, Sheet, or Selection, then click Export.

Excel's own export produces the most faithful PDF because it uses the same layout engine that displays the workbook on screen. It preserves cell colors, borders, conditional formatting, and charts. This is the best option for one-off conversions when you have an Excel license.

How to convert Excel to PDF with LibreOffice (free, no license)

LibreOffice is a free, open-source office suite that reads .xlsx files and exports PDF from the command line without a GUI. It runs on Linux, macOS, and Windows and is the standard choice for servers and CI pipelines.

Install LibreOffice

# macOS
brew install --cask libreoffice
 
# Ubuntu / Debian
sudo apt install libreoffice
 
# Windows (winget)
winget install LibreOffice

Convert a single file

libreoffice --headless --convert-to pdf book.xlsx

The --headless flag runs LibreOffice without opening a window. The output book.pdf appears in the current directory. Formulas export as their computed values, and charts render as vector graphics.

Convert every .xlsx in a directory

libreoffice --headless --convert-to pdf --outdir ./pdfs *.xlsx

LibreOffice processes files one at a time. On a 2024 MacBook Pro (M3), a 3-sheet financial workbook with charts converts in about 2 to 3 seconds. A workbook with 20 dense sheets takes 6 to 10 seconds.

LibreOffice reads the print ranges and page scaling stored in the .xlsx. If a sheet has no print area set, LibreOffice exports the full used range and may split a wide table across pages. Set the print range and scaling in the source file before converting, or in LibreOffice Calc under Format, Page Style, Sheet.

How to control page fit so columns are not cut off

The main headache with Excel to PDF is width: spreadsheets are wider than a printed page, so columns spill off the right edge or land on separate pages. Set scaling before you export, not after.

Excel offers three scaling controls in the Page Layout tab, Scale to Fit group:

SettingWhat it doesWhen to use
Width: 1 pageShrinks columns so all fit horizontallyWide tables that must stay on one page across
Height: 1 pageShrinks rows so all fit verticallyShort, wide summaries
Width + Height: 1 pageFits the entire sheet on a single pageDashboards, one-page reports
Fit All Columns on One Page (Print menu)Keeps columns intact, allows multiple vertical pagesLong tables where readability matters more than page count

Landscape orientation adds roughly 40 percent more horizontal room than portrait on A4 or Letter, so switch orientation before shrinking text to an unreadable size. For a table with 15 or more columns, Landscape plus Width: 1 page usually keeps the font legible. If the text still becomes too small, split the table across two print areas instead of forcing one page.

In LibreOffice Calc, the same controls live in Format, Page Style, Sheet, under the Scale section: choose "Fit print range(s) to width/height" and set the page count. LibreOffice honors these settings when converting through the CLI, so set them in the .xlsx first.

How to convert Excel to PDF in Python

Python has two practical approaches: call LibreOffice through subprocess for cross-platform servers, or drive Excel through COM automation on Windows for exact fidelity.

Using subprocess with LibreOffice

This works on any operating system with LibreOffice installed and needs no Excel license.

import subprocess
from pathlib import Path
 
def xlsx_to_pdf(input_path: str, output_dir: str = ".") -> str:
    """Convert an .xlsx file to PDF using LibreOffice headless."""
    subprocess.run(
        ["libreoffice", "--headless", "--convert-to", "pdf",
         "--outdir", output_dir, input_path],
        check=True,
        timeout=120,
    )
    stem = Path(input_path).stem
    return str(Path(output_dir) / f"{stem}.pdf")
 
pdf_path = xlsx_to_pdf("q3-report.xlsx", "./output")
print(f"Saved: {pdf_path}")

Batch convert a directory

from pathlib import Path
import subprocess
 
input_dir = Path("./workbooks")
output_dir = Path("./pdfs")
output_dir.mkdir(exist_ok=True)
 
xlsx_files = list(input_dir.glob("*.xlsx"))
 
for xlsx in xlsx_files:
    subprocess.run(
        ["libreoffice", "--headless", "--convert-to", "pdf",
         "--outdir", str(output_dir), str(xlsx)],
        check=True,
        timeout=180,
    )
 
print(f"Converted {len(xlsx_files)} files")

Using Excel COM on Windows

When exact Excel fidelity matters and the script runs on Windows with Excel installed, drive Excel directly through pywin32. This respects every print setting saved in the workbook.

import win32com.client
 
excel = win32com.client.Dispatch("Excel.Application")
excel.Visible = False
wb = excel.Workbooks.Open(r"C:\reports\q3-report.xlsx")
 
# 0 = xlTypePDF
wb.ExportAsFixedFormat(0, r"C:\reports\q3-report.pdf")
 
wb.Close(False)
excel.Quit()

LibreOffice does not support concurrent conversions from one install directory. For parallel processing, give each worker its own --user-install profile, or run conversions sequentially in a queue.

How to convert Excel to PDF in Node.js

The libreoffice-convert npm package wraps the LibreOffice CLI and returns a Buffer, which is handy for backends that already produce spreadsheets.

npm install libreoffice-convert
import { readFileSync, writeFileSync } from "fs";
import { convert } from "libreoffice-convert";
import { promisify } from "util";
 
const convertAsync = promisify(convert);
 
async function xlsxToPdf(inputPath: string, outputPath: string) {
  const input = readFileSync(inputPath);
  const pdf = await convertAsync(input, ".pdf", undefined);
  writeFileSync(outputPath, pdf);
  console.log(`Saved: ${outputPath}`);
}
 
xlsxToPdf("sales.xlsx", "sales.pdf");

This spawns a LibreOffice process per conversion, so it fits low-volume or batch workloads rather than a high-throughput API endpoint. For a request-per-second API, keep a warm LibreOffice pool or move to direct HTML rendering (covered below).

How to convert Excel to PDF with Google Sheets

Google Sheets converts .xlsx to PDF in the browser with no local software. Upload the file to Google Drive, open it in Sheets, then use File, Download, PDF. The export dialog exposes the same scaling controls (fit to width, fit to page, landscape) as the desktop apps.

For automation, the Google Sheets export URL accepts query parameters that set the format, orientation, and scale:

https://docs.google.com/spreadsheets/d/SHEET_ID/export?format=pdf&portrait=false&fitw=true&gridlines=false

Pass fitw=true to fit the content to page width, portrait=false for landscape, and gridlines=false to hide the grid. This is a practical path when your data already lives in Google Sheets, and it pairs with the approach in generate PDF from Google Sheets.

Comparison: which Excel to PDF method to use?

MethodRequires Excel licenseRuns headlessLayout controlBatch supportBest for
Microsoft ExcelYesNoExactNo (manual)One-off, highest fidelity
LibreOffice CLINoYesHigh (from .xlsx settings)YesServers, CI/CD, batch
Python (subprocess)NoYesHigh (from .xlsx settings)YesLinux and cross-platform scripts
Python (win32com)Yes (Windows)YesExactYesWindows servers with Excel
Node.js (libreoffice-convert)NoYesHigh (from .xlsx settings)YesNode.js backends
Google SheetsNoYes (cloud)Good (export params)Yes (with quota)No local install, cloud-first

For production servers that need no license, LibreOffice with fonts installed and print settings set in the .xlsx is the standard choice. Excel's own export is the most accurate but needs a license and a session. Both produce vector text and lines, so tables stay sharp at any zoom.

Common Excel to PDF issues and fixes

Columns are cut off at the right edge. The sheet is wider than the page and no scaling is set. Fix: set Width to 1 page in Page Layout, Scale to Fit, or switch to Landscape. Set this in the .xlsx before converting with LibreOffice, since the CLI reads the file's own print settings.

The whole workbook exports when you only wanted one sheet. The export scope defaults to the active sheet in some versions and the whole workbook in others. Fix: in File, Print or the Save As Options dialog, choose Active Sheets or Selection explicitly.

Gridlines are missing or unwanted. Screen gridlines do not print by default. To show them, enable Page Layout, Sheet Options, Gridlines, Print. To hide them in a Google Sheets export, add gridlines=false to the export URL.

Fonts shift or numbers change width. LibreOffice substitutes missing fonts with metrically different alternatives, which can shift column widths and page breaks. Fix: install the exact fonts used in the workbook on the conversion machine. On Linux, install the Microsoft core fonts for Calibri and Cambria.

The PDF is very large. Workbooks with embedded high-resolution images produce large PDFs. After conversion, run the file through the PDF4.dev compress tool. A 12 MB PDF with product photos typically drops to 2 to 4 MB. To combine several exported sheets into one document, use the merge PDF tool.

When to generate a PDF from data instead of Excel

Excel to PDF works well for spreadsheets a person built and wants to share as a fixed document. But for reports, invoices, and statements you generate from data on a schedule, starting from a spreadsheet is fragile. Page-fit scaling, font substitution, and column drift compound when you produce hundreds of documents a day.

PDF4.dev takes a different path: you write an HTML template with CSS for exact layout, inject the numbers through Handlebars variables, and render the PDF with a headless browser. The rendering engine (Chromium) is the same one that displays the template in a browser, so the output is identical every time, with no page-fit guesswork.

const response = await fetch("https://api.pdf4.dev/v1/render", {
  method: "POST",
  headers: {
    Authorization: `Bearer ${process.env.PDF4_API_KEY}`,
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
    template_id: "monthly-statement",
    data: {
      client: "Acme Corp",
      period: "June 2026",
      rows: [
        { item: "Rendering", qty: 1200, total: "$248.00" },
        { item: "Storage", qty: 500, total: "$45.00" },
      ],
      total: "$293.00",
    },
  }),
});
 
const pdf = await response.arrayBuffer();

This produces a table with exact column widths, exact fonts, and no clipped edges, because you control the layout in CSS instead of fighting a spreadsheet's print settings. For data-driven documents at scale, HTML to PDF with PDF4.dev is more predictable than converting .xlsx files. It is the same reasoning that applies to converting Word to PDF for generated documents.

Try the free HTML to PDF toolTry it free

Summary

  • Set scaling first: in Excel, Page Layout, Scale to Fit, Width 1 page, and use Landscape for wide tables so columns are not cut off.
  • For one-off conversions with a license, use Excel's File, Save As PDF. It gives the most faithful output.
  • For free conversions without Excel, install LibreOffice and run libreoffice --headless --convert-to pdf book.xlsx.
  • For Python automation, call LibreOffice through subprocess, or use win32com on Windows with Excel installed.
  • For Node.js backends, use the libreoffice-convert npm package.
  • For cloud-first workflows, export from Google Sheets with fitw=true and portrait=false in the export URL.
  • For documents you generate from data, skip the spreadsheet and render directly from an HTML template with PDF4.dev for exact control over layout, fonts, and page fit. See the complete guide to PDF conversion for the full picture, and PDF to Excel for the reverse direction.

Free tools mentioned:

Html To PdfTry it freeCompress PdfTry it freeMerge PdfTry it freeSplit PdfTry it free

Start generating PDFs

Build PDF templates with a visual editor. Render them via API from any language in ~300ms.