0
# PDF Conversion
1
2
The Convert interface provides both single-page and bulk conversion capabilities with three output formats: image files, base64 strings, and buffers.
3
4
## Capabilities
5
6
### Single Page Conversion
7
8
Convert individual PDF pages with different output formats based on the responseType option.
9
10
```typescript { .api }
11
/**
12
* Convert a specific PDF page (defaults to page 1, image output)
13
* @param pages - Page number to convert (1-indexed), defaults to 1
14
* @returns Promise resolving to WriteImageResponse
15
*/
16
(pages?: number): Promise<WriteImageResponse>;
17
18
/**
19
* Convert a specific PDF page to image file
20
* @param pages - Page number to convert (1-indexed)
21
* @param options - Conversion options with responseType
22
* @returns Promise resolving to WriteImageResponse
23
*/
24
(pages: number, options: { responseType?: undefined }): Promise<WriteImageResponse>;
25
(pages: number, options: { responseType: 'image' }): Promise<WriteImageResponse>;
26
27
/**
28
* Convert a specific PDF page to base64 string
29
* @param pages - Page number to convert (1-indexed)
30
* @param options - Conversion options with responseType set to 'base64'
31
* @returns Promise resolving to ToBase64Response
32
*/
33
(pages: number, options: { responseType: 'base64' }): Promise<ToBase64Response>;
34
35
/**
36
* Convert a specific PDF page to buffer
37
* @param pages - Page number to convert (1-indexed)
38
* @param options - Conversion options with responseType set to 'buffer'
39
* @returns Promise resolving to BufferResponse
40
*/
41
(pages: number, options: { responseType: 'buffer' }): Promise<BufferResponse>;
42
```
43
44
**Usage Examples:**
45
46
```typescript
47
import { fromPath } from "pdf2pic";
48
49
const convert = fromPath("/path/to/document.pdf", {
50
format: "jpg",
51
quality: 90,
52
width: 1200,
53
height: 800
54
});
55
56
// Convert page 1 to image file (default behavior)
57
const imageResult = await convert(1);
58
console.log(`Saved to: ${imageResult.path}`);
59
console.log(`File size: ${imageResult.fileSize} KB`);
60
61
// Convert page 2 to base64
62
const base64Result = await convert(2, { responseType: "base64" });
63
console.log(`Base64 length: ${base64Result.base64.length}`);
64
console.log(`Image size: ${base64Result.size}`);
65
66
// Convert page 3 to buffer for processing
67
const bufferResult = await convert(3, { responseType: "buffer" });
68
const imageBuffer = bufferResult.buffer;
69
console.log(`Buffer size: ${imageBuffer.length} bytes`);
70
```
71
72
### Bulk Conversion
73
74
Convert multiple PDF pages in a single operation with automatic batching for performance optimization.
75
76
```typescript { .api }
77
interface BulkConvert {
78
/**
79
* Convert multiple pages to image files (default behavior)
80
* @param pages - Page numbers to convert, or -1 for all pages
81
* @returns Promise resolving to array of WriteImageResponse
82
*/
83
(pages?: number | number[]): Promise<WriteImageResponse[]>;
84
(pages: number | number[], options: { responseType?: undefined }): Promise<WriteImageResponse[]>;
85
(pages: number | number[], options: { responseType: 'image' }): Promise<WriteImageResponse[]>;
86
87
/**
88
* Convert multiple pages to base64 strings
89
* @param pages - Page numbers to convert, or -1 for all pages
90
* @param options - Conversion options with responseType set to 'base64'
91
* @returns Promise resolving to array of ToBase64Response
92
*/
93
(pages: number | number[], options: { responseType: 'base64' }): Promise<ToBase64Response[]>;
94
95
/**
96
* Convert multiple pages to buffers
97
* @param pages - Page numbers to convert, or -1 for all pages
98
* @param options - Conversion options with responseType set to 'buffer'
99
* @returns Promise resolving to array of BufferResponse
100
*/
101
(pages: number | number[], options: { responseType: 'buffer' }): Promise<BufferResponse[]>;
102
}
103
```
104
105
**Usage Examples:**
106
107
```typescript
108
import { fromBuffer } from "pdf2pic";
109
110
const convert = fromBuffer(pdfBuffer, {
111
format: "png",
112
width: 800,
113
savePath: "./output"
114
});
115
116
// Convert specific pages to image files
117
const specificPages = await convert.bulk([1, 3, 5], { responseType: "image" });
118
specificPages.forEach(result => {
119
console.log(`Page ${result.page}: ${result.name} (${result.fileSize} KB)`);
120
});
121
122
// Convert all pages to base64 (-1 means all pages)
123
const allPagesBase64 = await convert.bulk(-1, { responseType: "base64" });
124
console.log(`Converted ${allPagesBase64.length} pages to base64`);
125
126
// Convert range of pages to buffers
127
const pageRange = [1, 2, 3, 4, 5];
128
const bufferResults = await convert.bulk(pageRange, { responseType: "buffer" });
129
bufferResults.forEach((result, index) => {
130
console.log(`Page ${result.page} buffer: ${result.buffer.length} bytes`);
131
});
132
133
// Convert first 10 pages (or all if PDF has fewer)
134
const firstTenPages = Array.from({ length: 10 }, (_, i) => i + 1);
135
const results = await convert.bulk(firstTenPages);
136
```
137
138
### Configuration Methods
139
140
Methods for modifying conversion settings after initialization.
141
142
```typescript { .api }
143
/**
144
* Apply current options to the GraphicsMagick instance
145
* Call this after modifying any settings to ensure they take effect
146
*/
147
setOptions(): void;
148
149
/**
150
* Configure the GraphicsMagick backend
151
* @param gmClass - GraphicsMagick class configuration
152
* - boolean: true for ImageMagick, false for GraphicsMagick
153
* - string: custom path to graphics processing binary
154
*/
155
setGMClass(gmClass: string | boolean): void;
156
```
157
158
**Usage Examples:**
159
160
```typescript
161
import { fromPath } from "pdf2pic";
162
163
const convert = fromPath("/path/to/document.pdf");
164
165
// Switch to ImageMagick backend
166
convert.setGMClass(true);
167
convert.setOptions(); // Apply the change
168
169
// Or specify custom binary path
170
convert.setGMClass("/usr/local/bin/gm");
171
convert.setOptions();
172
173
// Convert with new settings
174
const result = await convert(1);
175
```
176
177
## Response Format Details
178
179
### WriteImageResponse
180
181
Returned when converting to image files (responseType: 'image' or default).
182
183
```typescript { .api }
184
interface WriteImageResponse {
185
name?: string; // Generated filename (e.g., "page.1.png")
186
fileSize?: number; // File size in kilobytes
187
path?: string; // Full path to saved image file
188
size?: string; // Image dimensions (e.g., "800x600")
189
page?: number; // Page number that was converted
190
}
191
```
192
193
### ToBase64Response
194
195
Returned when converting to base64 strings (responseType: 'base64').
196
197
```typescript { .api }
198
interface ToBase64Response {
199
base64?: string; // Base64-encoded image data
200
size?: string; // Image dimensions (e.g., "800x600")
201
page?: number; // Page number that was converted
202
}
203
```
204
205
### BufferResponse
206
207
Returned when converting to buffers (responseType: 'buffer').
208
209
```typescript { .api }
210
interface BufferResponse {
211
buffer?: Buffer; // Raw image data as Node.js Buffer
212
size?: string; // Image dimensions (e.g., "800x600")
213
page?: number; // Page number that was converted
214
}
215
```
216
217
## Performance Considerations
218
219
### Bulk Conversion Batching
220
221
The bulk conversion method automatically processes pages in batches of 10 to optimize memory usage and prevent system overload:
222
223
```typescript
224
// Internally batches large requests
225
const manyPages = Array.from({ length: 100 }, (_, i) => i + 1);
226
const results = await convert.bulk(manyPages); // Processed in 10 batches of 10 pages each
227
```
228
229
### Memory Management
230
231
- **Image Files**: Most memory-efficient for large batches
232
- **Base64**: Moderate memory usage, good for web APIs
233
- **Buffers**: Highest memory usage, keep in memory only as needed
234
235
### Error Handling
236
237
```typescript
238
import { fromPath } from "pdf2pic";
239
240
const convert = fromPath("/path/to/document.pdf");
241
242
try {
243
// This will throw if page number is invalid
244
const result = await convert(0); // Pages are 1-indexed
245
} catch (error) {
246
if (error.message.includes("Page number should be more than or equal 1")) {
247
console.error("Invalid page number provided");
248
}
249
}
250
251
try {
252
// This will handle pages that don't exist gracefully
253
const results = await convert.bulk([1, 2, 999]); // Page 999 may not exist
254
console.log(`Successfully converted ${results.length} pages`);
255
} catch (error) {
256
console.error("Bulk conversion failed:", error.message);
257
}
258
```