NodeJS
Official Node.js SDK for the Docstron PDF Generation API. Generate professional PDFs from HTML templates with ease.
Installation
Section titled “Installation”npm install docstronConfiguration
Section titled “Configuration”Add your API key to your environment:
DOCSTRON_API_KEY=your-api-keyDOCSTRON_BASE_URL=https://api.docstron.com/v1Quick Start
Section titled “Quick Start”const Docstron = require("docstron");
// Initialize the clientconst client = new Docstron();
// With custom optionsconst client = new Docstron("your-api-key-here", { baseURL: "https://api.docstron.com/v1",});
// Quick generate a PDFconst pdf = await client.documents.quickGenerate({ html: "<h1>Hello {{name}}!</h1>", data: { name: "World" }, response_type: "pdf",});
// Save the PDFconst fs = require("fs");fs.writeFileSync("hello.pdf", pdf);Working with Applications
Section titled “Working with Applications”// Get all applicationsconst apps = await client.applications.list();apps.forEach((app) => { console.log(`App: ${app.name} - ${app.app_id}`);});
// Get a specific applicationconst app = await client.applications.get( "app-7b4d78fb-820c-4ca9-84cc-46953f211234");console.log(app.name, app.is_active);
// Create an applicationconst newApp = await client.applications.create({ name: "Invoice System", description: "Manages all customer invoices", is_active: true,});
// Update an applicationconst updated = await client.applications.update("app-xxx", { name: "Updated Invoice System", is_active: false,});
// Delete an applicationawait client.applications.delete("app-xxx");Managing Templates
Section titled “Managing Templates”// Create a templateconst 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 templatesconst templates = await client.templates.list("app-xxx");
// Get a specific templateconst fetchedTemplate = await client.templates.get(templateId);
// Update a templateconst updatedTemplate = await client.templates.update(templateId, { name: "Updated Invoice Template", is_active: false,});
// Delete a templateawait client.templates.delete(templateId);Generating Documents
Section titled “Generating Documents”// Generate PDF from templateconst pdfBinary = await client.documents.generate(templateId, { data: { customer_name: "John Doe", amount: "$299.00", date: "2024-12-02", }, response_type: "pdf",});
// Save PDF to fileconst fs = require("fs");fs.writeFileSync("invoice.pdf", pdfBinary);
// Generate and get document IDconst 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 protectionconst protectedPdf = await client.documents.generate(templateId, { data: { customer_name: "Bob Johnson" }, response_type: "pdf", password: "secret123",});Quick Generate (Without Template)
Section titled “Quick Generate (Without Template)”// Generate PDF without pre-creating a templateconst 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 useconst 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",});Managing Documents
Section titled “Managing Documents”// List all documentsconst docs = await client.documents.list();docs.forEach((doc) => { console.log(`Document: ${doc.document_id}`);});
// Get a specific documentconst doc = await client.documents.get( "document-517145ce-5a09-4e47-a257-887e239ecb36");console.log(doc.template_id, doc.created_at);
// Update document attributesconst updatedDoc = await client.documents.update( "document-517145ce-5a09-4e47-a257-887e239ecb36", { customer_name: "Updated Name", amount: "$999.00" });
// Download document as PDFconst pdfData = await client.documents.download( "document-517145ce-5a09-4e47-a257-887e239ecb36");
// Or download and save directlyawait client.documents.download( "document-517145ce-5a09-4e47-a257-887e239ecb36", "./downloaded_invoice.pdf");
// Delete documentawait client.documents.delete("document-517145ce-5a09-4e47-a257-887e239ecb36");Checking Usage
Section titled “Checking Usage”// Get usage statisticsconst 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}`);Response Types
Section titled “Response Types”When generating documents, you can choose from three response types:
pdf- Returns binary PDF data directlyjson_with_base64- Returns JSON with base64-encoded PDFdocument_id- Returns JSON with document ID (default)
// Get PDF directlyconst pdf = await client.documents.generate(templateId, { data: { name: "Test" }, response_type: "pdf",});
// Get base64 encoded PDFconst response = await client.documents.generate(templateId, { data: { name: "Test" }, response_type: "json_with_base64",});const base64Pdf = response.pdf_content;
// Get document ID onlyconst docResponse = await client.documents.generate(templateId, { data: { name: "Test" }, response_type: "document_id",});const docId = docResponse.document_id;Error Handling
Section titled “Error Handling”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); }}Advanced Usage
Section titled “Advanced Usage”Custom Base URL
Section titled “Custom Base URL”// Use a custom API endpointconst client = new Docstron("your-api-key", { baseURL: "https://custom.docstron.com/v1",});HTML and CSS Guidelines
Section titled “HTML and CSS Guidelines”For best results when creating templates:
- Use inline CSS or the
extra_cssparameter for styling - Support for modern CSS including flexbox and grid
- Use
@pagerules inextra_cssfor 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); } } `,});API Reference
Section titled “API Reference”Client
Section titled “Client”new Docstron(apiKey, options)- Initialize client with API key and optional configuration
Applications
Section titled “Applications”client.applications.get(appId)- Get application by IDclient.applications.list()- List all applicationsclient.applications.create(params)- Create a new applicationclient.applications.update(appId, params)- Update an applicationclient.applications.delete(appId)- Delete an application
Templates
Section titled “Templates”client.templates.create(params)- Create templateclient.templates.get(templateId)- Get template by IDclient.templates.list(applicationId)- List all templates for an applicationclient.templates.update(templateId, params)- Update templateclient.templates.delete(templateId)- Delete template
Documents
Section titled “Documents”client.documents.generate(templateId, options)- Generate document from templateclient.documents.quickGenerate(options)- Quick generate without templateclient.documents.get(documentId)- Get document by IDclient.documents.list()- List all documentsclient.documents.update(documentId, data)- Update documentclient.documents.delete(documentId)- Delete documentclient.documents.download(documentId, filepath)- Download PDF
client.usage.get()- Get usage statistics
Contributing
Section titled “Contributing”Contributions are welcome! Please feel free to submit a Pull Request.
- Fork the repository
- Create your feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add some amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
License
Section titled “License”This project is licensed under the MIT License - see the LICENSE file for details.
Support
Section titled “Support”- 📚 Documentation
- 💬 Issues
- 📧 Email: support@docstron.com