NODE HELP

JsdomNPM (How It Works For Developers)

Published October 24, 2024
Share:

Introduction

When Jsdom and IronPDF are combined in Node.js, programmers have access to an extensive toolkit for creating and modifying PDF documents. A pure JavaScript implementation of the W3C DOM called Jsdom makes it possible to manipulate HTML and XML documents server-side in a manner akin to what is possible in a browser. Conversely, IronPDF uses simple Node.js APIs to make it easier to create high-quality PDFs from HTML content.

Combining Jsdom and IronPDF allows developers to easily transform web pages into PDFs within their Node.js apps, change pre-existing PDFs, and create PDF documents from HTML templates on the fly. This combination is a great option for projects requiring strong PDF creation capabilities because it not only ensures compliance with contemporary web technologies but also speeds up document generation operations.

What is Jsdom npm?

Jsdom npm (Node Package Manager) is a JavaScript library that lets you use Node.js to parse and work with HTML documents. It offers a browser-like environment inside Node.js and supports the W3C DOM (Document Object Model). As a result, you may manipulate the characteristics and content of HTML and XML documents programmatically. You can even simulate actions like clicks and form submissions.

JsdomNPM (How It Works For Developers): Figure 1

Jsdom is very helpful for activities like creating HTML-based reports, testing and verifying online sites, and web scraping. When working with HTML pages in a server-side setting, where standard browser functions are not available, it helps developers. The jsdom npm package bridges the gap between client-side browser functionality and server-side JavaScript by handling HTML manipulation and interaction in Node.js applications.

With its implementation of many web robust capabilities, Jsdom in Node.js is a useful tool for developers working in server-side environments with HTML and XML documents. Jsdom's salient characteristics are as follows:

W3C DOM Implementation

A comprehensive javascript implementation of many of the W3C DOM and HTML specifications is offered by Jsdom. This enables you to use well-known DOM APIs to programmatically manipulate HTML and XML documents.

Browser-like Environment

Because Jsdom imitates a browser environment within Node.js, you can manipulate HTML pages just like you would if JavaScript were being performed in a browser. This covers working with the document object model, managing events, execute scripts, and accessing and changing items.

Support for Standards

Modern web standards including HTML5, CSS3, and the newest JavaScript features are supported. This guarantees compatibility with the majority of web content and makes it possible to manipulate and parse complex pages accurately.

Parsing and Serialization

HTML strings can be parsed by Jsdom into DOM structures, and DOM nodes can be serialized back into HTML strings. This is to enable executing scripts inside the page and allow us to edit, and produce updated HTML output from web pages.

Customizable Configuration

Jsdom can be configured to mimic many browser-related features, including the processing of external resources (like loading external scripts and then execute external scripts or stylesheets), switching between different JavaScript engines (like V8 or SpiderMonkey), and more.

Integration with Testing Frameworks

Jsdom is a popular tool for writing unit tests and integration tests including DOM manipulation in testing frameworks like Jest and Mocha. It makes it possible to test web apps headless without needing a whole browser environment.

Accessibility and Compatibility

It is appropriate for applications that need to comply with accessibility standards since it has accessibility features like compatibility with screen readers and support for ARIA properties.

Node.js Ecosystem Integration

Jsdom works well with other libraries and the larger Node.js ecosystem. It can be used, for instance, in conjunction with packages like Puppeteer for more complex web scraping and automation activities or with Cheerio for effective HTML parsing.

Create and Config Jsdom Node.js

The steps below can be used to construct and configure Jsdom in a Node.js application:

Install Jsdom

First, make sure that npm and Node.js are installed on your computer. Npm can be used to install Jsdom:

npm install jsdom
npm install jsdom
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'npm install jsdom
VB   C#

Basic Jsdom Usage

This is a simple example of setting up a Jsdom environment and working with an HTML document:

const { JSDOM } = require('jsdom');
// Example HTML content
const htmlContent = `
<!DOCTYPE html>
<html>
<head>
  <title>Jsdom Example</title>
</head>
<body>
  <div id="content">
    <p>Hello, Jsdom!</p>
  </div>
</body>
</html>
`;
// Create a Jsdom instances
const dom = new JSDOM(htmlContent);
// Access and manipulate the DOM
const document = dom.window.document;
const contentDiv = document.getElementById('content');
contentDiv.innerHTML = '<p>Hello, modified Jsdom!</p>';
// Serialize the modified DOM back to HTML
const modifiedHtml = dom.serialize();
console.log(modifiedHtml);
const { JSDOM } = require('jsdom');
// Example HTML content
const htmlContent = `
<!DOCTYPE html>
<html>
<head>
  <title>Jsdom Example</title>
</head>
<body>
  <div id="content">
    <p>Hello, Jsdom!</p>
  </div>
</body>
</html>
`;
// Create a Jsdom instances
const dom = new JSDOM(htmlContent);
// Access and manipulate the DOM
const document = dom.window.document;
const contentDiv = document.getElementById('content');
contentDiv.innerHTML = '<p>Hello, modified Jsdom!</p>';
// Serialize the modified DOM back to HTML
const modifiedHtml = dom.serialize();
console.log(modifiedHtml);
'INSTANT VB TODO TASK: The following line could not be converted:
const
If True Then
	JSDOM } = require( 'jsdom');
