Products Technologies Demo Docs Blog Support Company

How to Convert Excel to PDF in JavaScript

Convert an Excel workbook to PDF in JavaScript with TX Sheet Control. Configure paper size, orientation, margins, a print area, and one-page-wide scaling in the browser.

How to Convert Excel to PDF in JavaScript

Export an Excel worksheet as a PDF report directly in the browser. This example loads a sales workbook, sets its print layout, and creates a downloadable landscape A4 PDF with all eight columns on one page.

Part 2 of the JavaScript Spreadsheet Essentials series.

Run the JavaScript Sample

This example uses TX Sheet Control 2.0.0 with plain JavaScript. Download the complete sample and output files (ZIP). Extract it and open its sample folder.

Copy the complete browser folder from your TX Sheet Control download into sample/public/sheet, retaining its fonts, languages, and notices. Put your signed tx-sheet-control.license beside server.mjs. Use Node.js 22 or later to run the included local host:

npm start

Open http://127.0.0.1:5085. The host serves the files; workbook editing and conversion run in the browser. The HTML supplies the editor host and loads /sheet/tx-sheet-control.min.js followed by app.js.

The shared common.js module creates the editor, awaits its fonts and initial readiness, manages progress messages, and delivers byte downloads:

export const { Spreadsheet, StreamType } = TXTextControl.TXSheetControl;
export const status = document.getElementById('status');

export async function createEditor() {
    const response = await fetch('/license', {cache:'no-store'});
    if (!response.ok) throw new Error('Configure tx-sheet-control.license before starting the sample.');
    const editor = new Spreadsheet(document.getElementById('sheet'), {
        license: (await response.text()).trim(),
        fontCatalogURL: '/sheet/fonts/catalog.json',
        fontBaseURL: '/sheet/fonts/', locale:'en-US', currency:'USD'
    });
    await editor.ready;
    return editor;
}

export function download(bytes, name, mime) {
    const url = URL.createObjectURL(new Blob([bytes], {type:mime}));
    const link = document.createElement('a');
    link.href=url; link.download=name;
    document.body.append(link); link.click(); link.remove();
    setTimeout(()=>URL.revokeObjectURL(url),5000);
}

export function showWarnings(warnings) {
    const list=document.getElementById('diagnostics');
    list.replaceChildren();
    const messages=warnings.length ? warnings.map(w=>typeof w==='string' ? w : w.message ?? JSON.stringify(w))
        : ['No conversion warnings.'];
    for(const message of messages) {
        const item=document.createElement('li'); item.textContent=message; list.append(item);
    }
}

export async function busy(message, action) {
    const buttons=[...document.querySelectorAll('button,input[type=file]')];
    buttons.forEach(button=>button.disabled=true);
    status.textContent=message;
    try { return await action(); }
    catch(error) { status.textContent=error.message; throw error; }
    finally { buttons.forEach(button=>button.disabled=false); }
}

Load the Excel Workbook

The sample loads sales-input.xlsx with editor.load(bytes, StreamType.SpreadsheetML). Wait for that promise before obtaining the worksheet or configuring print settings. Its six orders contain $5,400 in revenue, $3,470 in costs, and $1,930 in margin.

The input workbook is included in the sample ZIP. To use a selected local file instead, obtain its bytes with await file.arrayBuffer() and keep the same load call.

Configure Paper, Margins, and Print Area

sheet.print.configure() supplies the settings used by the PDF export. The example uses landscape A4 paper, 12 mm left and right margins, and 15 mm top and bottom margins:

export function configurePdf(sheet) {
    sheet.print.configure({
        page:{size:'A4',orientation:'landscape'},
        margins:{unit:'mm',left:12,right:12,top:15,bottom:15},
        area:'A1:H12',gridlines:false,
        fitToPage:true,fitToWidth:1,fitToHeight:0,
        footer:{center:'Page &P of &N'}
    });
}

export async function createPdf(editor) {
    const {StreamType}=TXTextControl.TXSheetControl;
    const sheet=editor.workbook.sheets.at(0);
    configurePdf(sheet);
    return editor.save(StreamType.PDF,{
        pdf:{sheet,title:'Northstar Sales Report',locale:'en-US',timeZone:'UTC'}
    });
}

area: 'A1:H12' includes the report title, headings, six orders, and the total row. An explicit print area also prevents unrelated notes or unused formatted regions from extending the report.

fitToPage: true, fitToWidth: 1, and fitToHeight: 0 keep all columns on one page while allowing additional pages vertically. Setting both dimensions to one would shrink a long report to a single page, which can make its text too small.

The sample in Page Layout view, with the worksheet positioned on landscape A4 paper.
The sample in Page Layout view, with the worksheet positioned on landscape A4 paper.

Export Only the Sales Worksheet

