Auto-Fit HTML to Single PDF Page – FitToPage.js

Auto-Fit HTML to Single PDF Page – FitToPage.js
Auto-Fit HTML to Single PDF Page – FitToPage.js
FitToPage.js is a lightweight JavaScript library that automatically adjusts HTML content to fit onto a single PDF page during printing.

It calculates the exact rendered dimensions of a target DOM element and injects dynamic CSS to adjust the print page size. This prevents awkward page breaks in long reports, invoices, or dashboards.

The library works directly within the browser’s native print system. You can trigger the standard print dialog (Cmd+P or Ctrl+P) to generate a PDF that matches the content’s exact height and width.

It preserves text selectability and searchability because it retains the original HTML structure rather than converting the page to an image.

Features:

  • Automatic content measurement: Calculates the pixel dimensions of your selected HTML element.
  • Dynamic @page CSS injection: Injects a print-specific CSS rule that defines a custom page size.
  • Native browser print integration: Works directly with Chrome, Firefox, and Safari’s built-in print dialog (Cmd+P or Ctrl+P).
  • Zero dependencies: Written in vanilla JavaScript with no external libraries required.
  • Lightweight package: The minified file is approximately 2 kilobytes.
  • Preserved text content: Outputs standard PDF text instead of converting content to an image.
  • Customizable margins and padding: Adds white space around your content in the final page layout.
  • Dynamic content support: Provides a remeasure() method for updating the page size after content changes.

Use Cases:

  • Digital Invoices: Generates receipts that extend vertically to fit all line items on a single continuous sheet.
  • Data Dashboards: Captures full-length analytics views without cutting off charts at the bottom of a standard A4 page.
  • Legal Contracts: Formats terms and conditions into a single scrollable PDF file for easy archiving.
  • Email Newsletters: Converts HTML email templates into a unified PDF proof for review.

How To Use It:

1. Install & download.

# NPM
$ npm install fit-to-page

2. Load the minified version of the FitToPage.js library in the document.

<!-- Local -->
<script src="fit-to-page.min.js"></script>

<!-- CDN -->
<script src="https://cdn.jsdelivr.net/npm/fit-to-page/fit-to-page.js"></script>

3. Initialize the library with the init method. This configuration measures your entire body element and sets the page size accordingly. When you press Cmd+P on Mac or Ctrl+P on Windows and save as PDF, your content appears on a single page.

// Initialize with defaults
FitToPage.init()

4. If your application loads data asynchronously, you must update the measurements after the DOM updates using the remeasure method.

FitToPage.init({ selector: '.dynamic-report' });
const loadButton = document.getElementById('load-data');
loadButton.addEventListener('click', async () => {
  await fetchData(); // Assume this function populates the DOM
  // Recalculate dimensions after content changes
  FitToPage.remeasure();
});

5. Available configuration options.

  • selector (string, default: ‘body’): CSS selector for the element you want to measure and fit to the page.
  • margin (number, default: 10): Page margin in millimeters applied to all sides of the PDF page.
  • padding (number, default: 5): Extra padding in millimeters added to the measured content dimensions to prevent edge clipping.
  • dpi (number, default: 96): Screen dots per inch value used for pixel to millimeter conversion calculations.
  • orientation (string, default: ‘auto’): Page orientation control accepting ‘auto’, ‘portrait’, or ‘landscape’ values.
  • debug (boolean, default: false): Enables display of a debug information overlay showing measured dimensions and calculated page size.
  • preventPageBreaks (boolean, default: true): Applies CSS rules to prevent content elements from breaking across page boundaries.
  • onReady (function, default: null): Callback function executed after measurement completes, receiving an object with width, height, and pageSize properties.
FitToPage.init({
  selector: 'body', 
  margin: 10,
  padding: 5,
  dpi: 96,
  orientation: 'auto', 
  debug: false, 
  preventPageBreaks: true,
  onReady: null 
})

Related Resources:

  • jsPDF: Client-side PDF generation library that creates documents programmatically from JavaScript without print dialogs.
  • Print.js: Library that simplifies printing of HTML, JSON, images, and PDFs with customizable styling and modal dialogs.
  • html2canvas: Converts HTML elements to canvas images that can be embedded in PDFs or downloaded separately.

FAQs:

Q: Can I use this for multi-page documents?
A: No, FitToPage.js specifically solves the single-page fitting problem.

Q: What happens if my content is too large?
A: The library calculates and applies whatever page size is needed to fit your content.

Q: Can I measure and fit only part of my page?
A: Yes, use the selector option to target a specific container element. The library measures only that element and its contents, ignoring everything else on the page.

Q: Does the content remain searchable in the PDF?
A: Yes. Since the library uses native browser printing rather than canvas rendering, all text remains selectable and searchable in the final PDF.

Q: Does this library create the PDF file?
A: No. FitToPage.js only adjusts the CSS page size. You use your browser’s native “Print to PDF” function to save the file.

The post Auto-Fit HTML to Single PDF Page – FitToPage.js appeared first on CSS Script.


Discover more from RSS Feeds Cloud

Subscribe to get the latest posts sent to your email.

Discover more from RSS Feeds Cloud

Subscribe now to keep reading and get access to the full archive.

Continue reading