' Example HTML content
'INSTANT VB TODO TASK: The following line contains an assignment within expression that was not extracted by Instant VB:
'ORIGINAL LINE: const htmlContent = ` <!DOCTYPE html> <html> <head> <title> Jsdom Example</title> </head> <body> <div id="content"> <p> Hello, Jsdom!</p> </div> </body> </html> `;
const htmlContent = ` <(Not DOCTYPE) html> (Of html) (Of head) (Of title) Jsdom Example</title> </head> (Of body) <div id="content"> (Of p) Hello, Jsdom!</p> </div> </body> </html> `
' Create a Jsdom instances
const dom = New JSDOM(htmlContent)
' Access and manipulate the DOM
const document = dom.window.document
const contentDiv = document.getElementById( 'content');
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'contentDiv.innerHTML = '<p> Hello, modified Jsdom!</p>'; const modifiedHtml = dom.serialize(); console.log(modifiedHtml);
VB   C#

JsdomNPM (How It Works For Developers): Figure 2

Configuration Options

The Jsdom constructor accepts options that you can supply to customize different parts of its functionality. These are a few typical setup choices:

It regulates how scripts and stylesheets from external resources should be loaded by Jsdom object API. Decide if the scripts in the parsed HTML should be executed by Jsdom. Allows scripts running inside of Jsdom to have their console output captured. Mimics the visual environment of a browser, which could have an impact on several CSS and layout calculations.

This is an illustration of setting up Jsdom code using options.

const { JSDOM } = require('jsdom');
const htmlContent = '<!DOCTYPE html><html><body><p>Hello, Jsdom!</p></body></html>';
const options = {
  resources: 'usable', // Load external resources (e.g., scripts, stylesheets)
  runScripts: 'dangerously', // Allow scripts to run
};
const dom = new JSDOM(htmlContent, options);
// Access the document and window objects
const document = dom.window.document;
const window = dom.window;
// Manipulate the DOM or interact with the window object here
console.log(document.documentElement.outerHTML); // Output the modified HTML
const { JSDOM } = require('jsdom');
const htmlContent = '<!DOCTYPE html><html><body><p>Hello, Jsdom!</p></body></html>';
const options = {
  resources: 'usable', // Load external resources (e.g., scripts, stylesheets)
  runScripts: 'dangerously', // Allow scripts to run
};
const dom = new JSDOM(htmlContent, options);
// Access the document and window objects
const document = dom.window.document;
const window = dom.window;
// Manipulate the DOM or interact with the window object here
console.log(document.documentElement.outerHTML); // Output the modified HTML
'INSTANT VB TODO TASK: The following line could not be converted:
const
If True Then
	JSDOM } = require( 'jsdom');
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'const htmlContent = '<!DOCTYPE html><html><body><p> Hello, Jsdom!</p></body></html>'; const options = { resources: 'usable', runScripts: 'dangerously'}; const dom = New JSDOM(htmlContent, options); const document = dom.window.document; const window = dom.window; console.log(document.documentElement.outerHTML); ' Output the modified HTML
VB   C#

Advanced Usage

In more complicated situations, such as connecting test code with testing frameworks or emulating user interactions, Jsdom can also be applied. Here's an illustration of how to use Jsdom and Jest for testing:

const { JSDOM } = require('jsdom');
test('modifying DOM with Jsdom', () => {
  const dom = new JSDOM('<!DOCTYPE html><html><body><p>Hello, Jsdom!</p></body></html>');
  const document = dom.window.document;
  const contentParagraph = document.querySelector('p');
  // Assert initial content
  expect(contentParagraph.textContent).toBe('Hello, Jsdom!');
  // Modify content
  contentParagraph.textContent = 'Hello, modified Jsdom!';
  // Assert modified content
  expect(contentParagraph.textContent).toBe('Hello, modified Jsdom!');
});
const { JSDOM } = require('jsdom');
test('modifying DOM with Jsdom', () => {
  const dom = new JSDOM('<!DOCTYPE html><html><body><p>Hello, Jsdom!</p></body></html>');
  const document = dom.window.document;
  const contentParagraph = document.querySelector('p');
  // Assert initial content
  expect(contentParagraph.textContent).toBe('Hello, Jsdom!');
  // Modify content
  contentParagraph.textContent = 'Hello, modified Jsdom!';
  // Assert modified content
  expect(contentParagraph.textContent).toBe('Hello, modified Jsdom!');
});
'INSTANT VB TODO TASK: The following line could not be converted:
const
If True Then
	JSDOM } = require( 'jsdom');
