PDFshift API Guide Convert Documents Instantly with Reliable Format Support
Struggling to convert HTML documents into polished PDFs within your application? PDFshift API solves this by providing a simple, RESTful endpoint that transforms any HTML string or URL into a high-fidelity PDF file. It works by accepting your content via a POST request and returning the converted PDF, handling complex CSS and JavaScript rendering automatically. The key benefit is its straightforward integration, requiring only a single API call without needing to manage server-side PDF libraries or dependencies. You can use it by sending your HTML payload and receiving the ready-to-download PDF in response.
What Exactly Is This API and How Does It Generate PDFs?
PDFshift is a REST API that converts HTML content into PDF files. You send it a URL or raw HTML via a POST request, and it returns a ready-to-download PDF. The generation process works by rendering your HTML in a headless browser, then capturing that rendered page as a PDF document. Q: Does it handle CSS and JavaScript? A: Yes, PDFshift runs the full browser engine, so your styles and dynamic scripts are applied before the PDF is generated. You control output with parameters like page size, margins, and header/footer templates. The API processes your request almost instantly, making it practical for on-demand document creation without managing your own rendering infrastructure.
Core functionality: Converting HTML to PDF through a simple REST request
The core functionality of the PDFshift API revolves around accepting raw HTML content or a publicly accessible URL via a single REST POST request, then returning the rendered PDF file in the response. Users submit the HTML payload as JSON, specifying the source and optionally configuring page size, margins, or wait times to control rendering. The API processes the request server-side, converting the provided markup into a print-ready document without requiring local libraries, browser instances, or complex setup. This streamlined request-response pattern eliminates installation overhead, allowing any programming language with HTTP capabilities to generate a PDF through one straightforward API call.
Supported input formats and output customization parameters
PDFshift API accepts diverse input formats for seamless PDF generation, including HTML code, URLs, Markdown, and plain text, ensuring flexibility for any source. You can customize output via parameters like page_size, margin, orientation, and zoom, plus inject custom CSS or headers/footers for precise layout control. This allows tailoring every PDF pdf converter api to exact specifications without manual processing.
- Convert HTML, URLs, Markdown, or text directly into PDFs.
- Adjust page dimensions, margins, orientation, and scaling.
- Apply custom CSS, headers, footers, and watermark overlays.
- Set filename, viewport width, and even paper type (e.g., A4, letter).
How the API handles complex layouts, CSS, and JavaScript rendering
PDFshift API renders HTML using a full headless Chromium engine, ensuring that complex layouts with advanced CSS like Grid, Flexbox, and multi-column designs are faithfully reproduced. The engine also executes JavaScript before generating the PDF, so dynamic content—such as charts, interactive tables, or delayed renders—is fully captured. This means pages that rely on JS frameworks like React or Vue for layout construction will render accurately. Q: Does it support responsive CSS and print stylesheets? A: Yes, the API automatically processes both screen and print CSS rules, and you can enforce specific viewport widths to control how complex layouts adapt before PDF generation.
Key Features That Make the Service Stand Out for Developers
PDFshift API stands out for developers through its single POST request conversion model, eliminating the complexity of multi-step pipelines. It delivers blazing-fast rendering with full CSS and JavaScript support, ensuring pixel-perfect PDFs from any URL or raw HTML. The service offers customizable page options (size, margins, headers/footers) directly via query parameters, enabling precise output without post-processing. High-volume reliability is built on a stateless architecture, with concurrent request handling that prevents bottlenecks. All conversions return a direct download link, skipping file storage, which simplifies integration into CI/CD and serverless workflows. Developers also benefit from clear error codes and idempotent calls, making debugging and retries straightforward.
Built-in watermarking, headers, footers, and page numbering options
For developers who demand polished output, PDFshift delivers exact control over document formatting and branding elements. You can inject custom watermarks—text or images—directly via API parameters, overlaying them at specific opacity and rotation. Headers and footers support dynamic placeholders like {date} or {title}, while page numbering offers automatic left, center, or right alignment with customizable starting values.
- Define watermark position, scale, and opacity per request
- Insert repeating headers/footers with variables like {page} and {url}
- Set numbering style (Arabic, Roman) and start page
- Combine all three layers without extra processing overhead
Automatic table of contents generation and hyperlink preservation
PDFshift automates the creation of a table of contents from document headings, ensuring a logical navigation structure in the final PDF. This feature preserves hyperlinks within the generated TOC, allowing developers to deliver documents where each entry links directly to its corresponding section. The API parses heading levels to construct a hierarchical index, maintaining clickable integrity even after conversion from HTML or Markdown. This seamless hyperlink preservation eliminates manual post-processing, as every internal anchor remains functional. Q: Does PDFshift maintain hyperlinks in the table of contents when converting from HTML? A: Yes, it automatically converts header-based anchors into clickable entries within the generated TOC, preserving all original cross-references.
Security features: HTTPS enforcement and no data retention policy
HTTPS enforcement ensures all data exchanged with the PDFshift API is encrypted in transit, preventing interception during PDF generation. The API rejects any non-HTTPS requests, creating a mandatory secure channel. A strict no data retention policy means PDFshift does not store uploaded documents or generated PDFs on its servers after the conversion completes. Files are processed in memory only and permanently deleted within minutes. This sequence guarantees confidentiality:
- Client sends document via HTTPS.
- PDFshift converts and returns output.
- Source and result are immediately purged.
How to Integrate It Into Your Workflow in Minutes
To integrate PDFshift API into your workflow in minutes, send a POST request with your document URL or raw HTML to their single endpoint. It returns a converted PDF binary, so you can pipe it directly into cloud storage or a download prompt.
Most setups use a simple cURL call or a fetch in your language—no SDKs needed, just an API key.
Test immediately by hardcoding one URL, then replace it with dynamic data from your form or database. Cache the resulting PDF URL to avoid redundant API calls. For automated batch processing, use a queue to send conversions sequentially or run them in parallel with Promise.all.
Authentication method: simple API key passed in the request header
To integrate PDFshift into your workflow, simply pass your unique API key in the request header as Authorization: Bearer YOUR_API_KEY. No OAuth flows, no complex handshakes—just a single header value in every HTTP call. Your code appends this to the request, and PDFshift instantly validates the key, returning the converted PDF. This eliminates setup time entirely; you can send your first conversion within seconds of receiving the key. Whether using cURL, Python, or JavaScript, authentication remains a one-line addition, ensuring zero friction between your application and PDFshift’s conversion engine.
Code examples for common languages: cURL, Python, PHP, and Node.js
To get started with PDFshift, each language has a ready-to-use code snippet for rapid PDF generation. For a quick test, use cURL directly in your terminal:
- Send a POST request with your API key and a URL to convert.
- Save the returned binary as a PDF file.
In Python, import the `requests` library, post JSON to the endpoint, and write the response content to a file. PHP developers can use `file_get_contents()` with a stream context for a one-liner. Node.js users leverage the `axios` package: post the same JSON payload, then pipe the response data into a local writable stream. Each snippet requires only your API key and the source document.
Handling errors and understanding the response structure
When integrating PDFshift, examine the response structure immediately after each request. The API returns a JSON object containing a `success` boolean and either a `pdf_url` or an `error` field. For HTTP status codes, 200 indicates success; 4xx signals client-side issues like invalid parameters or exceeded rate limits, while 5xx points to server-side failures. Always log the full response body to capture error details such as `invalid_url` or `conversion_failed`. Proactive error handling should parse the `error` field and trigger retry logic with exponential backoff for transient 5xx errors. Q: What is the most common mistake in handling PDFshift errors? A: Ignoring the `success` boolean and assuming a 200 status guarantees a valid PDF—always verify the response structure before processing the URL.
Pricing Model, Limits, and When to Choose Different Tiers
PDFshift API employs a straightforward per-page pricing model, with the free tier offering 100 pages per month for testing. Paid tiers begin at $9/month for 1,000 pages, scaling to higher volumes with reduced per-page costs. Limits are strictly enforced: exceeding your plan’s page quota results in API errors unless you upgrade. Choose the Free tier for low-volume evaluation or hobby projects. The $9 tier suits startups or small teams with regular document generation. Enterprise tiers, requiring a custom quote, are ideal for high-throughput production environments where thousands of pages are processed daily. Q: When should I upgrade from the free tier? A: Upgrade immediately once your monthly page needs exceed 100, as any overage blocks API calls until the next cycle.
Free tier allowances and how paid plans scale with higher volume
PDFshift API offers a generous free tier allowance, typically including a set number of monthly conversions (e.g., 100 documents) to evaluate the service. Paid plans introduce scalable volume tiers that increase with higher monthly commitments, such as jumping from 1,000 to 50,000 conversions. Each paid tier reduces the per-conversion cost significantly, allowing businesses to pay for only the needed capacity without overage penalties. Volume limits are reset monthly, and higher tiers often include priority processing for large batches. This structure ensures smooth scaling from testing to production, as users can simply upgrade to a plan matching their current document load.
What happens when you exceed your monthly conversion quota
Exceeding your PDFshift API monthly conversion quota triggers an automatic hard limit on further requests. The service immediately returns a 429 Too Many Requests HTTP status code for all API calls until your quota resets at the start of the next billing cycle. Unprocessed conversions are rejected; no partial charges or rollovers occur. To resume conversions mid-cycle, you must upgrade to a higher tier or purchase an additional quota pack. Your account remains active for dashboard access, but no new documents can be rendered.
- All API calls fail with a
429error; no conversions are queued or held. - No automatic overage fees apply—service stops cleanly, not incurring extra costs.
- Quota resets monthly; unused allowances do not carry over to the next period.
- Upgrading your plan is the only way to restore immediate conversion capability.
Comparing the pay-as-you-go option versus subscription plans
When deciding between pay-as-you-go and a subscription for PDFshift, it really comes down to your volume. Pay-as-you-go is perfect for sporadic use, letting you buy a pack of conversions that never expire, so you’re never stuck with a monthly bill you don’t need. Subscriptions, however, offer a lower per-conversion cost and are ideal if you process steady batches each month. The key is matching your usage frequency—if you convert documents daily, a subscription saves money; for occasional projects, pay-as-you-go keeps things flexible.
Q: Should I choose pay-as-you-go or a subscription for PDFshift?
A: It depends on your conversion volume. Go pay-as-you-go for irregular use to avoid monthly fees, or pick a subscription if you convert regularly for a better per-document rate.
Common Troubleshooting Scenarios and Best Practices
When the PDFshift API returns a 422 error, first validate your HTML payload for unclosed tags or malformed CSS, as this is the most frequent cause. For large or complex documents experiencing timeouts, implement chunked processing by splitting the HTML into logical sections. Always enforce a 30-second request timeout in your client code, coupled with exponential backoff for retry logic on 429 rate-limit responses. A common oversight is ignoring the pdf_url response parameter, which allows asynchronous retrieval when generation exceeds standard latency. Log all HTTP response codes, especially 400 and 502, alongside the exact payload sent to pinpoint regression. For best results, serve the HTML from a UTF-8 encoded string rather than a publicly accessible URL to avoid caching and access control issues.
Why your generated PDF looks different from the browser preview
A key reason your generated PDF differs from the browser preview is that PDFshift API uses a headless Chromium engine with no user interaction, meaning CSS print styles, responsive breakpoints, and JavaScript-driven layouts may render inconsistently. Browser previews often include scrollbar widths, dynamic fonts, or zoom levels that the headless environment does not replicate. Ensure your CSS uses absolute units (px, pt) for page dimensions, avoids relying on viewport height (vh) for non-scrolling content, and specifies a fixed viewport meta tag. Additionally, any lazy-loaded images or fonts must be fully preloaded before PDF generation.
| Browser Preview | PDFshift Generated PDF |
| Interactive viewport, variable zoom | Fixed 595×842 points (A4 default) |
| CSS `@media screen` active | CSS `@media print` or `@page` rules applied |
| JS runs fully (async, timers) | Renders after initial JS (timers may be incomplete) |
Optimizing input HTML for faster and more reliable conversions
To optimize input HTML for faster and more reliable conversions via the PDFshift API, you must prioritize clean, minimal markup to reduce rendering overhead. Strip unnecessary whitespace, inline scripts, and external dependencies that delay DOM loading. For instance, replace complex CSS frameworks with inline styles for critical layout, as external stylesheets introduce latency. Even a small reduction in node count can shave seconds from API response times during peak load. Validate your HTML structure against PDFshift’s supported elements to avoid partial failures.
- Use base64-encoded images instead of external URLs to eliminate network request bottlenecks.
- Avoid JavaScript-driven dynamic content; PDFshift processes static HTML for consistency.
- Set a defined viewport `` tag to prevent layout shifts that distort page dimensions.
- Minify HTML and inline critical assets using tools like html-minifier before submission.
Handling large files, external resources, and custom fonts
Handling large files with PDFshift requires chunking payloads or using direct URL input to avoid timeouts. External resource dependencies, such as images or scripts hosted on third-party servers, must be publicly accessible or passed inline, as the API does not resolve private network paths. Custom fonts often fail when referenced via relative CSS paths; you must embed them as Base64 data URIs or host them on a publicly reachable CDN. The API strictly processes the provided HTML as a standalone document, so any resource not explicitly included or externally accessible will cause rendering failures. Always validate absolute URLs and font file formats before submission.