What’s actually slowing this PC down?
Pick the symptom - the matching free tool is one click away.
Use Puppeteer’s page.addScriptTag({ url: scriptUrl }) to insert a remotely hosted JavaScript file into the current page, wait for your application to finish rendering, then call page.pdf(). For a real site that already includes the file, navigate to the page instead of injecting it a second time. The complete pattern below covers asynchronous content, print CSS, security boundaries, failures and production details.
Minimal working example
Install Puppeteer in your Node.js project:
npm install puppeteer
This ES-module example creates a document, loads JavaScript from a URL, waits for an application-owned readiness flag and writes an A4 PDF:
import puppeteer from 'puppeteer';
const scriptUrl = 'https://example.com/app.js';
const browser = await puppeteer.launch();
try {
const page = await browser.newPage();
await page.setContent(`
<!doctype html>
<html>
<head><meta charset="utf-8"><title>Report</title></head>
<body><main id="app"></main></body>
</html>
`);
await page.addScriptTag({ url: scriptUrl });
// app.js must set this after it has finished updating the DOM.
await page.waitForFunction(() => window.pdfContentReady === true, {
timeout: 30_000
});
await page.pdf({
path: 'output.pdf',
format: 'A4',
printBackground: true
});
} finally {
await browser.close();
}
addScriptTag() returns a promise for the injected <script> element. The URL is fetched in the page or frame where the method is called. Replace the example URL and readiness contract with values owned by your application; Puppeteer does not create window.pdfContentReady for you.
Choose the correct loading approach
Inject a script into HTML you construct
Use page.setContent() followed by page.addScriptTag({ url }) when Node.js is assembling a document shell and the remote file supplies the rendering logic. The script can create markup, fetch data and set the readiness flag.
#1 Best Overall
- Read Before You Buy — No Video Output: These adapters support charging and USB 2.0 data transfer, but cannot transmit video signals. Except for standard USB webcams (which use USB data only), they are not compatible with HDMI/DisplayPort cables, video-capable USB-C hubs, or docking stations with video output.
- Convert USB-A Ports to USB-C: Designed to connect USB-C earphones, cables, flash drives, card readers, and other USB-C accessories to standard USB-A ports. Plug-and-play with no drivers or software required.
- Aluminum Alloy Housing: Built with a sturdy aluminum alloy shell that aids in heat dissipation and protects against daily wear and scratches. Designed to maintain a stable and secure connection.
- Compact & Travel-Friendly: The ultra-compact design allows the adapter to stay plugged into your device without blocking adjacent ports or adding bulk, reducing wear and tear on your original USB ports.
- 12-Month Warranty: Backed by a 12-month manufacturer warranty for peace of mind. Designed to meet strict quality control standards for reliable everyday performance.
Navigate to a page that already includes the script
If the source is a normal web page, let its HTML load the script:
await page.goto('https://example.com/report', {
waitUntil: 'networkidle2'
});
await page.waitForSelector('#report-ready');
await page.pdf({ path: 'report.pdf', format: 'A4' });
networkidle2 only describes network activity. Polling, delayed timers, charts or client-side API work can continue afterward, so also wait for a selector, global flag or other application-owned condition that means the PDF content is complete. Do not inject the same file again when the page already loaded it.
Script options
The script-tag API also supports inline content, a local path and a type such as module. A relative path is resolved from Node’s current working directory. Use the API reference matching your installed Puppeteer version for exact option names and behavior.
Wait for rendered content before printing
Loading a script tag only confirms that the tag was added and its load operation completed; it is not proof that the script’s asynchronous work is finished. Define a deterministic signal in application code:
Quick wins for a faster PC:
Fix the driver behind crashes, sound loss and screen glitchesFind Drivers →Clear out junk files and repair common Windows errorsFree Scan →Scan for outdated or missing drivers - takes under a minuteDriver Scan →// app.js
(async () => {
const response = await fetch('/api/report');
const report = await response.json();
document.querySelector('#app').textContent = report.title;
window.pdfContentReady = true;
})();
Then wait for that signal, or for a visible element whose presence means rendering is complete:
Rank #2
- 5-in-1 USB-C Hub: Experience comprehensive connectivity featuring a Power Delivery input, two USB-A 2.0 ports, a USB-A 3.0 port, and an HDMI port. (Note: The USB-C power delivery input port is only for connecting an external wall charger to power your laptop and cannot power peripheral devices.)
- 90W Pass-Through Charging: Achieve optimal charging with 90W pass-through power to your laptop, supported by a total input of 100W, with the hub reserving 10W for operational efficiency. (Note: Wall charger not included.)
- Quick Data Transfers: Accelerate your productivity with rapid data transfers using a high-speed 5Gbps USB 3.0 port and two 480Mbps USB 2.0 ports.
- 4K HDMI Display: Enhance your visual experience with a hub capable of delivering 4K resolution at 30Hz in both mirror and extend modes. Please note that this hub is compatible with MacBook (macOS 12 and newer), Windows 10 and 11, ChromeOS, and laptops equipped with DP Alt Mode and Power Delivery. Note: This device is not compatible with Linux.
- What You Get: Anker USB-C Hub (5-in-1, 4K HDMI), welcome guide, 18-month warranty, and our friendly customer service.
await page.waitForFunction(() => window.pdfContentReady === true);
// or: await page.waitForSelector('[data-pdf-ready]');
Puppeteer’s PDF guide documents waiting for fonts as part of PDF generation. That does not guarantee completion of arbitrary JavaScript, API calls, images or charts, so keep the application-level wait.
Control print CSS, colors and page layout
page.pdf() uses print media by default. That means @media print rules apply even if the page looked correct on screen. If the document is designed for screen media, select it before printing:
await page.emulateMediaType('screen');
await page.pdf({
path: 'screen-styled.pdf',
format: 'A4',
printBackground: true,
margin: { top: '16mm', right: '14mm', bottom: '16mm', left: '14mm' }
});
Use print media for a publication-style document and screen media when the screen layout is intentional. Check page breaks, overflow, backgrounds and font availability in the resulting file. Chromium adjusts colors for printing by default; when exact colors matter, CSS such as -webkit-print-color-adjust: exact can preserve them, subject to browser behavior.
Crashes, No Sound, or Screen Glitches?
Random freezes, missing sound and display glitches usually trace back to one bad driver. Find and replace yours safely.Free scan · under a minuteWindows Errors? Fix Them Before They Spread
Repair common Windows errors and clear accumulated junk for a smoother, more stable PC - no reinstall needed.Free scan · no reinstallOther useful PDF options include paper format, landscape orientation, margins, a path or returned buffer, page ranges and background printing. Keep the output decision explicit:
const pdfBuffer = await page.pdf({
format: 'Letter',
landscape: false,
pageRanges: '1-3',
printBackground: true
});
Security: a URL is executable code
A remote script URL is not merely an asset location. The browser executes whatever code that URL serves, with the page’s privileges. Puppeteer’s security policy states: “Puppeteer provides powerful capabilities for browser installation, automation, and inspection, and it is the responsibility of the calling code to ensure these are used safely and as intended.”
Rank #3
- Sleek 7-in-1 USB-C Hub: Features an HDMI port, two USB-A 3.0 ports, and a USB-C data port, each providing 5Gbps transfer speeds. It also includes a USB-C PD input port for charging up to 100W and dual SD and TF card slots, all in a compact design.
- Flawless 4K@60Hz Video with HDMI: Delivers exceptional clarity and smoothness with its 4K@60Hz HDMI port, making it ideal for high-definition presentations and entertainment. (Note: Only the HDMI port supports video projection; the USB-C port is for data transfer only.)
- Double Up on Efficiency: The two USB-A 3.0 ports and a USB-C port support a fast 5Gbps data rate, significantly boosting your transfer speeds and improving productivity.
- Fast and Reliable 85W Charging: Offers high-capacity, speedy charging for laptops up to 85W, so you spend less time tethered to an outlet and more time being productive.
- What You Get: Anker USB-C Hub (7-in-1), welcome guide, 18-month warranty, and our friendly customer service.
- Do not accept arbitrary script URLs from untrusted users.
- Allow only approved HTTPS hosts and schemes; validate redirects as well as the initial URL.
- Keep API keys, cookies and internal service credentials out of the page unless the render explicitly needs them.
- Run rendering in an isolated worker or container and restrict outbound network access at the infrastructure layer.
- Set request interception to inspect or abort unwanted resource requests when appropriate. Treat it as a control, not a complete defense against hostile pages or redirects.
- Do not copy
--no-sandboxinto production without reviewing the Chromium, Puppeteer and hosting-environment requirements.
If users control both the page URL and the script URL, assume the renderer can reach destinations you did not intend, consume excessive resources or attempt to exfiltrate data. Separate rendering credentials from application credentials and impose time, memory and network limits.
Version and compatibility checks
The official PDF guide is published for Puppeteer 25.12.0, while the addScriptTag and script-options references surfaced for 25.10.0. This does not establish a behavioral conflict, but examples should be checked against the version installed by your project. Pin Puppeteer, use a compatible Chromium revision and read the matching documentation:
- Puppeteer PDF generation guide
- Page.addScriptTag() API
- FrameAddScriptTagOptions
- Page.pdf() API
- PDFOptions reference
Troubleshooting
“Could not load script” or a rejected promise
Verify the URL from the renderer’s network environment, confirm HTTPS and certificate validity, and check redirects, DNS and the remote server’s response. If the host blocks headless browsers, use a permitted deployment or an approved first-party bundle rather than silently disabling security checks.
The PDF is blank
The script may have failed, rendered into a different frame, or printed before asynchronous work completed. Log page console and page errors, inspect the DOM before calling pdf(), and wait for an application-owned selector or flag.
page.on('console', message => console.log('[browser]', message.text()));
page.on('pageerror', error => console.error('[page error]', error));
Content is cut off or appears on the wrong pages
Inspect print-specific CSS, fixed heights and overflow rules. Try format: 'A4' or 'Letter', explicit margins, and print-only page-break rules. If the design is screen-first, call emulateMediaType('screen') before printing.
Rank #4
- Dual Converters, Infinite Potential:Includes 2× USB C male to USB A female adapters and 2× USB A male to USB C female adapters. Perfect for a wide range of uses—tablets with Bluetooth keyboards, expand USB ports on macbook, and more. Two different converters for all your daily needs
- Next-Level 10Gbps & 3A Charging: No more slow 480Mbps, this usb to usb c adapter has a transfer speed of up to 10Gbps, allowing you to do more transferring in less time. This usb adapter fits both USB A and USB C charger, supporting up to 3A fast charging
- Upgraded Exquisite Craftsmanship: With an aluminum alloy housing and metal connector, the usbc to usb adapter is extremely durable and sturdy. Rigorously tested to withstand more than 10,000 times of plugging and unplugging, ensuring long-lasting performance
- Broad Compatible: The usb c to usb adapter widely supports all USB C/ USB A devices like laptops, tablets, cellphones, car chargers, and phone chargers. Such as compatible with MacBook Pro/Air 2023/2022, Thunderbolt 4/3 Devices,Apple MagSafe Watch 9/8/7/SE/Ultra, iPad Pro 2022/2021, Samsung Galaxy S23/S20/S10, and iPhone 17/16/15 Pro. Plug and play
- Please Note: To reach 10Gbps speed, keep the cable under 3.3 ft. For USB A Male to USB C adapters, try flipping the USB C connector. USB C Male to USB A adapters support bidirectional 10Gbps transfer within 3.3 ft
Fonts or icons are missing
Ensure font requests are reachable from the browser and wait for the page’s font and content conditions. Puppeteer’s documented PDF flow waits for fonts, but external icon scripts and application assets still need their own readiness logic.
Recommended Free Tools
The process hangs
Give navigation and readiness waits finite timeouts, close pages and browsers in finally, and investigate scripts that keep polling or open connections. A network-idle event is not a substitute for a business-level completion signal.
Reliability and cost considerations
For repeatable output, pin the browser dependency, keep HTML and script versions compatible, use a stable readiness contract and record the URL, commit or release identifier and PDF options for each job. Retry transient navigation failures with a limit, but do not retry unsafe or deterministic script errors indefinitely. Rendering consumes CPU and memory per browser page; queue concurrent jobs according to the capacity of your deployment and enforce a maximum document size and execution time.
Puppeteer itself does not establish a universal hosted-rendering price or performance comparison with other libraries. Choose a self-hosted browser when you need control over code, network and credentials; choose a managed endpoint when operating Chromium is the larger burden, after checking that provider’s security and data-handling terms.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Or skip the browser setup
ScreenshotNeo is a website screenshot API and MCP server. A single request can return PNG, JPEG, WebP or a PDF, so you do not need to install or maintain Puppeteer for a basic URL capture. Cookie and consent banners, newsletter popups and chat widgets are removed before the shot; bot checks, blank pages, timeouts, failed loads and cache hits are not billed, and response headers identify the page verdict and billing status. Its MCP server provides take_screenshot, get_page_info and capture_pdf tools for Claude, Cursor and other MCP clients.
Free tools Windows power users keep installed
One-click scans. No signup required.
See the complete parameter list in the ScreenshotNeo documentation. The same endpoint accepts options for full-page lazy-image capture, CSS-selector elements, dark mode, device presets or custom viewports, retina scale, PDF paper and margins, custom CSS or JavaScript, clicks, waits, blocked requests, headers, cookies, user agents, Authorization, timezone, geolocation, transparent backgrounds, resizing, chosen cache TTLs, signed image links, asynchronous webhooks, bulk capture of up to 100 URLs per call and usage reporting.
Best Value
- 5-in-1 Connectivity: Equipped with a 4K HDMI port, a 5 Gbps USB-C data port, two 5 Gbps USB-A ports, and a USB C 100W PD-IN port. Note: The USB C 100W PD-IN port supports only charging and does not support data transfer devices such as headphones or speakers.
- Powerful Pass-Through Charging: Supports up to 85W pass-through charging so you can power up your laptop while you use the hub. Note: Pass-through charging requires a charger (not included). Note: To achieve full power for iPad, we recommend using a 45W wall charger.
- Transfer Files in Seconds: Move files to and from your laptop at speeds of up to 5 Gbps via the USB-C and USB-A data ports. Note: The USB C 5Gbps Data port does not support video output.
- HD Display: Connect to the HDMI port to stream or mirror content to an external monitor in resolutions of up to 4K@30Hz. Note: The USB-C ports do not support video output.
- What You Get: Anker 332 USB-C Hub (5-in-1), welcome guide, our worry-free 18-month warranty, and friendly customer service.
Node.js
const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);
const buffer = Buffer.from(await res.arrayBuffer());
await import('node:fs/promises').then(fs => fs.writeFile('shot.webp', buffer));
cURL
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
Python
import requests
r = requests.get("https://api.screenshotneo.com/v1/shot", params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"}, timeout=90)
open("shot.webp", "wb").write(r.content)
The Free plan includes 1,000 shots each month without a card. Paid plans start at $5 for 3,000 shots; every feature is included on every plan, and yearly billing gives two months free. Create a free ScreenshotNeo account to get started.
FAQ
Can I use a JavaScript module loaded from a URL?
Yes. Pass type: 'module' with the script options and still wait for an application-owned readiness signal before printing.
Does page.pdf() use screen styles?
No. Print media is the default. Call page.emulateMediaType('screen') first when the PDF must use screen CSS.
Should I inject a script into every frame?
No. addScriptTag() applies to the current page or frame context. Inject only where the application needs it, and avoid duplicating a script already included by the navigated document.
Frequently Asked Questions
Can I use a JavaScript module loaded from a URL?
Yes. Pass type: 'module' with the script options and still wait for an application-owned readiness signal before printing.
Does page.pdf() use screen styles?
No. Print media is the default. Call page.emulateMediaType('screen') first when the PDF must use screen CSS.
Should I inject a script into every frame?
No. addScriptTag() applies to the current page or frame context. Inject only where the application needs it, and avoid duplicating a script already included by the navigated document.
The Tool Desk
Outbyte PC Repair FREERepair Windows errors before they cause bigger problemsFix Now →Outbyte Driver Updater FREEScan for outdated or missing drivers - takes under a minuteDriver Scan →Quick Recap
Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