test( 'modifying DOM @with Jsdom', () =>
If True Then
	const dom = New JSDOM( '<!DOCTYPE html><html><body><p> Hello, Jsdom!</p></body></html>');
	const document = dom.window.document
	const contentParagraph = document.querySelector("p"c)
	expect(contentParagraph.textContent).toBe( 'Hello, Jsdom!');
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'	contentParagraph.textContent = 'Hello, modified Jsdom!'; expect(contentParagraph.textContent).toBe('Hello, modified Jsdom!'); });
VB   C#

Getting started

Getting IronPDF and Jsdom working in Node.js entails combining these libraries in order to convert HTML information into PDF documents. Jsdom lets you work with HTML documents using programming, while IronPDF makes it easier to convert HTML to PDF. Here's a how-to manual to get you going.

What is IronPDF?

A powerful library called IronPDF for Node.js is intended to produce PDF documents of superior quality from HTML text. While preserving the integrity of the original web content, it makes the process of converting HTML, CSS, and JavaScript into fully formatted PDFs easier. Web applications that need to generate dynamic, printable documents like reports, invoices, and certifications may find this tool especially helpful.

Among the many capabilities that IronPDF provides are adjustable page settings, headers, footers, and the ability to embed images and fonts. In order to guarantee that the generated PDFs adhere to the intended design, it allows intricate layouts and styles. Furthermore, IronPDF manages the execution of JavaScript inside HTML, enabling precise rendering of dynamic and interactive material.

JsdomNPM (How It Works For Developers): Figure 3

Features of IronPDF

PDF Generation from HTML

Convert JavaScript, HTML, and CSS to PDF. Supports media queries and responsive design, two contemporary web standards. Useful for dynamically decorating PDF documents, reports, and bills using HTML and CSS.

PDF Editing

Pre-existing PDFs can have text, photos, and other content added to them, or altenatively you can take text and pictures out of these PDF files. Combine numerous PDFs into one file. Divide PDF files into multiple separate papers. Include watermarks, annotations, headers, and footers.

Performance and Reliability

High performance and dependability are desired design qualities in industrial settings. IronPDF manages big document sets with ease.

Install IronPDF

Install the IronPDF package to get the tools you need to work with PDFs in node projects.

npm install @ironsoftware/ironpdf
npm install @ironsoftware/ironpdf
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'npm install @ironsoftware/ironpdf
VB   C#

Convert HTML to PDF using Jsdom and IronPDF

Get the HTML material ready to be converted to a PDF. As an illustration:

<!-- example.html -->
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Example Document</title>
  <style>
    body {
      font-family: Arial, sans-serif;
    }
    .content {
      margin: 20px;
    }
  </style>
</head>
<body>
  <div class="content">
    <h1>Hello, Jsdom with IronPDF!</h1>
    <p>This is a sample HTML document converted to PDF using Jsdom and IronPDF.</p>
  </div>
</body>
</html>
<!-- example.html -->
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Example Document</title>
  <style>
    body {
      font-family: Arial, sans-serif;
    }
    .content {
      margin: 20px;
    }
  </style>
</head>
<body>
  <div class="content">
    <h1>Hello, Jsdom with IronPDF!</h1>
    <p>This is a sample HTML document converted to PDF using Jsdom and IronPDF.</p>
  </div>
</body>
</html>
<(Not -)- example.html -- > <(Not DOCTYPE) html> <html lang="en"> <meta charset="UTF-8"> (Of title) Example Document</title> ReadOnly Property body() As (Of style)(Of head)
	  font-family: Arial, sans-serif
End Property
	.content
	If True Then
	  margin:
	  20px
	End If
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'  </style> </head> <body> <div class="content"> <h1> Hello, Jsdom @with IronPDF!</h1> <p> This is a sample HTML document converted @to PDF using Jsdom @and IronPDF.</p> </div> </body> </html>
VB   C#

Make a Node.js script called convertToPdf.js that parses the HTML content using Jsdom and creates a PDF using IronPDF.

const { JSDOM } = require('jsdom');
const IronPdf = require("@ironsoftware/ironpdf");
const document=IronPdf.PdfDocument;
var config=IronPdf.IronPdfGlobalConfig
config.setConfig({licenseKey:''});
const fs = require('fs');
// Load the HTML content from file
const htmlContent = fs.readFileSync('example.html', 'utf8');
// Create a Jsdom instance and parse the HTML
const dom = new JSDOM(htmlContent);
const jdocument = dom.window.document;
document.fromHtml(jdocument.documentElement.outerHTML).then((pdfres)=>{
    const filePath = `${Date.now()}.pdf`;
      pdfres.saveAs(filePath).then(()=>{
        console.log('PDF saved successfully!');
     }).catch((e)=>{
        console.log(e);
     });
    });
const { JSDOM } = require('jsdom');
const IronPdf = require("@ironsoftware/ironpdf");
const document=IronPdf.PdfDocument;
var config=IronPdf.IronPdfGlobalConfig
config.setConfig({licenseKey:''});
const fs = require('fs');
// Load the HTML content from file
const htmlContent = fs.readFileSync('example.html', 'utf8');
// Create a Jsdom instance and parse the HTML
const dom = new JSDOM(htmlContent);
const jdocument = dom.window.document;
document.fromHtml(jdocument.documentElement.outerHTML).then((pdfres)=>{
    const filePath = `${Date.now()}.pdf`;
      pdfres.saveAs(filePath).then(()=>{
        console.log('PDF saved successfully!');
     }).catch((e)=>{
        console.log(e);
     });
    });
'INSTANT VB TODO TASK: The following line could not be converted:
const
If True Then
	JSDOM } = require( 'jsdom');
