How to print login-protected pages

ERP, OA, and report centers often expose URLs that require login. printHtmlByUrl fetches the address locally and converts it to PDF—it does not automatically use your browser cookies. This guide shows how to pass cookies, httpHeaders, and localStorages in the fourth argument extraOptions.

The usual problem

Reports, order details, and statements live behind authenticated URLs. You are logged in, but a bare printHtmlByUrl(url) uses a fresh session on the client—you often get a login page or 401 instead of business content.

Fix: pass the user session via the fourth parameter extraOptions—cookies, headers, or storage—so the local client fetches the URL with credentials.

What printHtmlByUrl does

Unlike printHtml with an HTML string, printHtmlByUrl only supplies a URL; the local client does the rest:

  1. The browser sends url, pdfOptions, printOptions, and extraOptions over WebSocket
  2. The client requests the URL and applies cookies / HTTP headers / storage from extraOptions
  3. Renders the page to PDF (controlled by pdfOptions)
  4. Prints via printOptions, or returns a preview URL when action: 'preview'

Auth must live in extraOptions—your tab’s login state is not shared automatically.

extraOptions auth fields

These work with printHtmlByUrl, printPdfByUrl, printImageByUrl, and batch tasks (per-task extraOptions):

Field Type Auth scenario
cookies object Server session, JSESSIONID, cookie-based tokens
httpHeaders object JWT / API key: Authorization: 'Bearer …' (values must be strings)
localStorages object Vue/React SPAs storing access_token in localStorage
sessionStorages object Tab-scoped tokens or temporary keys
requestTimeout number(秒) Slow pages after auth or heavy XHR—increase from default 15s
action 'print' | 'preview' Use preview first to confirm you got the business page, not login

The client also sets localStorage._printMode_ = 'true' so your page can hide chrome for print layout.

For Java/PHP/.NET apps with cookie sessions—read cookies on the logged-in page and pass them:

import webPrintPdf from 'web-print-pdf';

/** 从 document.cookie 解析单个键(示例,可按项目封装) */
function getCookie(name) {
  const m = document.cookie.match(new RegExp('(?:^|; )' + name + '=([^;]*)'));
  return m ? decodeURIComponent(m[1]) : '';
}

async function printReport(reportUrl) {
  const sessionId = getCookie('JSESSIONID'); // 或 SESSION、sid 等,与后端一致

  await webPrintPdf.printHtmlByUrl(
    reportUrl,
    { paperFormat: 'A4', printBackground: true, margin: { top: '12mm', bottom: '12mm' } },
    { paperFormat: 'A4' },
    {
      cookies: { JSESSIONID: sessionId },
      requestTimeout: 30,
      action: 'print'
    }
  );
}

Example 2: Bearer token (httpHeaders)

When the gateway checks Authorization, read access_token from Pinia/localStorage into httpHeaders:

import webPrintPdf from 'web-print-pdf';
import { useUserStore } from '@/stores/user';

async function printProtectedPage(url) {
  const token = useUserStore().accessToken; // 或 localStorage.getItem('access_token')

  await webPrintPdf.printHtmlByUrl(
    url,
    { paperFormat: 'A4', printBackground: true },
    { paperFormat: 'A4' },
    {
      httpHeaders: {
        Authorization: `Bearer ${token}`
      },
      requestTimeout: 30,
      action: 'preview' // 联调时先预览,确认非登录页后再改为 print
    }
  );
}

Example 3: localStorage / sessionStorage

If the page reads token from localStorage on load, inject keys via localStorages:

await webPrintPdf.printHtmlByUrl(
  'https://erp.example.com/print/order/10086',
  { paperFormat: 'A4', printBackground: true },
  { paperFormat: 'A4' },
  {
    localStorages: {
      access_token: localStorage.getItem('access_token') || '',
      tenant_id: localStorage.getItem('tenant_id') || ''
    },
    cookies: { lang: 'zh-CN' },
    requestTimeout: 45
  }
);

Example 4: cookie + header combo

Some stacks need both session cookies and CSRF/custom headers:

await webPrintPdf.printHtmlByUrl(
  orderDetailUrl,
  { paperFormat: 'A4', printBackground: true },
  { paperFormat: 'A4' },
  {
    cookies: {
      SESSION: getCookie('SESSION'),
      XSRF-TOKEN: getCookie('XSRF-TOKEN')
    },
    httpHeaders: {
      'X-XSRF-TOKEN': getCookie('XSRF-TOKEN'),
      Authorization: `Bearer ${token}`
    },
    requestTimeout: 30
  }
);

Where credentials come from

  • Current logged-in page: read document.cookie, store, or localStorage in the print button handler
  • Server-issued: short-lived print token or signed URL from your backend
  • Use printHtml instead: API returns rendered HTML—no URL auth (see main docs)

Alternatives

Approach When to use
printHtmlByUrl + extraOptions You already have a report URL and want front-end to pass credentials
printHtml / printHtmlByBase64 Backend returns HTML/Base64; auth stays on the API
One-time print link Signed query URL from server—minimal extraOptions

Security notes

  • Never embed long-lived passwords; prefer short tokens and print-scoped permissions
  • Use HTTPS for report URLs; do not log full cookies/tokens
  • Use action: 'preview' while testing to verify PDF content
  • Surface failures with formatPrintError—see frontend error handling standard reference

Troubleshooting

Symptom What to check
PDF shows login page or blank Cookie names/domain; missing httpHeaders; try preview
401 / 403 Expired token; Authorization must be a string; CSRF header
Broken layout or missing data Raise requestTimeout; add localStorages; page may need WebSocket
timeout Slow intranet; increase requestTimeout above in-page XHR timeouts
Download client free Open live demos