-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdirect_method.ts
More file actions
149 lines (119 loc) · 4.29 KB
/
direct_method.ts
File metadata and controls
149 lines (119 loc) · 4.29 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
/**
* Direct Method Example
*
* This example demonstrates how to use the Nutrient DWS TypeScript Client
* with direct method calls for document processing operations.
*/
import { NutrientClient } from '@nutrient-sdk/dws-client-typescript';
import * as fs from 'fs';
import * as path from 'path';
import * as dotenv from 'dotenv';
// Load environment variables from .env file
dotenv.config();
// Check if API key is provided
if (!process.env.NUTRIENT_API_KEY) {
console.error('Error: NUTRIENT_API_KEY is not set in .env file');
process.exit(1);
}
// Initialize the client with API key
const client = new NutrientClient({
apiKey: process.env.NUTRIENT_API_KEY
});
// Define paths
const assetsDir = path.join(__dirname, '../assets');
const outputDir = path.join(__dirname, '../output');
// Ensure output directory exists
if (!fs.existsSync(outputDir)) {
fs.mkdirSync(outputDir, { recursive: true });
}
// Example 1: Convert a document
async function convertDocument() {
console.log('Example 1: Converting DOCX to PDF');
try {
const docxPath = path.join(assetsDir, 'sample.docx');
const result = await client.convert(docxPath, 'pdf');
// Save the result to the output directory
const outputPath = path.join(outputDir, 'converted-document.pdf');
fs.writeFileSync(outputPath, Buffer.from(result.buffer));
console.log(`Conversion successful. Output saved to: ${outputPath}`);
console.log(`MIME type: ${result.mimeType}`);
return outputPath;
} catch (error) {
console.error('Conversion failed:', error);
throw error;
}
}
// Example 2: Extract text from a document
async function extractText(filePath: string) {
console.log('\nExample 2: Extracting text from PDF');
try {
const result = await client.extractText(filePath);
// Save the extracted text to the output directory
const outputPath = path.join(outputDir, 'extracted-text.json');
fs.writeFileSync(outputPath, JSON.stringify(result.data, null, 2));
// Display a sample of the extracted text
const textSample = result.data.pages![0].plainText!.substring(0, 100) + '...';
console.log(`Text extraction successful. Output saved to: ${outputPath}`);
console.log(`Text sample: ${textSample}`);
return outputPath;
} catch (error) {
console.error('Text extraction failed:', error);
throw error;
}
}
// Example 3: Add a watermark to a document
async function addWatermark(filePath: string) {
console.log('\nExample 3: Adding watermark to PDF');
try {
const result = await client.watermarkText(filePath, 'CONFIDENTIAL', {
opacity: 0.5,
fontColor: '#FF0000',
rotation: 45,
width: { value: 50, unit: "%" }
});
// Save the watermarked document to the output directory
const outputPath = path.join(outputDir, 'watermarked-document.pdf');
fs.writeFileSync(outputPath, Buffer.from(result.buffer));
console.log(`Watermarking successful. Output saved to: ${outputPath}`);
return outputPath;
} catch (error) {
console.error('Watermarking failed:', error);
throw error;
}
}
// Example 4: Merge multiple documents
async function mergeDocuments() {
console.log('\nExample 4: Merging documents');
try {
// Create a second PDF
const pdfPath = path.join(assetsDir, 'sample.pdf');
// Get the converted PDF from Example 1
const convertedPdfPath = path.join(outputDir, 'converted-document.pdf');
// Merge the documents
const result = await client.merge([convertedPdfPath, pdfPath]);
// Save the merged document to the output directory
const outputPath = path.join(outputDir, 'merged-document.pdf');
fs.writeFileSync(outputPath, Buffer.from(result.buffer));
console.log(`Merging successful. Output saved to: ${outputPath}`);
return outputPath;
} catch (error) {
console.error('Merging failed:', error);
throw error;
}
}
// Run all examples
async function runExamples() {
try {
console.log('Starting direct method examples...\n');
// Run the examples in sequence
const convertedPdfPath = await convertDocument();
await extractText(convertedPdfPath);
await addWatermark(convertedPdfPath);
await mergeDocuments();
console.log('\nAll examples completed successfully!');
} catch (error) {
console.error('\nExamples failed:', error);
}
}
// Execute the examples
runExamples();