Hardware FixRecommendedDevice not working? Your driver may be the problemCheck updates for common hardware issues.Fix DriversOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsSlow PC?RecommendedPC slow today? Run a repair scan before it gets worseResolve common Windows issues and optimize system performance.Scan Now×
Skip to content
Base64

How to Encode a jsPDF and html2canvas File as Base64

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use canvas.toDataURL('image/png') when you need the image rendered by html2canvas. Use pdf.output('datauristring') after adding that image when you need the completed PDF. Both methods return a data URI; remove everything through the first comma only when the receiving API requires raw Base64.

Decide what you are encoding

There are two different artifacts in this workflow:

  • The rendered image: html2canvas paints an element into an HTML canvas. Encode it with canvas.toDataURL('image/png'). The result starts with data:image/png;base64,.
  • The finished PDF: jsPDF builds a document and embeds the image. Encode it with pdf.output('datauristring') (or its alias, dataurlstring). The result starts with a PDF media type and a Base64 marker.

Do not use the canvas string as a substitute for the PDF string. The canvas value represents only the rendered bitmap; the jsPDF value represents the completed PDF file.

Complete browser example

Install the libraries in your application (for example, with npm), then import them in a browser bundle:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
Lexar D40E 128GB Dual USB 3.2 Gen 1 Type-C Jump Drive, Champagne Silver
  • USB-C 2-in-1 storage OTG: The Lexar JumpDrive Dual Drive D40E features USB Type-A and Type-C connectors in a slim, portable form factor for easy device compatibility
  • Transfer speeds up to 100MB/s: Based on internal testing, performance may vary depending upon the host device, interface, and usage conditions. 1MB=1,000,000 bytes
  • Plug and Play: Widely compatible with USB Type-C smartphones, tablets, laptops, Macs, and traditional Type-A devices, no software installation required. The 360° swivel design allows for easy switching between connectors without the hassle of losing a cap
  • Durable & Compact: The Lexar D40E USB memory stick features a metal enclosure, withstands temperatures from 0° to 50° C (32°F to 122°F), and is lightweight at 26g with dimensions of 70.4 x 16.9 x 11.7mm
  • Security & Warranty: Securely protects files using an advanced security software solution with 256-bit AES encryption. Backed by a Lexar 3-year limited warranty
import html2canvas from 'html2canvas';
import { jsPDF } from 'jspdf';

async function encodeCapture() {
  const element = document.querySelector('#capture');
  if (!element) throw new Error('Missing #capture element');

  // Wait for fonts before painting the element.
  if (document.fonts?.ready) await document.fonts.ready;

  const canvas = await html2canvas(element);

  // Base64 data URI for the PNG rendered by html2canvas.
  const imageDataUrl = canvas.toDataURL('image/png');

  const pdf = new jsPDF();
  pdf.addImage(imageDataUrl, 'PNG', 10, 10, 190, 0);

  // Base64 data URI for the completed PDF.
  const pdfDataUrl = pdf.output('datauristring');

  // Only use this value if your endpoint explicitly wants raw Base64.
  const rawBase64 = pdfDataUrl.slice(pdfDataUrl.indexOf(',') + 1);

  return { canvas, imageDataUrl, pdfDataUrl, rawBase64 };
}

encodeCapture().then(({ pdfDataUrl }) => {
  console.log(pdfDataUrl); // Keep the data:application/pdf;base64,... prefix when allowed
});

The 190 value is the image width in the default jsPDF unit. A height of 0 asks jsPDF to preserve the image’s aspect ratio. Change the page, coordinates, and dimensions for your layout.

Convert an html2canvas canvas to Base64

Keep the data URI

canvas.toDataURL('image/png') synchronously serializes the canvas as a PNG data URI. Keeping the prefix is usually easiest because it tells the consumer both the media type and encoding:

const imageDataUrl = canvas.toDataURL('image/png');
imageElement.src = imageDataUrl;

await fetch('/upload-image', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({ image: imageDataUrl })
});

You can request another image type supported by the browser, such as JPEG, but use the matching MIME type and jsPDF format. PNG is lossless and handles transparency; JPEG is typically appropriate for photographic content but does not preserve transparency.

