Overview
This document provides complete technical reference for all WebSave as Image configuration options, attributes, and callbacks. For installation instructions, tutorials, and examples, see the WebSave as Image Guide.
HTML Button Attributes
WebSave buttons are configured using HTML attributes. These attributes control authentication, styling, and link the button to JavaScript configuration objects.
data-key
Your WebSave key for authentication. This attribute is required for the button to function. You can use "demo" as a test key, which will produce watermarked output, or use your personal WebSave key for production conversions.
- Allowed Values:
-
demo
— Test mode with watermarked output- Your personal WebSave key — Manage your keys
data-config
References a JavaScript configuration object by name. This object should be defined in your page's JavaScript and contain the conversion settings. When omitted, default settings are used.
- Allowed Values:
-
- Any valid JavaScript object name defined in the global scope
class
CSS class(es) that activate WebSave functionality and optionally add visual styling. The pdfcrowd-websave
class is required for the button to work. The optional pdfcrowd-websave-style
class adds pre-built styling including icons and loading animations. If you want to use your own custom styling, do not include the pdfcrowd-websave-style
class.
- Required Classes:
-
- pdfcrowd-websave - Activates WebSave functionality (required)
- Optional Classes:
-
- pdfcrowd-websave-style - Adds visual styling, icons, and spinners
JavaScript Configuration Options
The configuration object referenced by data-config
controls the conversion behavior, visual appearance, and event handling. Define this object in JavaScript before the WebSave script loads.
Configuration Overview
Property | Type | Default | Description |
---|---|---|---|
API & Conversion Options | |||
apiSettings | object | {} |
API-specific parameters |
conversionMode | "url" | "content" | url |
How to fetch the page |
fileAction | "download" | "open" | "openNewTab" | download |
What to do with the file |
fileName | string | function(url) | URL-based |
Output filename |
verbosity | 0 | 1 | 2 | 0 |
Console logging level |
Visual Options | |||
icon | "image1" | "image2" | "none" | image1 |
Button icon style |
iconPosition | "left" | "right" | left |
Icon placement relative to text |
spinner | "ring" | "ellipsis" | "logo" | "none" | ring |
Loading animation type |
Event Callbacks | |||
onBeforeConversion | function(config) | null |
Pre-conversion hook |
onFileCreated | function(blob) | null |
Success handler |
onError | function(message, status) | null |
Error handler |
Properties
Configuration properties that control the appearance and behavior of the conversion.
apiSettings
Object containing PDFCrowd API parameters for fine-tuning the conversion. Any valid API option can be included here. Common options include page size, margins, headers/footers, and JavaScript processing settings. See the complete API reference for all available options.
- Default:
{}
- Examples:
-
-
PNG output with specific width:
{ output_format: "png", image_width: 1200 }
-
High-quality JPEG:
{ output_format: "jpg", jpeg_quality: 90 }
-
Full HD screenshot:
{ screenshot_width: 1920, screenshot_height: 1080 }
-
PNG output with specific width:
conversionMode
Specifies how the page should be converted. URL mode has the PDFCrowd server fetch and convert the public URL. Content mode uploads the current DOM state, which works with dynamic content, authentication, and local changes.
- Default:
url
- Allowed Values:
-
url
— Server fetches the page URL (requires public access)content
— Upload current DOM content (works with private/dynamic pages)
- Examples:
-
-
Convert current DOM state including user modifications:
"content"
-
Convert current DOM state including user modifications:
fileAction
Determines what happens with the converted file after generation.
- Default:
download
- Allowed Values:
-
download
— Save to user's downloads folderopen
— Replace current tab with the ImageopenNewTab
— Open Image in a new browser tab
fileName
Specify the name of the downloaded file. Can be a fixed string or a function that generates the name based on the page URL. The function receives the current URL and should return a string. File extension is added automatically if missing.
- Default:
Function that converts URL to filename
- Allowed Values:
-
String - Fixed filename
Function - function(url) { return string; }
- Examples:
-
-
Fixed filename:
"report.png"
-
Dynamic filename with date:
(url) => `report-${new Date().toISOString().split("T")[0]}.png`
-
Use last URL segment:
(url) => url.split('/').pop() || 'download'
-
Fixed filename:
verbosity
Controls console logging during conversion. Useful for debugging configuration issues, monitoring conversion progress, and troubleshooting callbacks behavior.
- Allowed Values:
-
0
— Silent mode, no console output1
— Log main events (initialization, start, completion, errors)2
— Full debug output (includes API calls, timing, detailed errors)
icon
Choose the icon to display on the button. Only applies when using the pdfcrowd-websave-style
class.
- Default:
image1
- Allowed Values:
-
image1
— Default Image icon (blue background)image2
— Alternative Image icon (white background)none
— No icon displayed
- Examples:
-
-
Use alternative Image icon:
"image2"
-
Text-only button:
"none"
-
Use alternative Image icon:
iconPosition
Position of the icon relative to the button text. Only applies when an icon is displayed.
- Default:
left
- Allowed Values:
-
left
— Icon appears before the textright
— Icon appears after the text
spinner
Type of loading animation shown during conversion. The spinner replaces the icon while the conversion is in progress. Only applies when using the pdfcrowd-websave-style
class.
- Default:
ring
- Allowed Values:
-
ring
— Animated circular spinnerellipsis
— Three dots animationlogo
— PDFCrowd logo animationnone
— No loading indicator
Callbacks
Event handlers that allow you to intercept and modify the conversion process. All callbacks support both synchronous and asynchronous operations - they can return values directly, return Promises, or be async functions.
onBeforeConversion(config) { return boolean; }
Called before the conversion starts. You can modify the configuration object (including URL and API settings) or cancel the conversion entirely.
- Parameters:
-
-
config
(Object) - The mutable configuration object containing all conversion settings. Any changes made to this object will be used in the conversion.url
(String) - The current page URL that will be convertedapiSettings
(Object) - PDFCrowd API parameters (can be modified)conversionMode
(String) - 'url' or 'content' modefileAction
(String) - 'download', 'open', or 'openNewTab'fileName
(String/Function) - The output filename or function that generates it
-
- Returns:
- Boolean or Promise<Boolean> - Return
true
to cancel the conversion. Returnfalse
orundefined
to proceed with the conversion. Can also return a Promise that resolves to one of these values. - Examples:
-
-
Add print parameter to URL:
(cfg) => { cfg.url += '?print=1'; }
-
Dynamically set page size:
(cfg) => { cfg.apiSettings.page_size = 'Letter'; }
-
Ask for confirmation (return true cancels):
(cfg) => !confirm('Generate Image?')
-
Validate form before conversion ▼
(cfg) => { if (!document.querySelector('form').checkValidity()) { alert('Please complete the form'); return true; // Cancel conversion } }
-
Modify multiple settings dynamically ▼
(cfg) => { // Add timestamp to filename const timestamp = new Date().toISOString().replace(/[:.]/g, '-'); cfg.fileName = `report-${timestamp}.png`; // Add custom header with user info const username = document.querySelector('#username').textContent; cfg.apiSettings.header_html = '<div style="text-align: center; font-size: 10px;">' + 'Generated by ' + username + '</div>'; }
-
Asynchronous configuration with Promise and API call ▼
async (cfg) => { // Fetch user preferences from server try { const response = await fetch('/api/user/pdf-preferences'); const prefs = await response.json(); // Apply user preferences to API settings cfg.apiSettings.page_size = prefs.pageSize || 'A4'; cfg.apiSettings.margin_top = prefs.marginTop || '1cm'; cfg.apiSettings.margin_bottom = prefs.marginBottom || '1cm'; // Continue with conversion return false; } catch (error) { alert('Could not load preferences. Using defaults.'); return false; // Proceed with defaults } }
-
Add print parameter to URL:
onFileCreated(blob) { return boolean; }
Called when the file has been successfully generated. Allows you to prevent the default download/open behavior (controlled by fileAction) and handle the file yourself.
- Parameters:
-
-
blob
(Blob) - JavaScript Blob object containing the generated Image data. The blob includes size and MIME type properties. Can be used with FormData, URL.createObjectURL(), or FileReader API.
-
- Returns:
- Boolean or Promise<Boolean> - Return
true
to prevent the default file action (download/open). Returnfalse
orundefined
to proceed with the default action. Can also return a Promise that resolves to one of these values. - Examples:
-
-
Log file size:
(blob) => console.log(`Image size: ${blob.size} bytes`)
-
Custom file handling ▼
(blob) => { // Upload to server instead of downloading const formData = new FormData(); formData.append('image', blob, 'document.png'); fetch('/upload', { method: 'POST', body: formData }); return true; // Prevent default download }
-
Asynchronous custom confirm dialog ▼
async function(blob) { const userChoice = await showAsyncModal("Download?"); return !userChoice; // Return true to skip download }
-
Simple AWS S3 upload ▼
async (blob) => { // Upload to AWS S3 using presigned URL // Assumes window.s3PresignedUrl is already set await fetch(window.s3PresignedUrl, { method: 'PUT', body: blob, headers: { 'Content-Type': 'application/image' } }); alert('Uploaded to S3!'); return true; // Skip download }
-
Log file size:
onError(message, status) { return boolean; }
Called when the conversion fails. Allows you to prevent the default error dialog and handle the error yourself. Use verbosity setting for debugging error details.
Note: The onError callback only controls error display. Automatic retries for server errors and button state management always happen before the callback is called.
- Parameters:
-
-
message
(String) - Human-readable error message describing what went wrong. May include details about network failures, API errors, or configuration issues. -
status
(Number/null) - Optional error or reason code. Can be an HTTP status code (e.g., 403 for authorization errors) or a PDFCrowd-specific error code. May be null for network or client-side errors.
-
- Returns:
- Boolean or Promise<Boolean> - Return
true
to prevent the default error dialog. Returnfalse
orundefined
to show the default error dialog to the user. Can also return a Promise that resolves to one of these values. - Examples:
-
-
Log errors to console:
(msg, status) => console.error(`Conversion failed: ${msg}`)
-
Display error in custom UI element ▼
(msg, status) => { document.getElementById('error-div').textContent = msg; return true; // Prevent default error dialog }
-
Custom error handling based on status code ▼
(msg, status) => { if (status === 403) { alert('Invalid API key. Please check your credentials.'); } else if (status >= 500) { alert('Server error. Please try again later.'); } else { alert(`Error: ${msg}`); } return true; // Handle all errors ourselves }
-
Asynchronous error logging with Promise ▼
async (msg, status) => { // Log error to analytics service await fetch('/api/analytics/error', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ error: msg, code: status }) }); return false; // Still show default dialog }
-
Log errors to console: