Converting PDF files to DOCX format is a frequent requirement when building document‑centric applications, especially when you need editable Word output. GroupDocs.Conversion Cloud SDK for Node.js provides a robust API that makes this task simple and scalable. In this guide you will see a complete asynchronous code sample, learn how to achieve the same result with cURL REST calls, set up the SDK, and apply best‑practice recommendations for reliable conversions.
Complete Code Example: Async PDF to DOCX Conversion in Node.JS
This example demonstrates how to perform an asynchronous PDF to DOCX conversion using GroupDocs.Conversion Cloud SDK for Node.js.
// PDF to DOCX conversion using GroupDocs.Conversion Cloud SDK for Node.js
const GroupDocsConversionCloud = require('groupdocs-conversion-cloud');
const path = require('path');
// -------------------- Configuration --------------------
const CLIENT_ID = process.env.GROUPDOCS_CLIENT_ID || 'YOUR_CLIENT_ID';
const CLIENT_SECRET = process.env.GROUPDOCS_CLIENT_SECRET || 'YOUR_CLIENT_SECRET';
// Initialize API client
const apiInstance = new GroupDocsConversionCloud.ConversionApi();
apiInstance.apiClient = new GroupDocsConversionCloud.ApiClient();
apiInstance.apiClient.basePath = 'https://api.groupdocs.cloud';
apiInstance.apiClient.authentications['JWT'].clientId = CLIENT_ID;
apiInstance.apiClient.authentications['JWT'].clientSecret = CLIENT_SECRET;
// -------------------- Conversion Logic --------------------
async function convertPdfToDocx() {
try {
// Input file information (must already be uploaded to GroupDocs Cloud storage)
const inputFileInfo = new GroupDocsConversionCloud.FileInfo();
inputFileInfo.filePath = path.normalize('input.pdf'); // generic path in cloud storage
// DOCX specific conversion options (optional, shown for demonstration)
const docxOptions = new GroupDocsConversionCloud.DocxConvertOptions();
docxOptions.preserveOriginalFormatting = true; // keep original PDF layout as much as possible
docxOptions.password = null; // if PDF is password protected, set it here
// Build conversion request
const convertRequest = new GroupDocsConversionCloud.ConvertDocumentRequest();
convertRequest.format = 'docx';
convertRequest.fileInfo = inputFileInfo;
convertRequest.outputPath = path.normalize('output.docx'); // result will be stored in cloud storage
convertRequest.options = docxOptions; // attach format‑specific options
// Perform conversion (async)
const conversionResult = await apiInstance.convertDocument(convertRequest);
// conversionResult contains the path of the generated file and other metadata
console.log('Conversion succeeded.');
console.log('Output file path:', conversionResult.path);
console.log('File size (bytes):', conversionResult.size);
} catch (error) {
// Detailed error handling
if (error.response && error.response.body) {
console.error('API error:', error.response.body);
} else {
console.error('Unexpected error:', error.message);
}
}
}
// -------------------- Execution --------------------
(async () => {
// Optional: set a timeout to avoid hanging indefinitely
const timeoutMs = 300000; // 5 minutes
const timeout = setTimeout(() => {
console.error('Conversion timed out after', timeoutMs / 1000, 'seconds');
process.exit(1);
}, timeoutMs);
await convertPdfToDocx();
clearTimeout(timeout);
// Graceful shutdown
process.exit(0);
})();
Note: This code example demonstrates the core functionality. Before using it in your project, make sure to update the file paths (
input.pdf,output.docx, etc.) to match your actual locations, verify that all required dependencies are installed, and test thoroughly in your development environment. If you encounter any issues, please refer to the official documentation or reach out to the support team for assistance.
Convert Documents Using cURL and the REST API
You can achieve the same PDF to DOCX conversion without writing code by calling the GroupDocs.Conversion Cloud REST endpoints directly. The steps below show how to obtain an access token, upload a PDF, start the conversion, and download the resulting DOCX file.
- Authenticate and get an access token
ReplaceYOUR_CLIENT_IDandYOUR_CLIENT_SECRETwith your credentials.
curl -X POST "https://api.groupdocs.cloud/v1.0/oauth2/token" \
-H "Content-Type: application/json" \
-d '{
"grant_type":"client_credentials",
"client_id":"YOUR_CLIENT_ID",
"client_secret":"YOUR_CLIENT_SECRET"
}'
The response contains access_token that you will use in subsequent calls.
- Upload the source PDF
curl -X PUT "https://api.groupdocs.cloud/v1.0/storage/file/input.pdf" \
-H "Authorization: Bearer YOUR_ACCESS_TOKEN" \
-H "Content-Type: application/pdf" \
--data-binary @./local/input.pdf
- Execute the conversion
curl -X POST "https://api.groupdocs.cloud/v1.0/conversion/convert" \
-H "Authorization: Bearer YOUR_ACCESS_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"format":"docx",
"fileInfo":{"filePath":"input.pdf"},
"outputPath":"output.docx",
"options":{"preserveOriginalFormatting":true}
}'
The response returns the path of the generated DOCX file.
- Download the converted DOCX
curl -X GET "https://api.groupdocs.cloud/v1.0/storage/file/output.docx" \
-H "Authorization: Bearer YOUR_ACCESS_TOKEN" \
-o ./local/output.docx
For more details on request payloads and additional options, see the official API documentation.
Breaking Down PDF to DOCX Conversion in Node.JS
Below is a concise walkthrough of the key parts of the asynchronous code sample.
Import and configure the client
const GroupDocsConversionCloud = require('groupdocs-conversion-cloud'); const apiInstance = new GroupDocsConversionCloud.ConversionApi();The
ConversionApiclass (API reference) is the entry point for all conversion operations.Set authentication credentials
apiInstance.apiClient.authentications['JWT'].clientId = CLIENT_ID; apiInstance.apiClient.authentications['JWT'].clientSecret = CLIENT_SECRET;JWT authentication secures each request to the cloud service.
Prepare the input file information
const inputFileInfo = new GroupDocsConversionCloud.FileInfo(); inputFileInfo.filePath = path.normalize('input.pdf');FileInfotells the API where the source PDF resides in GroupDocs Cloud storage.Configure DOCX‑specific options
const docxOptions = new GroupDocsConversionCloud.DocxConvertOptions(); docxOptions.preserveOriginalFormatting = true;DocxConvertOptionslets you keep the original layout and handle passwords if needed.Create and send the conversion request
const convertRequest = new GroupDocsConversionCloud.ConvertDocumentRequest(); convertRequest.format = 'docx'; convertRequest.fileInfo = inputFileInfo; convertRequest.outputPath = path.normalize('output.docx'); convertRequest.options = docxOptions; const conversionResult = await apiInstance.convertDocument(convertRequest);The
convertDocumentmethod performs the actual conversion and returns metadata such as the output path and file size.
Installing and Configuring GroupDocs.Conversion Cloud SDK for Node.JS
- Install the package
npm install groupdocs-conversion-cloud
The package is available from the public npm registry. See the download page for version details.
Prerequisites
- Node.js 12 or higher.
- A GroupDocs Cloud account with client ID and client secret.
Initialize the SDK in your project (excerpt from the full example)
const GroupDocsConversionCloud = require('groupdocs-conversion-cloud');
const apiInstance = new GroupDocsConversionCloud.ConversionApi();
apiInstance.apiClient.basePath = 'https://api.groupdocs.cloud';
Adjust the basePath if you use a regional endpoint.
Best Practices for High‑Performance Document Conversion
- Reuse the API client instead of creating a new instance for each conversion; this reduces authentication overhead.
- Enable streaming uploads for large PDFs to avoid loading the entire file into memory.
- Set a reasonable timeout (e.g., 5 minutes) to prevent hanging jobs while still allowing complex documents to finish.
- Preserve original formatting only when needed; disabling it can speed up conversion for simple text‑only PDFs.
- Monitor API usage limits in your GroupDocs account dashboard to avoid throttling during batch operations.
Conclusion
GroupDocs.Conversion Cloud SDK for Node.js makes PDF to DOCX conversion straightforward, whether you prefer a full‑featured library or direct REST calls with cURL. By following the async code sample, configuring the client correctly, and applying the performance tips above, you can integrate reliable document conversion into any Node.JS service. Remember to acquire a proper license for production use; pricing details are available on the product page, and a temporary license can be obtained from the temporary license page for evaluation.
FAQs
How does PDF to DOCX conversion in Node.JS handle complex layouts?
The SDK attempts to preserve original formatting by default. You can togglepreserveOriginalFormattinginDocxConvertOptionsto trade fidelity for speed. See the API reference for all options.What are the limits on file size for PDF to DOCX conversion?
The cloud service accepts files up to 200 MB for free accounts; larger files require an upgraded plan. Uploads are streamed, so memory usage on your server stays low.Can I convert multiple PDFs to DOCX in a single request?
The API processes one document per request, but you can loop over a list of files in Node.JS and run conversions in parallel, respecting your account’s concurrency limits.Is there a way to test the conversion locally without a paid license?
Yes, you can request a temporary evaluation license from the temporary license page. This provides full functionality for development and testing.