createPdf() saves through the editor with StreamType.PDF. Its pdf.sheet option selects the Sales worksheet, so the input workbook's Summary and Notes worksheets do not add pages. Title, locale, and time zone are set explicitly for the export.

The footer uses &P and &N for the current page and page count. PDF is an output format; keep XLSX or TXWB when the recipient also needs an editable workbook.

Offer a PDF Download

The application waits until PDF bytes are available, creates a Blob with application/pdf, and downloads sales-report.pdf. Its initialization and download button are shown below:

import {createEditor,StreamType,download,busy,showWarnings,status} from './common.js';
import {configurePdf,createPdf} from './model.js';

async function start(){
 const editor=await createEditor();
 const actions={};let model={};
 const addAction=(id,label,action)=>{
  actions[id]=action;const button=document.createElement('button');button.id=id;button.textContent=label;
  button.addEventListener('click',()=>busy('Working…',action).catch(()=>{}));
  document.getElementById('actions').append(button);
 };
 const downloadXlsx=async()=>{
  const bytes=await editor.save(StreamType.SpreadsheetML);
  showWarnings(editor.getXlsxWarnings());
  download(bytes,'excel-to-pdf.xlsx','application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
  status.textContent='Workbook exported successfully. Review conversion diagnostics.';
 };
 const response=await fetch('./sales-input.xlsx');
 if(!response.ok)throw new Error('Sample workbook could not be loaded.');
 const result=await editor.load(await response.arrayBuffer(),StreamType.SpreadsheetML);
 showWarnings(result.warnings);configurePdf(editor.workbook.sheets.at(0));
 addAction('export','Download PDF',async()=>{const bytes=await createPdf(editor);download(bytes,'sales-report.pdf','application/pdf');status.textContent='PDF exported with landscape A4 pages and a one-page-wide print area.';});
 status.textContent='Sales workbook loaded. Print area A1:H12 · A4 landscape · 12 mm side margins.';
 return {editor,actions,get model(){return model;}};
}
window.sampleReady=start();
window.sampleReady.catch(error=>{status.textContent=error.message;console.error(error);});

Keep the supplied fonts available and wait for editor.ready. Font metrics influence wrapping and pagination, and PDF export needs fonts that can be embedded.

Review the Generated Report

The example produces one landscape A4 page. Check that the total row and the Margin column are visible, that the currency values are correct, and that the footer says Page 1 of 1.

The PDF exported by the browser sample: one landscape A4 sales report.
The PDF exported by the browser sample: one landscape A4 sales report.

Download the generated sales report PDF. The sample ZIP also contains the input workbook and PDF output.

For larger datasets, extend the print area to the actual total row and retain automatic height. Review page breaks before delivery instead of relying on the editor's screen zoom, which does not define the print scaling.

Read more in the TX Sheet Control documentation.

Previous: How to Import, Edit, and Export Excel XLSX Files in JavaScript
Next: How to Export JSON Data to Excel in JavaScript

Frequently Asked Questions

Yes. The sample calls the browser editor save method with StreamType.PDF. The local Node host only serves the application files.

Enable fitToPage, set fitToWidth to 1, and use fitToHeight 0 to allow additional pages vertically.

Yes. Pass the worksheet handle through the pdf.sheet save option.

Stay in the loop!

Subscribe to the newsletter to receive the latest updates.

TX Sheet Control

Excel-compatible spreadsheet editing, a robust calculation engine, and interactive dashboards for business applications.

Learn more about TX Sheet Control

Related Posts

JavaScriptExcelJavaScript Spreadsheet Essentials

How to Load REST API Data into a JavaScript Spreadsheet

Fetch REST API JSON into a JavaScript spreadsheet with TX Sheet Control. Validate and map records, show loading and error states, refresh data, and update dependent formulas.


JavaScriptExcelJavaScript Spreadsheet Essentials

How to Create an Excel XLSX File in JavaScript

Create an Excel XLSX file from scratch in JavaScript. Add worksheets, write typed data and formulas, format headers and currency, set column widths, and download the workbook.


JavaScriptExcelJavaScript Spreadsheet Essentials

How to Create an ODS File in JavaScript

Create an ODS workbook in JavaScript with text, numbers, formulas, and currency formatting. Download it, reopen it in TX Sheet Control, and check its standard spreadsheet content in LibreOffice Calc.


JavaScriptExcelJavaScript Spreadsheet Essentials

How to Apply Conditional Formatting in a JavaScript Spreadsheet

Apply conditional formatting in a JavaScript spreadsheet: highlight overdue invoices and negative margins, add revenue data bars and target color scales, and update the rules through cell edits.


JavaScriptExcelJavaScript Spreadsheet Essentials

How to Create Pivot Tables in JavaScript

Create a JavaScript PivotTable from sales records with TX Sheet Control. Configure row and column fields, sum revenue, filter regions, refresh source edits, and export a native Excel PivotTable.

Share this blog post on:

​​​