Creating PDF files from elements using Puppeteer JS

In my quest to master the usage of Puppeteer within a Vue.js application, I am facing a challenge. I am able to create a PDF based on the entire page successfully, but I am struggling to generate a PDF for a specific element on the page. Is there a method or class that I overlooked which can help with this task? I have searched for a chainable function within the 'page' object to filter by selector(s) like so:

    const browser = await puppeteer.launch();
    const page = await browser.newPage();
    await page.goto('https://what.a.fancy/website', {waitUntil: 'networkidle2'});
    await page.$('.just-this-html').pdf(options);

I came across the page.$(selector) function, but I am unsure of how to properly chain it with a .then() call to convert the returned HTML into a PDF.

Your insights and guidance on this matter would be greatly appreciated!

Answer №1

Give this code a try: await page.setContent() page.setContent

Here's an example:

const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.goto('https://www.google.com/', {waitUntil: 'networkidle2'});
const dom = await page.$eval('div.jsb', (element) => {
     return element.innerHTML
}) // Retrieve DOM HTML content
await page.setContent(dom)   // Set the HTML markup to generate PDF
await page.pdf(options)

Answer №2

Just arrived at the puppeteer gathering fashionably late. But as they say, better late than never. Anyone stumbling upon this should definitely give this snippet a try to see if it serves any purpose. Here's the code adapted from previous responses:

const puppeteer = require('puppeteer');

(async () => {
   const browser = await puppeteer.launch() //defaults to true 
   const page = await browser.newPage()

 // Generate a PDF from your URL => make sure to replace the placeholder url with your own for it to work! 
 await page.goto('https://932db2cf7b.ngrok.io/chapter/lesson.php', {waitUntil: 'networkidle2'})

const items = await page.$eval('#doto', (element) => {
return element.innerHTML 
}) // Extract DOM elements

  await page.setContent(items) 

 await page.pdf({ path: 'pdf/aip.pdf', format: 'A4' })

 await browser.close()
 })()

This script converts elements within a div into a PDF file named aip stored in a folder called pdf.

I hope the comments provided prove to be useful

Happy coding!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

use ajax to dynamically append a dropdown menu

Currently working on creating a form that includes a dropdown menu populated with elements from a database. The challenge I'm facing is ensuring that once an element is selected from the dropdown, another one appears dynamically. My goal is to use AJA ...

javascript - The window.onload event is not firing

I am currently working on developing a tool that will allow users to export a PDF file. There are two scenarios to consider: The first scenario involves a straightforward process where the user clicks the export button, and a new blank window opens imm ...

Enhancing Chart Accessibility with Highcharts in VUE.js

We have a client requesting full-screen readability and keyboard navigation for their website (which is hosted on Squarespace and we created a Vue plugin for them). I have successfully implemented these features in all areas of their site, including Leafl ...

Want to learn how to display a description below a photo when you hover over it in a photo gallery?

I am currently creating a basic photo gallery where hovering over a thumbnail displays an enlarged photo below it. My goal is to also have text displayed inside a white text box when hovering over each thumbnail, with unique descriptions for each. I need ...

Jest is throwing an error: Unable to access property from undefined while trying to import from a custom

I developed a package called @package/test. It functions perfectly when imported into a new, empty React TypeScript application. However, issues arise within Jest test suites. The usage of the CommonJS package version causes Jest to throw an error: Test ...

The request's body in the PUT method is void

I seem to be having an issue with my PUT request. While all my other requests are functioning properly, the req.body appears to remain empty, causing this error message to occur: errmsg: "'$set' is empty. You must specify a field like so: ...

Having trouble getting images to display in Vue markdown?

I am currently utilizing the vue-markdown package for rendering markdown content. The package works fine except for images, which do not display as expected. Interestingly, when using an img element with the correct file path, the image shows up without an ...

The player clicks once and the game is played two times

Struggling with a coding issue here. I've got some code where you click on an image and if it can be moved to the next cell, it should move. function changecell(a){ var moved=false; if(a%3 !=0) { if(ij[a-1]==0) { moved=true; ...

Load Vue 3 components dynamically using a string-based approach

Exploring ways to dynamically load components based on a string input. Here is an attempt at achieving this: <component v-for="component in components" :is="eval(component)" /> However, this approach does not yield the desired r ...

What is the method for arranging objects in AngularJS using a custom sorting sequence?

I would like to display an array of object's properties in a custom sorted order. Here is the initial array: $scope.weekDays = [ { "day" : "TUESDAY", "count": 10 }, { ...

When the search button is clicked to find a specific address, the React Google Maps API fails to zoom in on

How can we modify this code to achieve the functionality where, upon clicking the search button, the map zooms in closer to the address entered by the user, similar to how it works on Google Maps? The goal is to replicate the search feature from the Goog ...

Ways to avoid scrolling on a fixed element

Here is the HTML setup I have... body .top .content The issue I am facing is that when scrolling reaches the end of the ul in the .top element, the background starts to scroll. This can be quite disorienting and makes the site slow on tablets. Even ...

Removing leading zeros from numeric strings in JSON data

I am facing an issue with my jQuery-based JavaScript code that is making an Ajax call to a PHP function. updatemarkers.xhr = $.post( ih.url("/AjaxSearch/map_markers/"), params).done( function(json) { <stuff> } The PHP function returns the follo ...

Tips for efficiently saving and updating data simultaneously using Laravel and Vue

I'm currently facing an issue that has left me stumped with no solution in sight. My app is built using PHP (Laravel) on the backend and VueJs on the frontend. While I've smoothly developed the entire application so far, I've now encountered ...

AngularJS is throwing an error because it is unable to access the property `$valid` on an undefined object

I am currently working on a web application using AngularJS and I have created the following form: <form name="form2" novalidate><multiselect class="input-xlarge" multiple="true" ng-model="selectedCar" options="c.name for c in cars" change="selec ...

Executing functions in beforeRouteEnter NProgress

When I attempt to call an API before navigating to a route, I encounter some issues. If I make the axios call inside beforeRouteEnter, everything works as expected: { beforeRouteEnter(routeTo, routeFrom, next) { NProgress.start() axios.get(' ...

Discover potential routes to nodes using JavaScript

I need assistance displaying all potential node paths in JavaScript: var object = {"metadata":{"record_count":5,"page_number":1,"records_per_page":5},"records":[{"name":"Kitchen","id":666,"parent_id":0,"children":null},{"name":"Jewellery","id":667,"pare ...

What is the best way to include additional text in a dropdown menu?

I'm trying to add the text "Choose Country" in a drop-down list before the user selects their country. example1 Here is the line of code I used: <option data-hidden="true"> Choose Country </option> However, the phrase does ...

Tips for passing a timestamp to a Postgresql DB using a Button in a Form instead of a traditional rails time_select box

I am currently developing a CAD App in Rails 4 with Ruby 2. The goal is to provide users with a button on the screen to log an on-scene time and clear scene time, especially since most users will be using touch screen computers. Instead of using the defaul ...

When a user clicks on an element, use jQuery to show a specific

I am looking to extract the Admission ID field within a separate function that triggers when a user clicks on a button. $(document).ready(function () { $.each(data.student, function (i, item){ trHTML += '<tr>'+ ...