Return only the Base64 payload

A raw Base64 endpoint does not accept the metadata prefix. Remove it at the first comma instead of splitting on a fixed string:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #2
SANDISK 128GB Ultra Flair, USB-A Flash Drive, Up to 150MB/s Read Speeds
  • High-speed USB 3.0 performance of up to 150MB/s(1) [(1) Write to drive up to 15x faster than standard USB 2.0 drives (4MB/s); varies by drive capacity. Up to 150MB/s read speed. USB 3.0 port required. Based on internal testing; performance may be lower depending on host device, usage conditions, and other factors; 1MB=1,000,000 bytes]
  • Transfer a full-length movie in less than 30 seconds(2) [(2) Based on 1.2GB MPEG-4 video transfer with USB 3.0 host device. Results may vary based on host device, file attributes and other factors]
  • Transfer to drive up to 15 times faster than standard USB 2.0 drives(1)
  • Sleek, durable metal casing
  • Easy-to-use password protection for your private files(3) [(3)Password protection uses 128-bit AES encryption and is supported by Windows 7, Windows 8, Windows 10, and Mac OS X v10.9 plus; Software download required for Mac, visit the SanDisk SecureAccess support page]
const dataUrl = canvas.toDataURL('image/png');
const comma = dataUrl.indexOf(',');
if (comma === -1) throw new Error('Unexpected canvas data URL');
const rawImageBase64 = dataUrl.slice(comma + 1);

Send the media type separately when the protocol requires it. Never strip the prefix merely because it looks cleaner; a data URI and a raw Base64 payload are different interface values.

Get a Base64 PDF from jsPDF

Use the string-returning output mode

Build the PDF first, then call pdf.output('datauristring'). dataurlstring is an alias that also returns a string. These modes are intended for programmatic handling.

const pdf = new jsPDF({ format: 'a4', unit: 'mm' });
pdf.addImage(imageDataUrl, 'PNG', 10, 10, 190, 0);

const pdfDataUrl = pdf.output('datauristring');
const pdfBase64 = pdfDataUrl.slice(pdfDataUrl.indexOf(',') + 1);

await fetch('/upload-pdf', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({ pdf: pdfDataUrl })
});

Use pdfDataUrl when the server accepts a data URI. Use pdfBase64 only when the server contract says it wants the payload without the prefix. Encoding before addImage, or encoding the canvas and calling that value a PDF, produces the wrong artifact.

Prefer binary transport for large documents

Base64 is text wrapped around binary data and increases the amount of data your application must hold and transmit. If the receiving API supports binary uploads, ask jsPDF for an ArrayBuffer or Blob instead:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #3
2 Pack 64GB USB Flash Drive USB 2.0 Thumb Drives Jump Drive Fold Storage Memory Stick Swivel Design - Black
  • What You Get - 2 pack 64GB genuine USB 2.0 flash drives, 12-month warranty and lifetime friendly customer service
  • Great for All Ages and Purposes – the thumb drives are suitable for storing digital data for school, business or daily usage. Apply to data storage of music, photos, movies and other files
  • Easy to Use - Plug and play USB memory stick, no need to install any software. Support Windows 7 / 8 / 10 / Vista / XP / Unix / 2000 / ME / NT Linux and Mac OS, compatible with USB 2.0 and 1.1 ports
  • Convenient Design - 360°metal swivel cap with matt surface and ring designed zip drive can protect USB connector, avoid to leave your fingerprint and easily attach to your key chain to avoid from losing and for easy carrying
  • Brand Yourself - Brand the flash drive with your company's name and provide company's overview, policies, etc. to the newly joined employees or your customers
const arrayBuffer = pdf.output('arraybuffer');
const blob = pdf.output('blob');

await fetch('/upload-pdf', {
  method: 'POST',
  headers: { 'Content-Type': 'application/pdf' },
  body: blob
});

Use Base64 for JSON fields, message queues, or APIs that explicitly require it. Use a Blob or ArrayBuffer when your transport can carry binary bytes directly.

