Skip to content

NodeJS

Official Node.js SDK for the Docstron PDF Generation API. Generate professional PDFs from HTML templates with ease.

Terminal window
npm install docstron

Add your API key to your environment:

DOCSTRON_API_KEY=your-api-key
DOCSTRON_BASE_URL=https://api.docstron.com/v1
const Docstron = require("docstron");
// Initialize the client
const client = new Docstron();
// With custom options
const client = new Docstron("your-api-key-here", {
baseURL: "https://api.docstron.com/v1",
});
// Quick generate a PDF
const pdf = await client.documents.quickGenerate({
html: "<h1>Hello {{name}}!</h1>",
data: { name: "World" },
response_type: "pdf",
});
// Save the PDF
const fs = require("fs");
fs.writeFileSync("hello.pdf", pdf);

// Get all applications
const apps = await client.applications.list();
apps.forEach((app) => {
console.log(`App: ${app.name} - ${app.app_id}`);
});
// Get a specific application
const app = await client.applications.get(
"app-7b4d78fb-820c-4ca9-84cc-46953f211234"
);
console.log(app.name, app.is_active);
// Create an application
const newApp = await client.applications.create({
name: "Invoice System",
description: "Manages all customer invoices",
is_active: true,
});
// Update an application
const updated = await client.applications.update("app-xxx", {
name: "Updated Invoice System",
is_active: false,
});
// Delete an application
await client.applications.delete("app-xxx");
// Create a template
const template = await client.templates.create({
application_id: "app-7b4d78fb-820c-4ca9-84cc-46953f211234",
name: "Invoice Template",
content: `
<html>
<body>
<h1>Invoice</h1>
<p>Customer: {{customer_name}}</p>
<p>Amount: {{amount}}</p>
<p>Date: {{date}}</p>
</body>
</html>
`,
extra_css: "@page { margin: 2cm; }",
});
const templateId = template.template_id;
// List all templates
const templates = await client.templates.list("app-xxx");
// Get a specific template
const fetchedTemplate = await client.templates.get(templateId);
// Update a template
const updatedTemplate = await client.templates.update(templateId, {
name: "Updated Invoice Template",
is_active: false,
});
// Delete a template
await client.templates.delete(templateId);
// Generate PDF from template
const pdfBinary = await client.documents.generate(templateId, {
data: {
customer_name: "John Doe",
amount: "$299.00",
date: "2024-12-02",
},
response_type: "pdf",
});
// Save PDF to file
const fs = require("fs");
fs.writeFileSync("invoice.pdf", pdfBinary);
// Generate and get document ID
const doc = await client.documents.generate(templateId, {
data: { customer_name: "Jane Smith", amount: "$599.00" },
response_type: "document_id",
});
const documentId = doc.document_id;
// Generate with password protection
const protectedPdf = await client.documents.generate(templateId, {
data: { customer_name: "Bob Johnson" },
response_type: "pdf",
password: "secret123",
});
// Generate PDF without pre-creating a template
const pdf = await client.documents.quickGenerate({
html: `
<html>
<head>
<style>
body { font-family: Arial, sans-serif; }
.header { color: #333; }
</style>
</head>
<body>
<h1 class="header">Receipt</h1>
<p>Thank you, {{customer}}!</p>
<p>Total: {{total}}</p>
</body>
</html>
`,
data: { customer: "Alice Williams", total: "$49.99" },
response_type: "pdf",
extra_css: "@page { size: A4; margin: 1cm; }",
});
fs.writeFileSync("receipt.pdf", pdf);
// Quick generate and save as template for future use
const doc = await client.documents.quickGenerate({
html: "<h1>Report for {{month}}</h1>",
data: { month: "December" },
save_template: true,
application_id: "app-7b4d78fb-820c-4ca9-84cc-46953f211234",
response_type: "document_id",
});
// List all documents
const docs = await client.documents.list();
docs.forEach((doc) => {
console.log(`Document: ${doc.document_id}`);
});
// Get a specific document
const doc = await client.documents.get(
"document-517145ce-5a09-4e47-a257-887e239ecb36"
);
console.log(doc.template_id, doc.created_at);
// Update document attributes
const updatedDoc = await client.documents.update(
"document-517145ce-5a09-4e47-a257-887e239ecb36",
{ customer_name: "Updated Name", amount: "$999.00" }
);
// Download document as PDF
const pdfData = await client.documents.download(
"document-517145ce-5a09-4e47-a257-887e239ecb36"
);
// Or download and save directly
await client.documents.download(
"document-517145ce-5a09-4e47-a257-887e239ecb36",
"./downloaded_invoice.pdf"
);
// Delete document
await client.documents.delete("document-517145ce-5a09-4e47-a257-887e239ecb36");
// Get usage statistics
const usage = await client.usage.get();
console.log(`Plan: ${usage.subscription.plan_name}`);
console.log(`Documents used this month: ${usage.documents.monthly}`);
console.log(`Monthly limit: ${usage.documents.monthly_limit}`);
console.log(`Usage percentage: ${usage.documents.usage_percentage}%`);
console.log(
`Applications: ${usage.applications.total}/${usage.applications.limit}`
);
console.log(`Templates: ${usage.templates.total}/${usage.templates.limit}`);