const IronPdf = require("@ironsoftware/ironpdf")
const document=IronPdf.PdfDocument
Dim config=IronPdf.IronPdfGlobalConfig config.setConfig({licenseKey: ''});
const fs = require( 'fs');
' Load the HTML content from file
const htmlContent = fs.readFileSync( 'example.html', 'utf8');
' Create a Jsdom instance and parse the HTML
const dom = New JSDOM(htmlContent)
const jdocument = dom.window.document
'INSTANT VB TODO TASK: Local functions are not converted by Instant VB:
'document.fromHtml(jdocument.documentElement.outerHTML).@then((pdfres)=>
'{
'	const filePath = `$
'	{
'		@Date.now()
'	}
'	.pdf`;
'	pdfres.saveAs(filePath).@then(()=>
VB   C#

JsdomNPM (How It Works For Developers): Figure 4

Load HTML content from a database, file, or dynamically created content. To create a PDF document from the parsed HTML content, use IronPDF. The HTML string is accepted by IronPDF's RenderHtmlAsPdf function, which then delivers a Promise with the PDF data. Using the file system module (fs) of Node.js, IronPDF creates the PDF document as a buffer (pdfBuffer), which may be saved to a file. Error handling guarantees resilience in the event of problems, like corrupted HTML or network difficulties, during the creation of PDFs.

JsdomNPM (How It Works For Developers): Figure 5

Conclusion

For programmatically creating high-quality PDF documents from HTML information, Jsdom offers a reliable option. With Jsdom, developers may interact with DOM elements and dynamically edit information by making it easier to parse and manipulate HTML pages in a simulated browser environment. This feature is essential for jobs like data extraction, dynamic report generation, and web scraping.

With its robust capabilities for turning HTML texts into PDFs that give you exact control over layout, pagination, headers, footers, and other PDF-specific features, IronPDF is a great addition to Jsdom. It makes it easier to convert complicated HTML structures from Node.js apps directly into printable, prepared PDF files.

Combining Jsdom and IronPDF allows developers to create PDF documents from HTML templates or dynamically generated information automatically. This makes the documents useful for a variety of use cases, such as producing reports, certificates, invoices, and more. This integration efficiently meets the unique requirements of document-centric applications inside the Node.js ecosystem by utilizing the strengths of both libraries to improve productivity and preserve document fidelity.

IronPDF and Iron Software enable you to extend the capabilities of your. NET development toolkit with OCR, barcode scanning, PDF creation, Excel integration, and other features. IronPDF combines IronSoftware's highly configurable systems and suite with its core support to provide developers with additional online apps and features, as well as more efficient development, all for only $749 for the base edition.

When license options are clear and tailored to the project, developers may select the optimal model with greater ease. These features assist developers in solving a wide range of issues in a straightforward, effective, and well-integrated manner.

< PREVIOUS
sockjs NPM (How It Works For Developers)
NEXT >
Hashids NPM (How It Works For Developers)

Ready to get started? Version: 2024.11 just released

Free npm Install View Licenses >