Make the capture reliable

Wait for fonts and images

Capture only after the element has its final dimensions. document.fonts.ready helps prevent fallback-font text from being painted. For images, wait for loading before calling html2canvas:

async function waitForImages(root) {
  const images = [...root.querySelectorAll('img')];
  await Promise.all(images.map(img => {
    if (img.complete) return img.decode?.().catch(() => {});
    return new Promise(resolve => {
      img.addEventListener('load', resolve, { once: true });
      img.addEventListener('error', resolve, { once: true });
    });
  }));
}

const element = document.querySelector('#capture');
await document.fonts?.ready;
await waitForImages(element);
const canvas = await html2canvas(element);

html2canvas works in modern evergreen browsers. It is a browser library, not a direct Node.js renderer; a Node process needs a browser environment if you want to run this workflow there.

Handle cross-origin resources

Images, fonts, or other resources loaded from another origin can taint the canvas. The page may appear correctly rendered, but reading pixels with toDataURL() can then fail with a security exception. Configure the asset server for appropriate CORS headers and load resources in a CORS-compatible way. When cross-origin content must be included, the html2canvas guidance is to use a proxy that accepts the URL and returns the resource as a Base64 data URI. Do not treat allowTaint as a way to bypass browser security; a tainted canvas remains unreadable.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #4
SIMMAX 32GB Memory Stick USB 2.0 Flash Drives Swivel Thumb Drive Pen Drive (32GB Purple)
  • GOOD VALUE PACKAGE - 1 Pack 32GB Memory Stick USB 2.0 Flash Drives with great cost performance and high quality.
  • BIG CAPACITY - The available capacity: 29.10GB-29.8GB, You can save the data of movies, music, photos, designs, programs, manuals, handouts in a high speed.Good performance in digital data storing, transferring and sharing with families, friends, workmates, clients and machines.
  • EASY TO USE & PLUG AND WORK - Support windows 7 / 8 / 10 / Vista / XP / 2000 / ME / NT Linux and Mac OS, Compatible with USB2.0 and below.
  • TWISTTURN DESIGN & EASY CARRY - The metal clip rotates 360° round the ABS plastic body which with rubber oil skin feeling finish. The capless design can avoid lossing of cap, and providing efficient protection to the USB port.
  • WARRANTY & SUPPORT - SIMMAX logo is laser printed on the USB connector surface, our products are of good quality and we promise that any problem about the product within one year since you buy.

Common errors and fixes

Symptom Likely cause Fix
SecurityError or “tainted canvas” A cross-origin image or font lacks usable CORS permission. Serve the asset with the correct CORS headers, host it on the same origin, or route it through a proxy that returns a data URI.
PDF contains a blank or clipped page The element was captured before layout settled, or its dimensions exceed the page. Wait for fonts/images, inspect canvas.width/canvas.height, and calculate jsPDF dimensions and page breaks explicitly.
Server rejects the value as invalid Base64 The server expects raw Base64 but received data:...;base64,, or vice versa. Confirm the API contract. Preserve the complete data URI when accepted; otherwise remove text through the first comma.
Only a PNG arrives when a PDF was expected canvas.toDataURL() was sent instead of jsPDF output. Call pdf.output('datauristring') after pdf.addImage().
Unexpected browser navigation A navigation-oriented datauri/dataurl mode was selected. Use the string-returning datauristring or dataurlstring mode.
Works locally but fails in production Production asset origins, CSP, authentication, or font loading differ. Check browser console security errors and ensure every image/font is reachable with the same CORS and authentication behavior.

Size, memory, and security considerations

  • Canvas dimensions determine image memory. Capturing a very large, full-page element at high pixel density can exhaust browser memory before encoding.
  • Base64 strings are convenient but costly for large payloads. Prefer a Blob or ArrayBuffer upload where possible.
  • Do not put sensitive PDF data in URLs, logs, analytics events, or client-visible query strings. Data URIs can be copied like any other string.
  • Validate the destination API’s maximum request size and timeout. Chunking or direct binary upload may be necessary for large files.
  • Encode once, at the boundary that requires it. Repeated conversion between data URI, raw Base64, and binary increases memory use and creates opportunities to corrupt the payload.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Or skip the browser setup

