Hey folks! I’m new to web development and I’m trying to set up a project using Polymer Starter Kit (PSK) with Node.js and Express. I’ve got the basic setup working, but I’m stuck on adding PDF generation functionality.
Here’s what I’ve done so far:
Set up a simple Express server to serve my PSK website.
The website loads fine on localhost:3000.
Now, I want to add a feature where users can click a button to generate a PDF of a webpage. I’m trying to use Puppeteer for this, but I’m running into issues.
I added a function to my PSK’s my-app.html file:
makePDF() {
// Puppeteer code here
}
But when I try to use Puppeteer, I get an error saying ‘require is not defined’.
Am I missing something? Do I need to move this code to the server-side? How can I trigger the PDF generation from a button click on the client-side?
I’ve actually worked on a similar project recently, and I can share some insights that might help you out.
You’re on the right track with moving the PDF generation to the server-side. Puppeteer is a Node.js library, so it can’t run directly in the browser. Here’s what you can do:
Keep your makePDF() function in the client-side code, but instead of running Puppeteer there, make an AJAX call to your server.
On the server, create an endpoint (e.g., /generate-pdf) that uses Puppeteer to generate the PDF.
When the PDF is generated, send it back to the client as a response.
This approach worked well for me. Just remember to handle errors and maybe add a loading indicator while the PDF is being generated. It can take a few seconds, especially for complex pages.
One more tip: If you’re generating PDFs of your own pages, consider using a headless Chrome instance on your server for better performance. It saved me a lot of headaches with styling inconsistencies between the browser and Puppeteer-generated PDFs.
yo dave, ive been there. puppeteer’s a server-side thing, so you gotta move that code to your express server. make an endpoint like /generate-pdf, use puppeteer there. then from your PSK, just hit that endpoint when the buttons clicked. itll work smoother that way, trust me. good luck man!
Based on my experience, the Puppeteer code needs to run on the server side. Instead of trying to execute it within the client’s context, create an Express route—say, ‘/generate-pdf’—and implement the PDF generation there using Puppeteer. Then, adjust your makePDF function on the client to send an AJAX request to this route. When the server responds with the PDF data, you can prompt a download or display the PDF as needed. Handling errors and providing feedback during the process will further improve the user experience.