Getting started overview
Integrating CraftMyPDF involves a sequence of steps designed to enable automated document generation. This process typically begins with account creation, followed by the acquisition of API credentials. Developers then design a document template and utilize the CraftMyPDF API to programmatically populate that template with data and generate a PDF document. The API is RESTful with JSON input and output, supporting various programming languages through official SDKs and direct HTTP requests.
The core functionality revolves around two main components: the online Document Editor for template creation and the PDF Generation API for rendering. This guide focuses on the initial setup and making a successful first API call.
Quick reference steps
The table below outlines the essential steps to get started with CraftMyPDF:
| Step | What to Do | Where |
|---|---|---|
| 1. Create Account | Sign up for a CraftMyPDF account. | CraftMyPDF Homepage |
| 2. Generate API Key | Obtain your unique API key from the dashboard. | CraftMyPDF Dashboard > API Keys |
| 3. Design Template | Create or select a document template using the visual editor. | CraftMyPDF Dashboard > Templates |
| 4. Install SDK (Optional) | Install the appropriate SDK for your programming language. | CraftMyPDF Documentation |
| 5. Make API Call | Send a request to the API with your template ID and data. | Your application code |
| 6. Handle Response | Process the API response, which contains the PDF URL or binary. | Your application code |
Create an account and get keys
To access the CraftMyPDF API, developers must first create an account. CraftMyPDF offers a Developer Plan free tier, which includes 50 PDF generations per month, suitable for initial testing and development. Account registration typically requires an email address and password.
Account registration
- Navigate to the CraftMyPDF website.
- Locate and click the "Sign Up" or "Get Started Free" button.
- Follow the prompts to enter your email address and create a password.
- Verify your email address if required.
Obtaining API keys
Upon successful registration and login, you will be directed to the CraftMyPDF dashboard. API keys are essential for authenticating your requests to the CraftMyPDF API. These keys link your API calls to your account and usage limits. According to the CraftMyPDF documentation, API keys are managed within the dashboard settings.
- From the CraftMyPDF dashboard, find the "API Keys" or "Settings" section.
- Click on "Generate New API Key" or a similar option.
- A unique API key will be displayed. This key should be treated as a sensitive credential.
- Copy and store your API key securely. It is recommended to use environment variables for storing API keys in production applications, as outlined in security best practices for API key management.
Your first request
Making your first request involves two primary steps: designing a template and then sending a programmatic request to generate a PDF using that template and your data. CraftMyPDF provides an online editor to simplify template creation.
Designing a template
Templates define the layout and static content of your PDF documents. Dynamic content is inserted using placeholders that you define in the template.
- In the CraftMyPDF dashboard, navigate to the "Templates" section.
- Click "Create New Template" or select an existing sample template.
- Use the visual editor to design your document. Insert text, images, tables, and define placeholders (e.g.,
{{customer_name}},{{invoice_total}}) where dynamic data will be injected. - Save your template. Note the Template ID, which will be required for your API calls.
Making the API call
CraftMyPDF supports various programming languages through official SDKs. For this example, we will demonstrate a basic request using Node.js, one of the primary language examples. The API requires your template ID, the data to populate the template, and your API key for authentication.
Install the Node.js SDK
npm install craftmypdf-node
Node.js example
This example demonstrates how to generate a PDF using a predefined template and sample data. Replace YOUR_API_KEY and YOUR_TEMPLATE_ID with your actual credentials.
const CraftMyPDF = require('craftmypdf-node');
const apiKey = 'YOUR_API_KEY';
const templateId = 'YOUR_TEMPLATE_ID'; // e.g., 'tpl_xxxxxxxx'
const craftMyPDF = new CraftMyPDF(apiKey);
const data = {
customer_name: 'John Doe',
invoice_number: 'INV-2026-001',
items: [
{ description: 'Product A', quantity: 1, price: 100.00 },
{ description: 'Product B', quantity: 2, price: 50.00 }
],
total_amount: 200.00
};
async function generatePdf() {
try {
const response = await craftMyPDF.generatePdf({
templateId: templateId,
data: data,
output: 'url' // or 'base64' for base64 encoded PDF
});
console.log('PDF generated successfully. URL:', response.url);
} catch (error) {
console.error('Error generating PDF:', error.response ? error.response.data : error.message);
}
}
generatePdf();
Python example
For Python developers, the process is similar. First, install the SDK:
pip install craftmypdf
Then, use the following code structure:
from craftmypdf import CraftMyPDF
api_key = 'YOUR_API_KEY'
template_id = 'YOUR_TEMPLATE_ID' # e.g., 'tpl_xxxxxxxx'
cmpdf = CraftMyPDF(api_key)
data = {
'customer_name': 'Jane Smith',
'order_id': 'ORD-2026-002',
'products': [
{'name': 'Service X', 'amount': 150.00},
{'name': 'Service Y', 'amount': 75.00}
],
'grand_total': 225.00
}
try:
response = cmpdf.generate_pdf(
template_id=template_id,
data=data,
output='url' # or 'base64'
)
print(f"PDF generated successfully. URL: {response['url']}")
except Exception as e:
print(f"Error generating PDF: {e}")
The API response will typically include a URL where the generated PDF can be accessed, or the PDF content directly encoded in base64, depending on the output parameter specified in the request.
Common next steps
After successfully generating your first PDF, developers often explore additional features and integrations to enhance their document generation workflows:
- Advanced Template Design: Utilize more complex features of the online editor, such as conditional logic within templates, loops for dynamic lists, and custom fonts, as described in the CraftMyPDF template editor guide.
- Webhook Integration: Configure webhooks to receive notifications when PDF generation is complete, especially for asynchronous or long-running tasks. This is a common pattern for event-driven systems, as detailed in AWS Lambda's asynchronous invocation patterns.
- Error Handling and Logging: Implement robust error handling mechanisms in your application to gracefully manage API failures, rate limit errors, or invalid template data. Incorporate logging to monitor API usage and troubleshoot issues.
- Security Best Practices: Beyond securing API keys, consider implementing measures like input validation for data sent to the API to prevent injection vulnerabilities.
- Scalability and Performance: For high-volume generation, review CraftMyPDF's pricing plans and consider strategies for optimizing API call frequency or leveraging asynchronous generation options.
- Integration with Other Services: Connect CraftMyPDF with other platforms for end-to-end automation, such as sending generated invoices via email (e.g., using Twilio SendGrid) or storing reports in cloud storage services (e.g., Amazon S3).
Troubleshooting the first call
Encountering issues during the initial API call is common. Here are some troubleshooting steps:
- Invalid API Key: Double-check that your API key is correct and has not expired or been revoked. Ensure no leading or trailing spaces are copied. The API key authenticates your request, and an incorrect key will result in an authorization error.
- Incorrect Template ID: Verify that the
templateIdused in your API request exactly matches a template ID from your CraftMyPDF dashboard. A mismatch will prevent the API from finding the correct document structure. - Malformed Data Payload: Ensure that the
dataobject sent in your request is valid JSON and that the keys (e.g.,customer_name) precisely match the placeholders defined in your CraftMyPDF template. Mismatched or malformed data will lead to empty fields or rendering errors in the PDF. Refer to the CraftMyPDF API reference for expected data structures. - Network Issues: Confirm that your application has network connectivity and can reach the CraftMyPDF API endpoints. Firewall rules or proxy settings might interfere with outbound requests.
- Rate Limiting: While less common for a first call, excessive requests in a short period can trigger rate limiting. Review the CraftMyPDF documentation for specific rate limit details if you are making multiple rapid tests.
- Error Messages: Pay close attention to the error messages returned by the API. They often provide specific clues about what went wrong (e.g., "Unauthorized" for API key issues, "Template not found" for template ID issues).
- SDK vs. Raw HTTP: If you are using an SDK, ensure it's up to date. If making raw HTTP requests, confirm headers (e.g.,
Content-Type: application/jsonandAuthorization: Bearer YOUR_API_KEY) are correctly set, as described in MDN Web Docs on Authorization header.