# @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: ```bash npm install @push.rocks/smartpdf --save ``` Or with yarn: ```bash 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: ```typescript 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: ```typescript 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: ```typescript // 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: ```typescript async function createPdfFromHtml() { const smartPdf = await SmartPdf.create(); await smartPdf.start(); const htmlString = `

Professional PDF Document

This PDF was generated from HTML content.

`; 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: ```typescript 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: ```typescript 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: ```typescript async function mergePdfs() { const smartPdf = await SmartPdf.create(); await smartPdf.start(); // Create or load your PDFs const pdf1 = await smartPdf.getA4PdfResultForHtmlString('

Document 1

'); const pdf2 = await smartPdf.getA4PdfResultForHtmlString('

Document 2

'); 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: ```typescript 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: ```typescript 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: ```typescript 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('

Hello

'); // 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: ```typescript 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('

PDF 1

'), instance2.getA4PdfResultForHtmlString('

PDF 2

'), instance3.getA4PdfResultForHtmlString('

PDF 3

') ]); // 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: ```typescript async function safePdfGeneration() { let smartPdf: SmartPdf; try { smartPdf = await SmartPdf.create(); await smartPdf.start(); const pdf = await smartPdf.getA4PdfResultForHtmlString('

Hello

'); // 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: ```typescript 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 1. **Always start and stop**: Initialize with `start()` and cleanup with `stop()` to properly manage resources. 2. **Port management**: Use the automatic port allocation feature to avoid conflicts when running multiple instances. 3. **Error handling**: Always implement proper error handling as PDF generation can fail due to various reasons. 4. **Resource cleanup**: Ensure `stop()` is called even if an error occurs to prevent memory leaks. 5. **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](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.