-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Add support for embedded files and file attachment annotations #1226
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 1 commit
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,42 @@ | ||
| const PDFDocument = require('../'); | ||
| const fs = require('fs'); | ||
| const path = require('path'); | ||
|
|
||
| const doc = new PDFDocument({ pdfVersion: '1.4' }); | ||
|
|
||
| doc.pipe(fs.createWriteStream('attachment.pdf')); | ||
|
|
||
| doc.info['Title'] = 'Attachment Test'; | ||
|
|
||
| // add an embedded file from file system | ||
| doc.file(path.join(__dirname, 'images', 'test.png'), { | ||
| name: 'test.png', | ||
| type: 'image/png', | ||
| description: 'this is a test image' | ||
| }); | ||
|
|
||
| // add some text | ||
| doc.text(`This PDF contains three text files: | ||
| Two file attachment annotations and one embedded file. | ||
| If you can see them (not every PDF viewer supports embedded files), | ||
| hover over the paperclip to see its description!`); | ||
|
|
||
| // add a file attachment annotation | ||
| // first, declare the file to be attached | ||
| const file = { | ||
| src: Buffer.from('buffered input!'), | ||
| name: 'embedded.txt', | ||
| creationDate: new Date(2020, 3, 1) | ||
| }; | ||
| // then, add the annotation | ||
| doc.fileAttachmentAnnotation(100, 150, 10, doc.currentLineHeight(), file); | ||
|
|
||
| // declared files can be reused, but they will show up separately in the PDF Viewer's attachments panel | ||
| // we're going to use the paperclip icon for this one together with a short description | ||
| // be aware that some PDF Viewers may not render the icon correctly — or not at all | ||
| doc.fileAttachmentAnnotation(150, 150, 10, doc.currentLineHeight(), file, { | ||
| Name: 'Paperclip', | ||
| Contents: 'Paperclip attachment' | ||
| }); | ||
|
|
||
| doc.end(); |
Binary file not shown.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,53 @@ | ||
| # Attachments in PDFKit | ||
|
|
||
| ## Embedded Files | ||
|
|
||
| Embedded files make it possible to embed any external file into a PDF. | ||
| Adding an embedded file is as simple as calling the `file` method and specifying a filepath. | ||
|
|
||
| doc.file(path.join(__dirname, 'example.txt')) | ||
|
|
||
| It is also possible to embed data directly as a Buffer, ArrayBuffer or base64 encoded string. | ||
| If you are embedding data, it is recommended you also specify a filename like this: | ||
|
|
||
| doc.file(Buffer.from('this will be a text file'), { name: 'example.txt' }) | ||
|
|
||
| When embedding a data URL, the `type` option will be set to the data URL's MIME type automatically: | ||
|
|
||
| doc.file('data:text/plain;base64,YmFzZTY0IHN0cmluZw==', { name: 'base64.txt' }) | ||
|
|
||
| There are a few other options for `doc.file`: | ||
|
|
||
| * `name` - specify the embedded file's name | ||
| * `type` - specify the embedded file's subtype as a [MIME-Type](https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types/Common_types) | ||
| * `description` - add descriptive text for the embedded file | ||
| * `hidden` - if true, do not show file in the list of embedded files | ||
| * `creationDate` - override the date and time the file was created | ||
| * `modifiedDate` - override the date and time the file was last updated | ||
|
|
||
| If you are attaching a file from your file system, creationDate and modifiedDate will be set to the source file's creationDate and modifiedDate. | ||
|
|
||
| Setting the `hidden` option prevents this file from showing up in the pdf viewer's attachment panel. | ||
| While this may not be very useful for embedded files, it is absolutely necessary for the file attachment annotations, to prevent them from showing up twice in the attachment panel. | ||
|
|
||
| ## File Attachment Annotations | ||
|
|
||
| A file attachment annotation contains a reference to an embedded file that can be placed anywhere in the document. | ||
| File attachment annotations show up in your reader's annotation panel as well as the attachment panel. | ||
|
|
||
| In order to add a file attachment annotation, you should first read the chapter on annotations. | ||
| Like other annotations, you specify position and size with `x`, `y`, `width` and `height`, unlike other annotations you must also specify a file object. | ||
| The file object may contain the same options as `doc.file` in the previous section with the addition of the source file or buffered data in `src`. | ||
|
|
||
| Here is an example of adding a file attachment annotation: | ||
|
|
||
| const file = { | ||
| src: path.join(__dirname, 'example.txt'), | ||
| name: 'example.txt', | ||
| description: 'file annotation description' | ||
| } | ||
| const options = { Name: 'Paperclip' } | ||
|
|
||
| doc.fileAttachmentAnnotation(100, 100, 100, 100, file, options) | ||
|
|
||
| The annotation's appearance may be changed by setting the `Name` option to one of the three predefined icons `GraphPush`, `Paperclip` or `Push` (default value). |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Binary file not shown.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,118 @@ | ||
| const fs = require('fs'); | ||
| const { createHash } = require('crypto'); | ||
|
|
||
| export default { | ||
| /** | ||
| * Embed contents of `src` in PDF | ||
| * @param {Buffer | ArrayBuffer | string} src input Buffer, ArrayBuffer, base64 encoded string or path to file | ||
| * @param {object} options | ||
| * * options.name: filename to be shown in PDF, will use `src` if none set | ||
| * * options.type: filetype to be shown in PDF | ||
| * * options.description: description to be shown in PDF | ||
| * * options.hidden: if true, do not add attachment to EmbeddedFiles dictionary. Useful for file attachment annotations | ||
| * * options.creationDate: override creation date | ||
| * * options.modifiedDate: override modified date | ||
| * @returns filespec reference | ||
| */ | ||
| file(src, options = {}) { | ||
| options.name = options.name || src; | ||
|
|
||
| const refBody = { | ||
| Type: 'EmbeddedFile', | ||
| Params: {} | ||
| }; | ||
| let data; | ||
|
|
||
| if (!src) { | ||
| throw new Error('No src specified'); | ||
| } | ||
| if (Buffer.isBuffer(src)) { | ||
| data = src; | ||
| } else if (src instanceof ArrayBuffer) { | ||
| data = Buffer.from(new Uint8Array(src)); | ||
| } else { | ||
| let match; | ||
| if ((match = /^data:(.*);base64,(.*)$/.exec(src))) { | ||
| if (match[1]) { | ||
| refBody.Subtype = match[1].replace('/', '#2F'); | ||
| } | ||
| data = Buffer.from(match[2], 'base64'); | ||
| } else { | ||
| data = fs.readFileSync(src); | ||
| if (!data) { | ||
| throw new Error(`Could not read contents of file at filepath ${src}`); | ||
| } | ||
|
|
||
| // update CreationDate and ModDate | ||
| const { birthtime, ctime } = fs.statSync(src); | ||
| refBody.Params.CreationDate = birthtime; | ||
| refBody.Params.ModDate = ctime; | ||
| } | ||
| } | ||
|
|
||
| // override creation date and modified date | ||
| if (options.creationDate instanceof Date) { | ||
| refBody.Params.CreationDate = options.creationDate; | ||
| } | ||
| if (options.modifiedDate instanceof Date) { | ||
| refBody.Params.ModDate = options.modifiedDate; | ||
| } | ||
| // add optional subtype | ||
| if (options.type) { | ||
| refBody.Subtype = options.type.replace('/', '#2F'); | ||
| } | ||
|
|
||
| // add checksum and size information | ||
| const checksum = createHash('md5') | ||
| .update(data) | ||
| .digest('hex'); | ||
| refBody.Params.CheckSum = new String(checksum); | ||
| refBody.Params.Size = data.byteLength; | ||
|
|
||
| // save some space when embedding the same file again | ||
| // if a file with the same name and metadata exists, reuse its reference | ||
| let ref; | ||
| if (!this._fileRegistry) this._fileRegistry = {}; | ||
| let file = this._fileRegistry[options.name]; | ||
| if (file && isEqual(refBody, file)) { | ||
| ref = file.ref; | ||
| } else { | ||
| ref = this.ref(refBody); | ||
| ref.end(data); | ||
|
|
||
| this._fileRegistry[options.name] = { ...refBody, ref }; | ||
| } | ||
| // add filespec for embedded file | ||
| const fileSpecBody = { | ||
| Type: 'Filespec', | ||
| F: new String(options.name), | ||
| EF: { F: ref }, | ||
| UF: new String(options.name) | ||
| }; | ||
| if (options.description) { | ||
| fileSpecBody.Desc = new String(options.description); | ||
| } | ||
| const filespec = this.ref(fileSpecBody); | ||
| filespec.end(); | ||
|
|
||
| if (!options.hidden) { | ||
| this.addNamedEmbeddedFile(options.name, filespec); | ||
| } | ||
|
|
||
| return filespec; | ||
| } | ||
| }; | ||
|
|
||
| /** check two embedded file metadata objects for equality */ | ||
| function isEqual(a, b) { | ||
| if ( | ||
| a.Subtype !== b.Subtype || | ||
| a.Params.CheckSum.toString() !== b.Params.CheckSum.toString() || | ||
| a.Params.Size !== b.Params.Size || | ||
| a.Params.CreationDate !== b.Params.CreationDate || | ||
| a.Params.ModDate !== b.Params.ModDate | ||
| ) { | ||
| return false; | ||
| } | ||
| return true; | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.