0
# File Attachments
1
2
Embed files within PDF documents for comprehensive document packages, creating portable documents with associated resources.
3
4
## Capabilities
5
6
### File Embedding
7
8
Embed external files directly into PDF documents as attachments.
9
10
```javascript { .api }
11
/**
12
* Embed a file as an attachment in the PDF
13
* @param src - File source (path or Buffer)
14
* @param options - File attachment options
15
* @returns PDF reference for the embedded file
16
*/
17
file(src: string | Buffer, options?: FileOptions): PDFReference;
18
19
interface FileOptions {
20
/** Display name for the attachment */
21
name?: string;
22
/** MIME type of the file */
23
type?: string;
24
/** Description of the file */
25
description?: string;
26
/** Hide from embedded files list in viewer */
27
hidden?: boolean;
28
/** File creation date */
29
creationDate?: Date;
30
/** File modification date */
31
modifiedDate?: Date;
32
/** Relationship to the document */
33
relationship?: FileRelationship;
34
}
35
36
type FileRelationship =
37
| 'Alternative' // Alternative representation
38
| 'Data' // Data file
39
| 'Source' // Source file
40
| 'Supplement' // Supplementary file
41
| 'Unspecified'; // Unspecified relationship
42
```
43
44
**Usage Examples:**
45
46
```javascript
47
// Embed a simple file
48
doc.file('./attachments/data.xlsx', {
49
name: 'Quarterly Data.xlsx',
50
description: 'Q1 2024 sales data'
51
});
52
53
// Embed with full metadata
54
doc.file('./attachments/source.zip', {
55
name: 'Source Code.zip',
56
type: 'application/zip',
57
description: 'Complete source code for the project',
58
relationship: 'Source',
59
creationDate: new Date('2024-01-15'),
60
modifiedDate: new Date('2024-03-20')
61
});
62
63
// Embed from Buffer
64
const fileBuffer = fs.readFileSync('./data/report.docx');
65
doc.file(fileBuffer, {
66
name: 'Full Report.docx',
67
type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
68
description: 'Complete project report with appendices'
69
});
70
```
71
72
### Named File Management
73
74
Create named references to embedded files for later use.
75
76
```javascript { .api }
77
/**
78
* Add a named embedded file reference
79
* @param name - Reference name for the file
80
* @param fileRef - PDF reference to the embedded file
81
* @returns Document instance for chaining
82
*/
83
addNamedEmbeddedFile(name: string, fileRef: PDFReference): PDFDocument;
84
```
85
86
**Usage Examples:**
87
88
```javascript
89
// Embed file and create named reference
90
const dataFileRef = doc.file('./data/sales.csv', {
91
name: 'Sales Data.csv',
92
description: 'Monthly sales figures'
93
});
94
95
// Add named reference for later use
96
doc.addNamedEmbeddedFile('sales_data', dataFileRef);
97
98
// Reference in document content
99
doc.text('See attached sales data file for detailed figures.', 100, 100);
100
```
101
102
### File Type Detection
103
104
PDFKit can automatically detect common file types, but explicit specification is recommended.
105
106
**Common MIME Types:**
107
108
```javascript
109
// Document files
110
doc.file('./report.pdf', { type: 'application/pdf' });
111
doc.file('./document.docx', {
112
type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
113
});
114
115
// Spreadsheets
116
doc.file('./data.xlsx', {
117
type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
118
});
119
doc.file('./data.csv', { type: 'text/csv' });
120
121
// Images
122
doc.file('./photo.jpg', { type: 'image/jpeg' });
123
doc.file('./diagram.png', { type: 'image/png' });
124
125
// Archives
126
doc.file('./source.zip', { type: 'application/zip' });
127
doc.file('./backup.tar.gz', { type: 'application/gzip' });
128
129
// Text files
130
doc.file('./readme.txt', { type: 'text/plain' });
131
doc.file('./config.json', { type: 'application/json' });
132
```
133
134
### Multiple File Attachments
135
136
Organize multiple related files within a single PDF document.
137
138
**Usage Examples:**
139
140
```javascript
141
// Embed related project files
142
const projectFiles = [
143
{ path: './src/main.js', name: 'Main Script', desc: 'Primary application logic' },
144
{ path: './src/config.json', name: 'Configuration', desc: 'Application settings' },
145
{ path: './docs/api.md', name: 'API Documentation', desc: 'API reference guide' },
146
{ path: './tests/test.js', name: 'Test Suite', desc: 'Unit tests' }
147
];
148
149
projectFiles.forEach(file => {
150
doc.file(file.path, {
151
name: file.name,
152
description: file.desc,
153
relationship: file.path.includes('src/') ? 'Source' : 'Supplement'
154
});
155
});
156
157
// Create table of contents for attachments
158
doc.addPage()
159
.fontSize(16)
160
.text('Attached Files', 100, 100);
161
162
let y = 130;
163
projectFiles.forEach(file => {
164
doc.fontSize(12)
165
.text(`• ${file.name}: ${file.desc}`, 120, y);
166
y += 20;
167
});
168
```
169
170
### Attachment Security and Compliance
171
172
Handle file attachments with security and compliance considerations.
173
174
```javascript { .api }
175
interface SecureFileOptions extends FileOptions {
176
/** Mark file as hidden from casual viewing */
177
hidden?: boolean;
178
/** Specify security relationship */
179
relationship?: 'Source' | 'Data' | 'Alternative';
180
/** Add compliance metadata */
181
compliance?: {
182
standard?: string;
183
version?: string;
184
checksum?: string;
185
};
186
}
187
```
188
189
**Usage Examples:**
190
191
```javascript
192
// Embed sensitive data with appropriate marking
193
doc.file('./sensitive/audit-trail.log', {
194
name: 'Audit Trail',
195
description: 'System audit log (restricted access)',
196
hidden: true,
197
relationship: 'Data',
198
type: 'text/plain'
199
});
200
201
// Compliance-related attachments
202
doc.file('./compliance/validation-report.pdf', {
203
name: 'Validation Report',
204
description: 'FDA validation documentation',
205
relationship: 'Supplement',
206
compliance: {
207
standard: 'FDA 21 CFR Part 11',
208
version: '2.1',
209
checksum: 'sha256:abc123...'
210
}
211
});
212
```
213
214
## File Attachment Patterns
215
216
### Documentation Package
217
218
```javascript
219
// Create comprehensive documentation package
220
const docPackage = [
221
{ file: './docs/user-guide.pdf', name: 'User Guide', relationship: 'Supplement' },
222
{ file: './docs/api-reference.pdf', name: 'API Reference', relationship: 'Supplement' },
223
{ file: './examples/samples.zip', name: 'Code Examples', relationship: 'Source' },
224
{ file: './data/test-data.json', name: 'Test Data', relationship: 'Data' }
225
];
226
227
// Add cover page explaining attachments
228
doc.fontSize(20).text('Document Package', 100, 100);
229
doc.fontSize(12).text('This PDF contains the following attached files:', 100, 140);
230
231
let y = 170;
232
docPackage.forEach(item => {
233
// Embed the file
234
doc.file(item.file, {
235
name: item.name,
236
relationship: item.relationship
237
});
238
239
// List in document
240
doc.text(`• ${item.name}`, 120, y);
241
y += 20;
242
});
243
```
244
245
### Data Analysis Report
246
247
```javascript
248
// Embed data files with analysis report
249
const analysisFiles = {
250
rawData: './data/raw-data.csv',
251
processedData: './data/processed-data.xlsx',
252
code: './analysis/analysis-script.py',
253
config: './analysis/config.yaml'
254
};
255
256
// Embed all related files
257
Object.entries(analysisFiles).forEach(([key, path]) => {
258
doc.file(path, {
259
name: key.replace(/([A-Z])/g, ' $1').replace(/^./, str => str.toUpperCase()),
260
description: `${key} file for the analysis`,
261
relationship: key === 'code' ? 'Source' : 'Data'
262
});
263
});
264
265
// Reference in report
266
doc.text('Data Analysis Report', 100, 100);
267
doc.text('All source data and analysis code are attached to this document.', 100, 130);
268
```
269
270
### Archive and Backup
271
272
```javascript
273
// Create archive with backup files
274
const backupDate = new Date();
275
const archiveRef = doc.file('./backup/system-backup.tar.gz', {
276
name: `System Backup ${backupDate.toISOString().split('T')[0]}`,
277
description: 'Complete system backup archive',
278
type: 'application/gzip',
279
creationDate: backupDate,
280
relationship: 'Data'
281
});
282
283
// Add to named files for reference
284
doc.addNamedEmbeddedFile('latest_backup', archiveRef);
285
```
286
287
## Best Practices
288
289
### File Organization
290
291
- Use descriptive names for attachments
292
- Include file extensions in names for clarity
293
- Organize related files with consistent naming
294
- Provide meaningful descriptions
295
296
### Metadata Management
297
298
- Always specify MIME types explicitly
299
- Include creation and modification dates
300
- Use appropriate relationship types
301
- Consider compliance requirements
302
303
### Performance Considerations
304
305
- Large files increase PDF size significantly
306
- Consider compression for text-based files
307
- Use hidden flag for auxiliary files
308
- Limit number of attachments for better performance