When generating documents, you can choose from three response types:

  1. pdf - Returns binary PDF data directly
  2. json_with_base64 - Returns JSON with base64-encoded PDF
  3. document_id - Returns JSON with document ID (default)
// Get PDF directly
const pdf = await client.documents.generate(templateId, {
data: { name: "Test" },
response_type: "pdf",
});
// Get base64 encoded PDF
const response = await client.documents.generate(templateId, {
data: { name: "Test" },
response_type: "json_with_base64",
});
const base64Pdf = response.pdf_content;
// Get document ID only
const docResponse = await client.documents.generate(templateId, {
data: { name: "Test" },
response_type: "document_id",
});
const docId = docResponse.document_id;

The SDK provides custom error types for better error handling:

const {
DocstronError,
ValidationError,
AuthenticationError,
NotFoundError,
RateLimitError,
} = require("docstron");
const client = new Docstron("your-api-key");
try {
const doc = await client.documents.generate("invalid-template-id", {
data: { test: "data" },
});
} catch (error) {
if (error instanceof AuthenticationError) {
console.error("Authentication failed:", error.message);
} else if (error instanceof NotFoundError) {
console.error("Resource not found:", error.message);
} else if (error instanceof ValidationError) {
console.error("Validation error:", error.message);
error.errors.forEach((err) => {
console.error(`- ${err.field}: ${err.message}`);
});
} else if (error instanceof RateLimitError) {
console.error("Rate limit exceeded:", error.message);
} else if (error instanceof DocstronError) {
console.error("An error occurred:", error.message);
console.error("Status code:", error.statusCode);
} else {
console.error("Unexpected error:", error);
}
}

// Use a custom API endpoint
const client = new Docstron("your-api-key", {
baseURL: "https://custom.docstron.com/v1",
});

For best results when creating templates:

  • Use inline CSS or the extra_css parameter for styling
  • Support for modern CSS including flexbox and grid
  • Use @page rules in extra_css for page-specific styling
  • Template placeholders use {{variable_name}} syntax

Example with advanced styling:

const template = await client.templates.create({
application_id: "app-123",
name: "Styled Invoice",
content: `
<html>
<head>
<style>
.container { max-width: 800px; margin: 0 auto; }
.header { background: #1ee494; color: white; padding: 20px; }
.content { padding: 20px; }
table { width: 100%; border-collapse: collapse; }
th, td { padding: 10px; border: 1px solid #ddd; }
</style>
</head>
<body>
<div class="container">
<div class="header">
<h1>Invoice #{{invoice_number}}</h1>
</div>
<div class="content">
<p>Customer: {{customer_name}}</p>
<table>
<tr>
<th>Item</th>
<th>Amount</th>
</tr>
<tr>
<td>{{item_name}}</td>
<td>{{item_amount}}</td>
</tr>
</table>
</div>
</div>
</body>
</html>
`,
extra_css: `
@page {
margin: 2cm;
@bottom-center {
content: "Page " counter(page) " of " counter(pages);
}
}
`,
});

  • new Docstron(apiKey, options) - Initialize client with API key and optional configuration
  • client.applications.get(appId) - Get application by ID
  • client.applications.list() - List all applications
  • client.applications.create(params) - Create a new application
  • client.applications.update(appId, params) - Update an application
  • client.applications.delete(appId) - Delete an application
  • client.templates.create(params) - Create template
  • client.templates.get(templateId) - Get template by ID
  • client.templates.list(applicationId) - List all templates for an application
  • client.templates.update(templateId, params) - Update template
  • client.templates.delete(templateId) - Delete template
  • client.documents.generate(templateId, options) - Generate document from template
  • client.documents.quickGenerate(options) - Quick generate without template
  • client.documents.get(documentId) - Get document by ID
  • client.documents.list() - List all documents
  • client.documents.update(documentId, data) - Update document
  • client.documents.delete(documentId) - Delete document
  • client.documents.download(documentId, filepath) - Download PDF
  • client.usage.get() - Get usage statistics

Contributions are welcome! Please feel free to submit a Pull Request.

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add some amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

This project is licensed under the MIT License - see the LICENSE file for details.