How to Use the DocRaptor API in PHP for HTML to PDF in India
Generate PDFs from HTML in PHP with DocRaptor, test safely, choose sync or async processing, and know what to confirm about India-specific billing and service terms.
Use DocRaptor’s PHP agent to send HTML or a page URL to its API and receive PDF bytes that your application can save or return to a user. Install the package with Composer, keep the API key on your server, and start in test mode, which adds a watermark. The technical integration works from a PHP application in India; the documentation cited here does not establish India-specific account availability, local payment methods, INR pricing, tax treatment, or data residency.
1. Install the PHP client and configure your API key
Install the official package and load Composer’s autoloader. Keep the key in an environment variable or another server-side secret store; do not place it in browser JavaScript or commit it to source control. DocRaptor’s PHP guide documents the package and client setup: PHP documentation.
composer require docraptor/docraptor
For example, set DOCRAPTOR_API_KEY in your deployment environment, then read it in PHP:
<?php
$apiKey = getenv('DOCRAPTOR_API_KEY');
if (!$apiKey) {
throw new RuntimeException('DOCRAPTOR_API_KEY is not configured');
}
require_once __DIR__ . '/vendor/autoload.php';
2. Create a PDF from inline HTML
This complete synchronous example uses test mode, creates a PDF from inline HTML, and writes the returned binary bytes to a file. Test output is watermarked, so use it to validate layout before switching to production mode.
<?php
$apiKey = getenv('DOCRAPTOR_API_KEY');
if (!$apiKey) {
throw new RuntimeException('DOCRAPTOR_API_KEY is not configured');
}
require_once __DIR__ . '/vendor/autoload.php';
$docraptor = new DocRaptor\DocApi();
$docraptor->getConfig()->setUsername($apiKey);
$doc = new DocRaptor\Doc();
$doc->setTest(true); // Watermarked validation output
$doc->setDocumentType('pdf');
$doc->setDocumentContent('<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Invoice</title>
<style>
body { font: 12pt sans-serif; margin: 24mm; }
h1 { color: #17324d; }
</style>
</head>
<body>
<h1>Invoice</h1>
<p>Generated from HTML with DocRaptor.</p>
</body>
</html>');
try {
$pdf = $docraptor->createDoc($doc);
if (file_put_contents(__DIR__ . '/output.pdf', $pdf) === false) {
throw new RuntimeException('Could not write output.pdf');
}
} catch (DocRaptor\ApiException $e) {
// Log diagnostics securely on the server; do not expose secrets to users.
error_log('DocRaptor API error: ' . $e->getMessage());
throw $e;
}
In production, set the document to production mode only after reviewing the test PDF, and use the account key configured for that environment. The PHP guide documents DocApi, Doc, setDocumentType, setDocumentContent, setTest, and the binary result from createDoc.
3. Choose inline HTML or a document URL
Use document_content when PHP already has the HTML, such as a rendered invoice or report. Use document_url when the document is available at a URL that the service can retrieve. Relative links to stylesheets, fonts, and images need a usable base URL; the PHP guide demonstrates setting a base URL through Prince options. Confirm that any URL and assets are reachable by the rendering service.
The REST document creation endpoint is https://api.docraptor.com/docs. The API accepts a PDF type and either HTML content or a document URL. Its documented HTTP Basic authentication uses the API key as the username and an empty password. See the API overview.
curl --user "$DOCRAPTOR_API_KEY:" \
-H 'Content-Type: application/json' \
-d '{"type":"pdf","document_content":"<html><body><h1>Hello</h1></body></html>","test":true}' \
https://api.docraptor.com/docs \
--output output.pdf
Keep the key in an environment variable and run this from a trusted server or terminal. A successful synchronous, non-hosted request returns PDF bytes, so save the response as a binary file.
4. Return a PDF from a PHP endpoint
To deliver the generated bytes directly to a browser, send PDF headers and echo the binary response rather than writing it to disk. Ensure the response contains no PHP notices, debug output, or HTML before the PDF data.
<?php
// Assume $pdf contains the binary string returned by createDoc($doc).
header('Content-Type: application/pdf');
header('Content-Disposition: attachment; filename="document.pdf"');
header('Content-Length: ' . strlen($pdf));
echo $pdf;
exit;
For larger or repeated jobs, consider writing to controlled storage and returning an application-managed download link. Protect generated documents according to their sensitivity and your organization’s retention policy.
5. JavaScript, layout, and external assets
DocRaptor renders HTML with Prince. Most layout work belongs in the HTML and CSS. JavaScript is disabled by default; enable it only when the document depends on client-side rendering, such as a chart that is absent from the initial HTML. The JavaScript tutorial describes the default and delayed rendering controls.
The PHP guide shows optional PrinceOptions, including a media setting and a base URL for relative resources. Use the base URL when your HTML references relative images or stylesheets. Test page breaks, fonts, images, and print-specific CSS in the resulting PDF; a successful API response does not guarantee the visual result matches a browser view.
External resources must be reachable during rendering. If a document relies on authenticated resources, private network addresses, or scripts that fetch data, verify that those resources are accessible to the renderer and that the document finishes rendering before the request limit.
6. Use asynchronous generation for longer documents
For large documents or documents with many external assets, use the asynchronous flow rather than keeping a web request open. DocRaptor’s PHP guide documents a 60-second maximum for synchronous generation and a 10-minute limit for asynchronous generation; check the live guide for current limits before relying on them. The PHP agent provides createAsyncDoc, and the documented workflow uses status polling or a callback to learn when the PDF is ready.
Keep the asynchronous job identifier with your application’s record, poll according to the API workflow, and make the completion handler safe to run more than once. Do not assume a submitted job is already a downloadable PDF: wait for its completed status and then retrieve the result as described in the PHP guide.
7. Python and Node.js REST examples
The PHP agent is the recommended fit for a PHP application. These direct REST examples show the same documented endpoint and Basic authentication pattern for other server-side environments. They use inline HTML and test mode; keep the key secret and save the response as bytes.
Python
import os
import requests
api_key = os.environ["DOCRAPTOR_API_KEY"]
response = requests.post(
"https://api.docraptor.com/docs",
auth=(api_key, ""),
json={
"type": "pdf",
"document_content": "<html><body><h1>Hello</h1></body></html>",
"test": True,
},
timeout=90,
)
response.raise_for_status()
with open("output.pdf", "wb") as pdf_file:
pdf_file.write(response.content)
Node.js
const apiKey = process.env.DOCRAPTOR_API_KEY;
if (!apiKey) throw new Error('DOCRAPTOR_API_KEY is not configured');
const basic = Buffer.from(`${apiKey}:`).toString('base64');
const response = await fetch('https://api.docraptor.com/docs', {
method: 'POST',
headers: {
Authorization: `Basic ${basic}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({
type: 'pdf',
document_content: '<html><body><h1>Hello</h1></body></html>',
test: true,
}),
});
if (!response.ok) {
throw new Error(`DocRaptor request failed: HTTP ${response.status}`);
}
const bytes = Buffer.from(await response.arrayBuffer());
await import('node:fs/promises').then(fs => fs.writeFile('output.pdf', bytes));
8. India-specific account and billing checks
The cited official integration and API pages explain how to call DocRaptor, but they do not establish India-specific account eligibility, payment methods, INR pricing, GST or other tax handling, or data-residency terms. Do not infer those details from the fact that the API is reachable or from a price quoted in another currency.
If any of those terms matter to your deployment, confirm them directly with DocRaptor and your organization’s finance, legal, or security team before committing. Keep this commercial review separate from the technical proof of concept: the PHP integration itself is based on the documented API workflow.
9. Troubleshooting
| Symptom | Likely cause | What to do |
|---|---|---|
| Composer cannot find the classes | The package is not installed or the Composer autoloader was not loaded. | Run composer require docraptor/docraptor in the application and include vendor/autoload.php. |
| Authentication fails | The key is missing, malformed, or not set as the API username. | Check server-side secret configuration and setUsername($apiKey). For REST, use Basic auth with the key as username and blank password. |
| The PDF has a watermark | The document was generated in test mode. | This is expected for validation. After checking the output, switch to production mode and use the account key for production generation. |
| Images, fonts, or CSS are missing | Relative URLs lack a base URL, or the renderer cannot reach the resource. | Set an appropriate base URL where needed and verify asset URLs are reachable during rendering. |
| A chart or dynamic section is blank | JavaScript is disabled by default or asynchronous content did not finish before capture. | Enable JavaScript only when required and configure the documented delayed-rendering behavior for the page. |
| A synchronous request runs too long | The document is large or has many external assets. | Use the asynchronous PHP flow and poll for completion or handle its callback. |
| The saved file is not a readable PDF | Application output was mixed with the binary response, or the response was handled as text. | Save the binary response unchanged; when streaming, send PDF headers and emit no prior output. |
| API exception reaches the user | Exception details were surfaced directly in the application. | Log diagnostics securely on the server, return a generic user-facing error, and avoid logging API secrets. |
10. Performance, reliability, and cost considerations
- Rendering time: Reduce unnecessary external assets and client-side work. Use async for long jobs; the cited PHP guide gives current documented limits of 60 seconds synchronous and 10 minutes asynchronous, which should be rechecked against the live docs.
- Reliability: Handle API exceptions and incomplete jobs explicitly. For async work, track job state and make polling or callbacks safe to repeat. Do not mark a document ready until the API reports completion and the result has been retrieved.
- Binary handling: Treat the response as bytes end to end. Avoid text encodings and accidental output before PDF bytes.
- Cost: DocRaptor’s documentation advertises paid plans starting at $15/month, but prices and plan terms can change. The sources do not establish an India-specific price, tax, or payment method; confirm current terms with DocRaptor.
- Hosted output: The API also documents hosted documents, which return a public URL, with pricing dependent on plan. Review access and retention implications before choosing hosted delivery. See document hosting details.
11. Or skip the browser setup
DocRaptor converts HTML into a PDF. If your job is to capture a web page as an image or PDF through an API, ScreenshotNeo is the ScreenshotNeo option to try first: it provides clean screenshots, bills only clean shots, and its lowest paid plan is $5.
One GET request can return a screenshot or PDF. See the ScreenshotNeo API documentation for the request options.
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
Cookie banners are accepted and removed before the shot, along with known newsletter popups and chat widgets. Bot checks, blank pages, and failed loads are never billed. An MCP server lets AI agents take screenshots. The free plan includes 1,000 screenshots a month with no card; paid plans start at $5 for 3,000.
Sign up free for 1,000 screenshots a month, with no card required.
12. FAQ
Can I use DocRaptor from India?
The documented API workflow can be called from a PHP application. The cited sources do not confirm India-specific availability or commercial terms, so verify those directly with DocRaptor.
Does a successful API call mean the PDF layout is correct?
No. Inspect the generated file for page breaks, missing assets, fonts, and dynamic content before moving from watermarked test output to production.
When should I enable JavaScript?
Only when the HTML needs client-side rendering. JavaScript is off by default, and dynamic pages may need delayed rendering so content is ready before PDF generation.
Can the API return something other than PDF?
The API reference lists XLS and XLSX as additional output types. This guide focuses on PDF generation.


