@push.rocks/smartpdf
Create PDFs on the fly from HTML, websites, or existing PDFs with advanced features like text extraction, PDF merging, and PNG conversion.
Install
To install @push.rocks/smartpdf
, use npm or yarn:
npm install @push.rocks/smartpdf --save
Or with yarn:
yarn add @push.rocks/smartpdf
Requirements
This package requires a Chrome or Chromium installation to be available on the system, as it uses Puppeteer for rendering. The package will automatically detect and use the appropriate executable.
Usage
@push.rocks/smartpdf
provides a powerful interface for PDF generation and manipulation. All examples use ESM syntax and TypeScript.
Getting Started
First, import the necessary classes:
import { SmartPdf, IPdf } from '@push.rocks/smartpdf';
Basic Setup with Automatic Port Allocation
SmartPdf automatically finds an available port between 20000-30000 for its internal server:
async function setupSmartPdf() {
const smartPdf = await SmartPdf.create();
await smartPdf.start();
// Your PDF operations here
await smartPdf.stop();
}
Advanced Setup with Custom Port Configuration
You can specify custom port settings to avoid conflicts or meet specific requirements:
// Use a specific port
const smartPdf = await SmartPdf.create({ port: 3000 });
// Use a custom port range
const smartPdf = await SmartPdf.create({
portRangeStart: 4000,
portRangeEnd: 5000
});
// The server will find an available port in your specified range
await smartPdf.start();
console.log(`Server running on port: ${smartPdf.serverPort}`);
Creating PDFs from HTML Strings
Generate PDFs from HTML content with full CSS support:
async function createPdfFromHtml() {
const smartPdf = await SmartPdf.create();
await smartPdf.start();
const htmlString = `
<!DOCTYPE html>
<html>
<head>
<style>
body { font-family: Arial, sans-serif; margin: 40px; }
h1 { color: #333; }
.highlight { background-color: yellow; }
</style>
</head>
<body>
<h1>Professional PDF Document</h1>
<p>This PDF was generated from <span class="highlight">HTML content</span>.</p>
</body>
</html>
`;
const pdf: IPdf = await smartPdf.getA4PdfResultForHtmlString(htmlString);
// pdf.buffer contains the PDF data
// pdf.id contains a unique identifier
// pdf.name contains the filename
// pdf.metadata contains additional information like extracted text
await smartPdf.stop();
}
Generating PDFs from Websites
Capture web pages as PDFs with two different approaches:
A4 Format PDF from Website
Captures the viewable area formatted for A4 paper:
async function createA4PdfFromWebsite() {
const smartPdf = await SmartPdf.create();
await smartPdf.start();
const pdf: IPdf = await smartPdf.getPdfResultForWebsite('https://example.com');
// Save to file
await fs.writeFile('website-a4.pdf', pdf.buffer);
await smartPdf.stop();
}
Full Webpage as Single PDF
Captures the entire webpage in a single PDF, regardless of length:
async function createFullPdfFromWebsite() {
const smartPdf = await SmartPdf.create();
await smartPdf.start();
const pdf: IPdf = await smartPdf.getFullWebsiteAsSinglePdf('https://example.com');
// This captures the entire scrollable area
await fs.writeFile('website-full.pdf', pdf.buffer);
await smartPdf.stop();
}
Merging Multiple PDFs
Combine multiple PDF files into a single document:
async function mergePdfs() {
const smartPdf = await SmartPdf.create();
await smartPdf.start();
// Create or load your PDFs
const pdf1 = await smartPdf.getA4PdfResultForHtmlString('<h1>Document 1</h1>');
const pdf2 = await smartPdf.getA4PdfResultForHtmlString('<h1>Document 2</h1>');
const pdf3 = await smartPdf.readFileToPdfObject('./existing-document.pdf');
// Merge PDFs - order matters!
const mergedPdf: Uint8Array = await smartPdf.mergePdfs([
pdf1.buffer,
pdf2.buffer,
pdf3.buffer
]);
// Save the merged PDF
await fs.writeFile('merged-document.pdf', mergedPdf);
await smartPdf.stop();
}
Reading PDFs and Extracting Text
Extract text content from existing PDFs:
async function extractTextFromPdf() {
const smartPdf = await SmartPdf.create();
// Read PDF from disk
const pdf: IPdf = await smartPdf.readFileToPdfObject('/path/to/document.pdf');
// Extract all text
const extractedText = await smartPdf.extractTextFromPdfBuffer(pdf.buffer);
console.log('Extracted text:', extractedText);
// The pdf object also contains metadata with text extraction
console.log('Metadata:', pdf.metadata);
}
Converting PDF to PNG Images
Convert each page of a PDF into PNG images:
async function convertPdfToPng() {
const smartPdf = await SmartPdf.create();
await smartPdf.start();
// Load a PDF
const pdf = await smartPdf.readFileToPdfObject('./document.pdf');
// Convert to PNG images (one per page)
const pngImages: Uint8Array[] = await smartPdf.convertPDFToPngBytes(pdf.buffer);
// Save each page as a PNG
pngImages.forEach((pngBuffer, index) => {
fs.writeFileSync(`page-${index + 1}.png`, pngBuffer);
});
await smartPdf.stop();
}
Using External Browser Instance
For advanced use cases, you can provide your own Puppeteer browser instance:
import puppeteer from 'puppeteer';
async function useExternalBrowser() {
// Create your own browser instance with custom options
const browser = await puppeteer.launch({
headless: true,
args: ['--no-sandbox', '--disable-setuid-sandbox']
});
const smartPdf = await SmartPdf.create();
await smartPdf.start(browser);
// Use SmartPdf normally
const pdf = await smartPdf.getA4PdfResultForHtmlString('<h1>Hello</h1>');
// SmartPdf will not close the browser when stopping
await smartPdf.stop();
// You control the browser lifecycle
await browser.close();
}
Running Multiple Instances
Thanks to automatic port allocation, you can run multiple SmartPdf instances simultaneously:
async function runMultipleInstances() {
// Each instance automatically finds its own free port
const instance1 = await SmartPdf.create();
const instance2 = await SmartPdf.create();
const instance3 = await SmartPdf.create();
// Start all instances
await Promise.all([
instance1.start(),
instance2.start(),
instance3.start()
]);
console.log(`Instance 1 running on port: ${instance1.serverPort}`);
console.log(`Instance 2 running on port: ${instance2.serverPort}`);
console.log(`Instance 3 running on port: ${instance3.serverPort}`);
// Use instances independently
const pdfs = await Promise.all([
instance1.getA4PdfResultForHtmlString('<h1>PDF 1</h1>'),
instance2.getA4PdfResultForHtmlString('<h1>PDF 2</h1>'),
instance3.getA4PdfResultForHtmlString('<h1>PDF 3</h1>')
]);
// Clean up all instances
await Promise.all([
instance1.stop(),
instance2.stop(),
instance3.stop()
]);
}
Error Handling
Always wrap SmartPdf operations in try-catch blocks and ensure proper cleanup:
async function safePdfGeneration() {
let smartPdf: SmartPdf;
try {
smartPdf = await SmartPdf.create();
await smartPdf.start();
const pdf = await smartPdf.getA4PdfResultForHtmlString('<h1>Hello</h1>');
// Process PDF...
} catch (error) {
console.error('PDF generation failed:', error);
// Handle error appropriately
} finally {
// Always cleanup
if (smartPdf) {
await smartPdf.stop();
}
}
}
IPdf Interface
The IPdf
interface represents a PDF with its metadata:
interface IPdf {
name: string; // Filename of the PDF
buffer: Buffer; // PDF content as buffer
id: string | null; // Unique identifier
metadata?: {
textExtraction?: string; // Extracted text content
};
}
Best Practices
- Always start and stop: Initialize with
start()
and cleanup withstop()
to properly manage resources. - Port management: Use the automatic port allocation feature to avoid conflicts when running multiple instances.
- Error handling: Always implement proper error handling as PDF generation can fail due to various reasons.
- Resource cleanup: Ensure
stop()
is called even if an error occurs to prevent memory leaks. - HTML optimization: When creating PDFs from HTML, ensure your HTML is well-formed and CSS is embedded or inlined.
License and Legal Information
This repository contains open-source code that is licensed under the MIT License. A copy of the MIT License can be found in the license file within this repository.
Please note: The MIT License does not grant permission to use the trade names, trademarks, service marks, or product names of the project, except as required for reasonable and customary use in describing the origin of the work and reproducing the content of the NOTICE file.
Trademarks
This project is owned and maintained by Task Venture Capital GmbH. The names and logos associated with Task Venture Capital GmbH and any related products or services are trademarks of Task Venture Capital GmbH and are not included within the scope of the MIT license granted herein. Use of these trademarks must comply with Task Venture Capital GmbH's Trademark Guidelines, and any usage must be approved in writing by Task Venture Capital GmbH.
Company Information
Task Venture Capital GmbH
Registered at District court Bremen HRB 35230 HB, Germany
For any legal inquiries or if you require further information, please contact us via email at hello@task.vc.
By using this repository, you acknowledge that you have read this section, agree to comply with its terms, and understand that the licensing of the code does not imply endorsement by Task Venture Capital GmbH of any derivative works.