If your goal is a clean screenshot or PDF of a URL rather than a browser-side html2canvas render, ScreenshotNeo provides a website screenshot API and MCP server. It accepts consent banners before capture and removes more than 60 known consent platforms, newsletter popups, and chat widgets; each cleanup step can be disabled. Bot checks, CAPTCHAs, blank pages, timeouts, failed loads, and cache hits are not billed, and the response identifies the page verdict and billing status in X-Page-Verdict and X-Billed headers.

One GET request returns PNG, JPEG, WebP, or PDF:

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp

See the ScreenshotNeo documentation for options such as full-page lazy-image loading, CSS-selector element capture, device and viewport presets, retina scale, PDF paper and margin controls, custom CSS or JavaScript, waits, request blocking, cookies, headers, geolocation, caching, signed links, asynchronous webhooks, bulk capture, and the usage API. Its MCP server includes take_screenshot, get_page_info, and capture_pdf for Claude, Cursor, and other MCP clients.

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)
const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);

The Free plan includes 1,000 shots per month with no card. Paid plans start at $5 for 3,000 shots; every feature is available on every plan. Create a free ScreenshotNeo account.

FAQ

Can I encode the canvas without creating a PDF?

Yes. Return the PNG (or another supported image type) from canvas.toDataURL(). It is an image data URI, not a PDF.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Which jsPDF output mode should I use in application code?

Use datauristring or dataurlstring when you need a returned string. Choose arraybuffer or blob when your transport accepts binary data.

Best Value
Sale
IMEASON Swivel Design 16GB USB Flash Drive with Keychain, USB 2.0 Portable Thumb Drive Memory Stick, FAT32 Format Flashdrive for Data Storage, Photos, Music, Files (Black, 16 GB)
  • 【16GB Flash Drive】USB flash drives with 16GB capacity, meet your needs of daily use on work, school, home and travelling for photos, music, videos, files storage and transfer. IMEASON thumb drives can be used to store different files, easy to data backup.
  • 【Metal Swivel Cap Design】USB thumb drive is metal swivel cover provides extra protection for the usb thumbdrive connector, no usb drive cap to lose; keychain design makes it easier to carry without worrying lose it.
  • 【Wide Compatibility】USB drive supports Windows 7/8/10/11 / Vista / XP / Unix / 2000 / ME / NT Linux and Mac OS, also Supports USB 2.0 and 1.1 ports. USB Stick support TV, desktop, notebook computer, car, audio and other device. The USB Memory Stick is your great data storage and transfer companion with traveling and working.
  • 【Easy to use】usb memory stick is plug and play without any software installation. Just simply plug the Flashdrive into the port of your USB-compatible devices such as computer, laptop to start data storage or transmission.
  • 【What You Get】16 GB USB Flash Drive Thumb Drive, The default format of the usb storage flash drive is FAT32.

Why does my Base64 value include a comma?

The comma separates the data-URI metadata from the encoded payload. Keep the entire value for a data-URI field; remove the prefix only for a raw-Base64 field.

Frequently Asked Questions

Can I encode the canvas without creating a PDF?

Yes. Return the PNG (or another supported image type) from canvas.toDataURL(). It is an image data URI, not a PDF.

Which jsPDF output mode should I use in application code?

Use datauristring or dataurlstring when you need a returned string. Choose arraybuffer or blob when your transport accepts binary data.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Why does my Base64 value include a comma?

The comma separates the data-URI metadata from the encoded payload. Keep the entire value for a data-URI field; remove the prefix only for a raw-Base64 field.

The Bottom Line

Encode the rendered image with canvas.toDataURL(), but encode the completed PDF with pdf.output('datauristring'). Strip the data-URI prefix only when the receiving API explicitly requires raw Base64.

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.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Read next

Recommended PC Tool
Recommended PC Tool
Crashes, No Sound, or Screen Glitches?Free driver scan
Windows Errors? Fix Them Before They SpreadFree repair scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.