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 →If your HTML and JavaScript begin as a string, render that string in a real headless browser, wait for the application’s own ready signal, and then print the page. In Puppeteer the sequence is page.setContent(html), a readiness wait such as page.waitForSelector(), and page.pdf(). Playwright provides the equivalent page.setContent() and page.pdf() APIs. A generic load or network-idle event is not proof that data-driven JavaScript has finished.
Why a browser is required
PDF converters that only parse HTML do not execute browser JavaScript reliably. A headless Chromium browser does: it creates a document, runs inline and external scripts, performs fetches, lays out the resulting DOM, loads fonts and images, and prints the rendered page. The important distinction is timing. Calling the PDF method immediately after assigning the string can capture an empty chart, loading spinner, or pre-render template.
Puppeteer’s setContent API accepts markup as a string. Its PDF guide demonstrates printing a page and closing the browser afterward. Playwright documents the same methods in its Page API; its setContent implementation internally calls document.write(), so the supplied string becomes the page document.
Puppeteer: complete working example
Install Puppeteer in a Node.js project, then put the HTML and JavaScript in one string. This example deliberately exposes a #report-ready element only after asynchronous rendering has completed.
Quick wins for a faster PC:
Clear out junk files and repair common Windows errorsFree Scan →Fix the driver behind crashes, sound loss and screen glitchesFind Drivers →Repair Windows errors before they cause bigger problemsFix Now →#1 Best Overall
- RCA Female to HDMI Video Converters Adapter : The cable is used to convert analog composite input to HDMI 1080p output, displayed on a 1080p HD TV/TV/monitor.
- Input ports: 1xRCA Female (Yellow, White, Red), Output ports: 1xHDMI 1.3 1080p. NOT support 3D and 4K, NOT support HDMI Converts to AV
- AV to HDMI Converter: Plug and Play, Easy to Install and Operate, Powered by External USB Cable. Note: Please hook up the USB power cable (included) to 5V 1Apower source during use (not included power supply ).
- Support PAL, NTSC3.58, NTSC4.43, SECAM, PAL/M, PAL/N standard TV formats input. For PS2,PS3,Xbox,N64,STB, VHS, VCR, DVD Players and other devices with standard composite AV input.
- You Will Get : 1x RCA Female TO HDMI Converter, 1xHDMI cable, 1xUSB cable, 1xUser Manual. ONE YEAR WARRANTY - if you are not satisfied for any reason whatsoever, do not hesitate to contact us .
npm install puppeteer
const puppeteer = require('puppeteer');
const html = `
String to PDF
Monthly report
Loading…
Ready
`;
(async () => {
const browser = await puppeteer.launch();
try {
const page = await browser.newPage();
await page.setContent(html, { waitUntil: 'load' });
await page.waitForSelector('#report-ready', { visible: true, timeout: 30000 });
await page.pdf({
path: 'output.pdf',
format: 'A4',
printBackground: true,
preferCSSPageSize: true
});
} finally {
await browser.close();
}
})();
The waitUntil: 'load' option covers the document’s initial load lifecycle. The selector wait is the application-specific gate: it prevents printing until the script has changed the page. The selector and delay are illustrative; use a condition that your application controls.
Return PDF bytes instead of writing a file
Remove path and retain the returned buffer. You can send it from an HTTP response or store it in object storage.
const pdfBuffer = await page.pdf({
format: 'A4',
printBackground: true,
preferCSSPageSize: true
});
// Express example: res.type('application/pdf').send(pdfBuffer);
When the JavaScript is a separate string
If you receive HTML and JavaScript separately, insert the script before calling setContent. Escaping the closing script sequence is important when untrusted text could contain </script>.
function makeDocument(markup, script) {
const safeScript = script.replaceAll('</script>', '<\/script>');
return `${markup}<script>${safeScript}</script>`;
}
const html = makeDocument(
'<!doctype html><main id="app"></main>',
`document.querySelector('#app').textContent = 'Rendered';`
);
await page.setContent(html, { waitUntil: 'load' });
Puppeteer also exposes an addScriptTag method that supports script content. Confirm the exact overload in the version you install using the current Page API index, because the focused method page is version-sensitive.
Rank #2
- RCA to HDMI Converter: Converts analog RCA composite (Yellow, White, Red) input to HDMI 720P/1080P (60HZ) output,displayed on HDTV/Monitor,which can bring back your childhood memories.
- Plug to Play: ABLEWE Mini RCA to HDMI converter no extra drivers need, just plug and play,easy to use.Please hook up the USB power cable (included) to 5V power source during use.
- Wide Compatibility: Support source formats of PAL, NTSC3.58, NTSC4.43, SECAM, PAL/M, PAL/N standard TV. Provide advanced signal processing with great precision, colors, resolutions, and details.
- Widely Used:Widely applied to PS2,PS3,Xbox,N64, WII, STB, VHS, VCR, DVD Players and other devices with standard composite AV input.
- Attention & Package:Please ensure to connect this rca to hdmi converter to power source to make it work.Package include:1*RCA to HDMI Converter,1*usb power cable(adapter not included),1*User Manual.
Playwright equivalent
Playwright is a suitable alternative when it already matches your automation stack. Its PDF output uses print CSS media by default.
npm install playwright
const { chromium } = require('playwright');
const html = `<!doctype html>
<style>@page { size: Letter; margin: 16mm } body { font-family: sans-serif }</style>
<h1 id="title">Loading</h1>
<script>
setTimeout(() => {
document.querySelector('#title').textContent = 'Finished';
document.body.dataset.ready = 'true';
}, 200);
</script>`;
(async () => {
const browser = await chromium.launch();
try {
const page = await browser.newPage();
await page.setContent(html, { waitUntil: 'load' });
await page.waitForFunction(() => document.body.dataset.ready === 'true');
const pdf = await page.pdf({ format: 'Letter', printBackground: true });
require('fs').writeFileSync('output.pdf', pdf);
} finally {
await browser.close();
}
})();
Playwright lists load, domcontentloaded, networkidle and commit as wait options, but its documentation discourages using networkidle as a readiness test. Applications can keep analytics, websockets or polling requests open, and a quiet network does not prove that a chart or table has been painted. Prefer a selector, a data attribute, a count assertion, or an application promise.
Choose a readiness signal that means “printable”
Known DOM marker
Set hidden = false or add data-ready="true" only after all required content is present. Wait for that marker with waitForSelector or waitForFunction.
Application promise
For code you control, expose a promise on window and await it from the page:
Rank #3
- Composite to HDMI Converter: Converts analog AV composite (Yellow, White, Red) input to HDMI 720P/1080P (60HZ) output, displayed on smart TV, Projector or HD Display, which bring back your old and cherish memories.
- Plug to Play: This HDMI Converter no extra drivers need, just plug and play,easy to use. Please hook up the USB Power Cable (included) to 5V power source during use. Note: The Video Converters only support converts AV to HDMI, can't converts HDMI to AV.
- Widely Used: This composite to hdmi adapter is widely applied to PS1, PS2, PS3, Xbox, N64, Wii, STB, VHS, VCR, DVD Players and other devices with standard composite AV input. Note: It can only be used when PS2 is set to RGB output.
- Wide Compatibility: This Video Audio Converter Adapter supports source formats of PAL, NTSC3.58, NTSC4.43, SECAM, PAL/M, PAL/N standard TV. Provide advanced signal processing with great precision, colors, resolutions, and details. Important Note: This converter can't improve video quality!
- Attention & Package: Please ensure to connect this av hdmi converter to power source to make it work. Package include: 1*AV to HDMI Adaptor, 1*USB Power Cable(adapter not included), 1*User Manual.
await page.waitForFunction(() => window.reportReady === true, { timeout: 30000 });
Assign window.reportReady = true after data fetching, chart rendering and image preparation finish.
Fonts and images
Puppeteer’s PDF method waits for fonts by default. Explicitly wait for critical images when their dimensions affect pagination:
await page.waitForFunction(() => [...document.images].every(img => img.complete));
This checks completion, not whether an image loaded successfully; inspect img.naturalWidth if a missing image should fail the job.
Control print appearance
Both libraries print with print CSS media by default. Put page size, margins and print-only rules in @page and @media print. Puppeteer can instead use screen rules with:
Rank #4
- Convert RCA to HDMI Instantly – BD&M RCA to HDMI Converter easily converts analog RCA/composite AV signals to HDMI output, allowing you to connect older devices to modern HDTVs, monitors, and projectors with clear video and audio quality.
- Wide Device Compatibility – Supports VHS players, VCRs, DVD players, camcorders, retro gaming consoles, and more including PS1, PS2, PS3, Xbox, N64, Wii, and older AV devices with standard RCA output.
- 1080P HDMI Output – Advanced signal processing delivers stable and sharp video output with support for 720P/1080P HDMI resolution, improving compatibility with modern TVs and displays.
- Plug & Play Setup – No drivers or software required. Simply connect the RCA cables, HDMI cable, and included USB power cable for quick and easy installation in minutes.
- Compact & Reliable Design – Lightweight mini converter design makes it perfect for home entertainment setups, retro gaming, travel, or converting old media collections while maintaining stable performance.
await page.emulateMediaType('screen');
await page.pdf({ path: 'screen-styled.pdf', printBackground: true });
Browsers modify colors for printing by default. If exact colors matter, add -webkit-print-color-adjust: exact to the relevant elements, while recognizing that color output still depends on the browser and printer/PDF viewer.
Handling external resources and security
- Relative URLs: a string document has no useful site origin for many relative links. Use absolute URLs for images, stylesheets and fetch endpoints, or provide a suitable base URL in the markup.
- CORS and authentication: browser fetches still obey web security rules. Pass data into the string, host resources with appropriate CORS headers, or configure request interception and headers deliberately.
- Untrusted HTML: JavaScript in the string executes with the browser’s privileges. Sanitize untrusted markup, isolate the browser process, restrict outbound access and never inject secrets into page-visible code.
- Long-running scripts: a script that never resolves will leave your readiness wait pending. Set explicit timeouts and fail with a useful diagnostic.
Troubleshooting checklist
| Symptom | Likely cause | Fix |
|---|---|---|
| PDF shows “Loading…” | Printed before asynchronous code finished | Wait for an app-specific selector, attribute or promise. |
waitForSelector times out |
The script threw, the selector is wrong, or a request failed | Listen for page errors, log console messages, verify the selector in DevTools, and inspect failed requests. |
| Styles or images are missing | Relative URLs, blocked requests or CORS | Use absolute URLs, check response status, and provide the required headers or cookies. |
| Colors differ from the browser | Print media and print color adjustment | Use print-specific CSS, printBackground: true, or emulate screen media when appropriate. |
| Pages break unexpectedly | Content changes after printing or CSS page rules are absent | Wait for final layout, define @page, and use page-break CSS deliberately. |
| Browser process hangs | Unclosed browser, infinite page work or excessive resources | Close in finally, enforce navigation/readiness timeouts and cancel work that cannot complete. |
Reliability, performance and cost decisions
The supplied API documentation does not establish a performance or reliability ranking between Puppeteer and Playwright. Choose the library already used by your team, then measure your own templates. Reuse a browser process for a batch of jobs, create an isolated page per document, cap concurrency, and close pages after each job. Waiting for a precise readiness signal avoids both premature PDFs and unnecessarily long fixed delays.
For repeatable output, pin the library and browser versions, include fonts and critical assets under your control, set timeouts, capture console and request failures, and retain the input or a safe diagnostic identifier when a conversion fails. These practices make a failed PDF explainable without claiming that any particular browser version guarantees identical output.
Or skip the browser setup
If the page already exists at a public URL, ScreenshotNeo provides a hosted capture API and an MCP server for AI agents. It accepts cookie or consent banners before capture and removes more than 60 known consent platforms, newsletter popups and chat widgets; each step can be disabled. Only clean shots are billed: bot checks or CAPTCHAs, blank pages, timeouts, failed loads and cache hits cost nothing, and response headers identify the page verdict and billing status.
Do these 3 things before closing this tab:
1Fix the driver behind crashes, sound loss and screen glitches2Clear out junk files and repair common Windows errors3Scan for outdated or missing drivers - takes under a minuteFor a direct request, see the ScreenshotNeo API documentation:
Best Value
- Export or Convert Text, HTML, PNG, JPG, or Camera Pictures to PDFs
- Unlimited use
- No ads
- No personal data taken
- GDPR compliant
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
The service also has take_screenshot, get_page_info and capture_pdf tools for Claude, Cursor and other MCP clients. Plans include 1,000 shots per month free with no card; paid plans start at $5 for 3,000 shots. Every feature is on every plan. Sign up free to try it.
Reference APIs
- Puppeteer Page.setContent
- Puppeteer PDF generation guide
- Playwright Page API
- Puppeteer Page.pdf API
- Puppeteer Page API method index
Frequently Asked Questions
Can I convert the string with a non-browser PDF library?
Only if that library explicitly executes the JavaScript your document needs. For general browser-compatible scripts, use Puppeteer or Playwright so the same rendering engine runs before printing.
Should I always wait for networkidle?
No. Network-idle does not prove that application rendering is complete and can remain pending because of analytics or polling. Wait for a condition your application sets when required content is ready.
What’s actually slowing this PC down?
Pick the symptom - the matching free tool is one click away.
What does page.pdf() return?
Puppeteer can write a file with the path option or return PDF bytes when no path is supplied. Playwright documents a PDF buffer return that you can write or send in an HTTP response.
Why is my inline script not running?
Check that the script is inside the final string passed to setContent, that it has no syntax error, and that your readiness marker is set only after the script executes.
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.

