pdf-lib
pdf-lib creates new PDFs and modifies existing ones, and runs in Node.js, browsers, Deno, and React Native. A loaded document can gain, lose, or reorder pages, copy pages from another PDF, and take new text, images, and SVG paths. The form API creates fields, fills them, and flattens them into page content. Custom fonts embed once the separate @pdf-lib/fontkit package is registered. Encrypted PDFs are outside its support.
- Downloads / mo
- 118.0M
- Stars
- 8.7K
- Last release
- 1.17.1
- License
- MIT
Strengths
- Modifies existing PDF documents. Load existing PDFs to add content, copy pages, and update form fields.
- Creates and fills PDF forms. Create fields or read and fill existing text fields and controls.
Limitations
- Page text editing is restricted. Existing page text can't be edited or removed; only form field text changes.
- Needs unencrypted input PDFs. Encrypted PDFs must be decrypted before loading and modifying them.
- Custom fonts need fontkit. Install and register @pdf-lib/fontkit before embedding custom fonts.
Quickstart
import {PDFDocument} from 'pdf-lib' const pdfDoc = await PDFDocument.create() const page = pdfDoc.addPage() page.drawText('Hello world!', {x: 50, y: 700, size: 20}) const pdfBytes = await pdfDoc.save()
pdf-lib examples
async function extractPages() { const pagesInput = document.getElementById( 'pages-to-extract' ) as HTMLInputElement; if (!pagesInput || !pagesInput.value.trim()) { showAlert('No Pages', 'Please enter page numbers to extract.'); return; } const pagesToExtract = parsePageRanges( pagesInput.value, extractState.totalPages ).map((i) => i + 1); if (pagesToExtract.length === 0) { showAlert('Invalid Pages', 'No valid page numbers found.'); return; } showLoader('Extracting pages...'); try { const zip = new JSZip(); const baseName = extractState.file?.name.replace('.pdf', '') || 'document'; for (const pageNum of pagesToExtract) { const newPdf = await PDFDocument.create(); const [copiedPage] = await newPdf.copyPages(extractState.pdfDoc, [ pageNum - 1, ]); newPdf.addPage(copiedPage); const pdfBytes = await newPdf.save(); zip.file(`${baseName}_page_${pageNum}.pdf`, pdfBytes); } const zipBlob = await zip.generateAsync({ type: 'blob' }); downloadFile(zipBlob, `${baseName}_extracted_pages.zip`); hideLoader(); showAlert( 'Success', trText('Extracted {{length}} page(s) successfully!', { length: pagesToExtract.length, }), 'success', () => { resetState(); } ); } catch (error) { console.error('Error extracting pages:', error); hideLoader(); showAlert('Error', 'Failed to extract pages.'); } }