To generate an invoice PDF from a URL that requires login, establish an authenticated browser session first, carry its cookies and local storage into a fresh context, open the invoice URL, wait for the final redirect and invoice-ready content, then call the browser’s PDF method. If the protected endpoint already returns a PDF, skip browser rendering and make an authenticated HTTP request instead.
The correct method depends on what the URL returns
Inspect the protected endpoint before choosing a tool. A server-generated PDF should be downloaded directly; an HTML invoice that builds itself with JavaScript needs a real browser session.
| Invoice URL behavior | Best fit | Why |
|---|---|---|
| The response is already a PDF | Authenticated HTTP request | Lowest overhead and no layout rendering is required. |
| The response is an HTML application with JavaScript | Playwright or Puppeteer | The browser executes scripts, loads fonts and images, and preserves session state. |
| Login is represented by cookies or local storage | Playwright storageState or an equivalent browser context |
The signed-in state can be reused without automating the login on every invoice. |
| Login uses HTTP Basic authentication | Browser credentials or an authenticated HTTP client | Credentials can be scoped to the protected origin. |
| You generate many invoices | One browser process with isolated contexts | Contexts reduce startup cost while keeping accounts separated; validate concurrency against the billing system. |
A reliable authenticated-PDF workflow
- Authenticate through the application’s UI or API. Complete redirects, consent screens and any required MFA before attempting the invoice URL.
- Persist the resulting state. Save cookies, local storage and related browser state with Playwright’s
storageState, or retain an equivalent in-memory object. - Create a fresh context for rendering. Load the saved state into a new context rather than reusing a page that may contain stale navigation state.
- Navigate and verify identity. Wait for the final post-login URL and a selector that proves the invoice is ready. A successful HTTP response alone can still be a login page.
- Wait for visual dependencies. Ensure invoice data, fonts, images and client-side totals have finished loading. Use a readiness selector, a short application-specific delay or network-idle detection as appropriate.
- Choose print behavior and PDF options. PDF generation normally uses print CSS. Emulate screen media when the invoice only has screen styles, then set paper size, margins, page ranges, backgrounds and header/footer behavior.
- Write or stream the bytes. Save the PDF to controlled storage, close the context and remove temporary state when it is no longer needed.
Playwright: save login state, then render the invoice
The following Node.js example uses a two-phase flow. The first phase logs in once and writes a state file. The second phase loads that state into a new context and creates the PDF. Replace the URLs and selectors with those used by your application.
import { chromium } from 'playwright';
const loginUrl = 'https://billing.example.com/login';
const invoiceUrl = 'https://billing.example.com/invoices/123';
const statePath = './auth-state.json';
const browser = await chromium.launch();
// Phase 1: authenticate and save cookies/local storage.
const loginContext = await browser.newContext();
const loginPage = await loginContext.newPage();
await loginPage.goto(loginUrl, { waitUntil: 'domcontentloaded' });
await loginPage.getByLabel('Email').fill(process.env.BILLING_EMAIL);
await loginPage.getByLabel('Password').fill(process.env.BILLING_PASSWORD);
await loginPage.getByRole('button', { name: /sign in|log in/i }).click();
await loginPage.waitForURL('**/dashboard**');
await loginContext.storageState({ path: statePath });
await loginContext.close();
// Phase 2: render with the saved authenticated state.
const context = await browser.newContext({ storageState: statePath });
const page = await context.newPage();
await page.goto(invoiceUrl, { waitUntil: 'domcontentloaded' });
await page.waitForURL('**/invoices/**');
await page.locator('[data-invoice-ready="true"]').waitFor({ state: 'visible' });
// Use print CSS. Change to "screen" if the invoice is styled only for screens.
await page.emulateMedia({ media: 'print' });
await page.pdf({
path: 'invoice-123.pdf',
format: 'A4',
printBackground: true,
displayHeaderFooter: false,
margin: { top: '16mm', right: '14mm', bottom: '16mm', left: '14mm' }
});
await context.close();
await browser.close();
If the site does not redirect to a URL matching the example, replace waitForURL with a condition that is stable for your application, such as a signed-in navigation item. The readiness selector should appear only after invoice values and totals are present; do not use a generic page-load event as proof that the document is complete.
What’s actually slowing this PC down?
Pick the symptom - the matching free tool is one click away.
#1 Best Overall
- Two-Part Carbonless Invoice Book: Each invoice book has 50 sets of invoices, each with a white/light yellow section, with the yellow section retained in the invoice book to maintain detailed records.
- Consecutively Numbered: Enlarged red 6-digit numbers in the upper right corner of each invoice receipt book help you quickly navigate through your orders.
- Wraparound Divider Flap: A thick folded cardboard divider is integrated into the back of each invoice book for use between each two-part sales order to prevent the written content from rubbing off on subsequent copies of the invoice, resulting in wasted invoices.
- 2 Packs/50 Sets (100 Sets Total): Each invoice book provides 50 sequentially numbered carbonless sets of 2 invoice books for long-term use.
- Customizable Space: Each invoice book for small business has space at the top to add a company seal or sticker.
Reuse state without reusing accounts
For a worker queue, launch one browser process and create a separate context for each account or job. Never load one account’s state into another account’s context. Refresh the state when sessions expire, and keep the login phase outside the hot path when your identity provider permits it.
Puppeteer alternative
Puppeteer’s official guidance is direct: “For printing PDFs use Page.pdf().” This example assumes you already have a valid cookie value. A UI login can be used instead, followed by page.cookies() and secure storage of the returned cookies.
import puppeteer from 'puppeteer';
const browser = await puppeteer.launch();
const context = await browser.createBrowserContext();
const page = await context.newPage();
await page.setCookie({
name: 'session',
value: process.env.INVOICE_SESSION,
domain: 'billing.example.com',
path: '/',
secure: true,
httpOnly: true
});
await page.goto('https://billing.example.com/invoices/123', {
waitUntil: 'domcontentloaded'
});
await page.waitForSelector('[data-invoice-ready="true"]', { visible: true });
await page.emulateMediaType('print');
await page.pdf({
path: 'invoice-123.pdf',
format: 'A4',
printBackground: true,
margin: { top: '16mm', right: '14mm', bottom: '16mm', left: '14mm' }
});
await context.close();
await browser.close();
When the invoice uses screen-only CSS, call emulateMediaType('screen') before page.pdf(). Both Playwright and Puppeteer wait for fonts as part of PDF generation, but application data and images still need an explicit readiness check.
Direct authenticated downloads when the endpoint is a PDF
Do not launch a browser if the server already returns the final PDF bytes. Check the response’s Content-Type, status and, where possible, a document identifier before saving it.
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 →Rank #2
- Easily print W-2s, 1099s, statements, invoices, certificates, and coupons with this half-sheet perforated paper. These perforated sheets help you save time by providing clean and easy tears
- Case includes 2500 bright white 8.5" x 11" sheets of 20 lb copy paper, featuring a clean horizontal perforation 5 1/2" from the bottom for quick tearing and folding (A5 paper)
- Our perforated printer paper makes payroll, shipping, and everyday business tasks easier and more efficient, reducing the stress and hassle of manual document processing
- This 2-part paper is compatible with laser and inkjet printers; copiers; and most business, accounting, and shipping software that uses standard templates, ensuring simple integration
- PrintWorks Professional perforated paper has been proudly made in the USA since 1964 using domestically sourced, environmentally friendly materials for reliable quality and sustainability
Bearer token with cURL
curl --fail --silent --show-error
-H "Authorization: Bearer $INVOICE_TOKEN"
-H "Accept: application/pdf"
"https://billing.example.com/api/invoices/123.pdf"
-o invoice-123.pdf
Bearer token with Python
import os
import requests
url = "https://billing.example.com/api/invoices/123.pdf"
response = requests.get(
url,
headers={
"Authorization": f"Bearer {os.environ['INVOICE_TOKEN']}",
"Accept": "application/pdf",
},
timeout=90,
)
response.raise_for_status()
if response.headers.get("content-type", "").split(";", 1)[0].lower() != "application/pdf":
raise RuntimeError("The endpoint did not return a PDF")
with open("invoice-123.pdf", "wb") as output:
output.write(response.content)
If the endpoint returns HTML, a redirect to a login page or a JavaScript shell, switch to Playwright or Puppeteer. Passing a bearer token to a browser is safe only when the application supports that mechanism; otherwise complete the application’s normal login flow and let it establish cookies or local storage.
Authentication patterns and edge cases
Cookies and local storage
Playwright’s saved state can contain cookies and local-storage values needed by a single-page application. Treat the state as an authenticated session, load it only for approved jobs and regenerate it after logout or expiry.
HTTP Basic authentication
For Basic Auth, configure credentials before navigation. In Playwright, create the context with the appropriate HTTP credentials; for a direct PDF endpoint, send an Authorization header from your HTTP client. Scope credentials to the protected host and avoid embedding them in URLs.
Bearer tokens
A direct PDF API normally accepts a bearer token in the request header. An HTML application may expect the token in a login exchange, a cookie or an application-specific storage key. Follow the application’s supported flow instead of injecting an arbitrary header into every request.
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 →Rank #3
- QUALITY INVOICES: Adams Order books provide a professional invoice or customer receipt; a great way to create and maintain a professional image for small businesses and service providers
- 50 TWO-PART CARBONLESS FORMS: Customers get the perforated white top copy; retain the canary and pink copies for your records
- WRAP-AROUND COVER: Fold the back cover between sets to keep invoices neat and legible
- ROOM FOR CUSTOMIZATION: A blank space at top leaves room for your company stamp; a big savings over custom-printed forms
- CONSECUTIVELY NUMBERED: Large 6-digit numbers in the upper right hand corner help you thumb through orders quickly
Redirect-based login
Identity providers can set cookies across several redirects. Wait for the final signed-in URL or an invoice-ready element. Rendering immediately after clicking “Sign in” commonly produces the identity provider page or a partially initialized invoice.
Multiple invoices and account isolation
Use an isolated context per account and restrict navigation to the invoice hosts you expect. A queue can reuse the browser process, but concurrency must be tested against rate limits, session invalidation and the application’s own document-locking behavior.
PDF layout controls that affect invoice fidelity
- Print versus screen CSS: PDF methods use print media by default. Emulate screen media when the invoice’s colors, columns or visibility rules exist only in screen styles.
- Paper and margins: Set an explicit format such as A4 or Letter and margins that leave room for totals, tax details and payment instructions.
- Backgrounds: Enable background graphics when branding or shaded table rows are part of the invoice.
- Headers and footers: Use templates only when you need page numbers, an invoice identifier or a generated timestamp; otherwise disable them so browser defaults do not add unexpected content.
- Page ranges: Restrict ranges only after confirming that long line-item tables are not being truncated.
- Lazy content: Scroll or wait for the application’s lazy-loading trigger before capture when images or line items appear only after they enter the viewport.
Reliability, throughput and cost considerations
Browser startup is more expensive than an HTTP download, so keep a browser process alive for queued work and create short-lived contexts. The context still provides account isolation. Set navigation and readiness timeouts appropriate to the application, capture diagnostic details such as the final URL and response status, and retry only transient navigation failures. Do not blindly retry an authentication failure.
Validate every output before publishing it to storage: confirm that the bytes are a PDF, that the invoice number and account are the expected ones, and that the file is non-empty. Keep the original response or a checksum when your audit process requires reproducibility. No authoritative performance or accuracy figure is established for these workflows, so measure on your own application and document the conditions.
Rank #4
- Easily print W-2s, 1099s, statements, invoices, certificates, and coupons with this 3 1/2" perforated paper. These perforated sheets help you save time by providing clean and easy tears
- Ream includes 500 bright white 8.5" x 11" sheets of 20 lb copy paper, featuring a clean horizontal perforation 3 1/2" from the bottom for quick tearing and folding
- Our 3 1/2 inch perforated printer paper makes payroll, shipping, and everyday business tasks easier and more efficient, reducing the stress and hassle of manual document processing
- This 2-part paper is compatible with laser and inkjet printers; copiers; and most business, accounting, and shipping software that uses standard templates, ensuring simple integration
- PrintWorks Professional perforated paper has been proudly made in the USA since 1964 using domestically sourced, environmentally friendly materials for reliable quality and sustainability
Security checklist for financial documents
- Keep Playwright state files, cookies and authorization headers out of source control and logs.
- Use a least-privilege account dedicated to document retrieval.
- Encrypt stored state, limit its lifetime and delete temporary copies after the job.
- Restrict outbound navigation to approved invoice hosts to reduce SSRF exposure.
- Check content type and invoice identity before retaining a PDF.
- Apply retention, access-control and encryption policies to generated invoices because they contain financial information.
Troubleshooting authenticated invoice PDFs
| Symptom | Likely cause | Fix |
|---|---|---|
| The PDF is a login page | State was not loaded, expired or set on the wrong domain. | Inspect the final URL, regenerate state through the normal login flow and verify the cookie domain. |
| HTTP 401 or 403 | Missing, expired or insufficient credentials. | Refresh the token or session, check account permissions and stop retrying until authentication succeeds. |
| Invoice is blank | Client-side data has not finished loading. | Wait for an invoice-specific readiness selector or application signal instead of relying on domcontentloaded. |
| Styles or logos are missing | Print CSS hides them, resources are blocked or lazy loading has not run. | Try screen media, enable background graphics, wait for fonts/images and inspect failed resource requests. |
| Only the first page is present | Content is virtualized or a page range was set unintentionally. | Trigger lazy content, remove restrictive page ranges and verify the line-item count before saving. |
| Capture hangs | A network request never settles or a readiness selector never appears. | Use bounded navigation and selector timeouts, record the failing URL and provide a controlled fallback or failure state. |
| PDF contains the wrong invoice | A stale page, cached route or incorrect account context was reused. | Create a fresh context, assert the invoice number and account in the DOM, and isolate jobs by account. |
Or skip the browser setup
ScreenshotNeo is a hosted website screenshot API and MCP server. It can render a URL as a PDF with custom cookies, headers or an Authorization value, so you can provide the authenticated session without maintaining Playwright or Puppeteer infrastructure. Its PDF options include paper size, margins, landscape mode and page ranges.
For a basic invoice URL, the request shape is:
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://billing.example.com/invoices/123 -o invoice-123.pdf
Use the authentication and PDF parameters described in the ScreenshotNeo API documentation to supply the invoice’s cookies, custom headers or bearer authorization. The same endpoint can also be called from Python or Node.js:
import requests
r = requests.get("https://api.screenshotneo.com/v1/shot", params={"access_key": "YOUR_API_KEY", "url": "https://billing.example.com/invoices/123"}, timeout=90)
open("invoice-123.pdf", "wb").write(r.content)
const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://billing.example.com/invoices/123' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);
const pdf = Buffer.from(await res.arrayBuffer());
await Bun.write('invoice-123.pdf', pdf);
ScreenshotNeo removes cookie-consent banners, newsletter popups and chat widgets before capture. Bot checks, blank pages, failed loads, timeouts and cache hits are not billed, and response headers identify the page verdict and billing result. Its MCP server exposes take_screenshot, get_page_info and capture_pdf tools for Claude, Cursor and other MCP clients. The Free plan includes 1,000 shots per month with no card; paid plans start at $5 for 3,000 shots. Plans are:
| Plan | Allowance | Price |
|---|---|---|
| Free | 1,000 shots/month | $0 |
| Starter | 3,000 shots | $5 |
| Growth | 15,000 shots | $15 |
| Pro | 60,000 shots | $39 |
| Scale | 250,000 shots | $99 |
| Business | 1,000,000 shots | $249 |
Yearly billing gives two months free, and every feature is available on every plan. Create a free ScreenshotNeo account to start with 1,000 screenshots a month and no card.
Recommended Free Tools
FAQ
What if the invoice is drawn on a canvas or inside a shadow DOM?
Use a real browser renderer and wait for the application’s own completion signal. If a readiness selector is inside a shadow root, expose a host-level marker or evaluate a narrowly scoped condition before calling the PDF method.
Best Value
- PACKAGE INCLUDES - Our invoice book per pack has 50 sets sheets, Total of 100 sheets. red code printed on each page with consecutive numbers
- Material - Receipt book is excellent quality carbonless paper is used in their production, tears off easily along the perforation.
- A5 Size - Sales invoice book size of 5.5" x 8.5", and forms are 2 part carbonless white/yellow sets on a sturdy chipboard backing
- WIDE APPLICATION - Sales reciepts/invoice book for small business is ideal for restaurants, food trucks, vendors, service provider, photographers, caterers, florists, bakeries, cafes, boutiques and salons
How should MFA be handled in an automated job?
Complete MFA during an approved login step, then save the resulting browser state for the short period in which it is valid. Do not record one-time codes or bypass the identity provider’s controls.
Frequently Asked Questions
What if the invoice is drawn on a canvas or inside a shadow DOM?
Use a real browser renderer and wait for the application’s completion signal. If the readiness selector is inside a shadow root, expose a host-level marker or evaluate a narrowly scoped condition before calling the PDF method.
How should MFA be handled in an automated job?
Complete MFA during an approved login step, then save the resulting browser state for the short period in which it is valid. Do not record one-time codes or bypass the identity provider’s controls.
Free tools Windows power users keep installed
One-click scans. No signup required.
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.

