Solvedpdf lib Add metadata

Hello,

Is it possible to add metadata to the PDF?

Thanks!

25 Answers

✔️Accepted Answer

Version 1.2.0 is now published.

It contains several new methods on PDFDocument to easily add metadata to documents:

  • PDFDocument.setTitle(string)
  • PDFDocument.setAuthor(string)
  • PDFDocument.setSubject(string)
  • PDFDocument.setKeywords(string[])
  • PDFDocument.setProducer(string)
  • PDFDocument.setCreator(string)
  • PDFDocument.setCreationDate(Date)
  • PDFDocument.setModificationDate(Date)

The full release notes are available here.

You can install this new version with npm:

npm install pdf-lib@1.2.0

It's also available on unpkg:

Other Answers:

Hello @erjimmmy. You can add metadata to PDFs with pdf-lib. There isn't currently a nice high level API for it, though. So the code is a bit ugly, but it works nonetheless!

(Note that PDFs store metadata in XMP format. The XMP standard supports a wide variety of options, and even allows you to add your own custom tags.)

Here's a snippet that creates a PDF and adds metadata to it with a couple details omitted for brevity:

...

const addMetadataToDoc = (pdfDoc, options) => {
  const metadataXML = `
    <?xpacket begin="" id="W5M0MpCehiHzreSzNTczkc9d"?>
      <x:xmpmeta xmlns:x="adobe:ns:meta/" x:xmptk="Adobe XMP Core 5.2-c001 63.139439, 2010/09/27-13:37:26        ">
        <rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">

          <rdf:Description rdf:about="" xmlns:dc="http://purl.org/dc/elements/1.1/">
            <dc:format>application/pdf</dc:format>
            <dc:creator>
              <rdf:Seq>
                <rdf:li>${options.author}</rdf:li>
              </rdf:Seq>
            </dc:creator>
            <dc:title>
               <rdf:Alt>
                  <rdf:li xml:lang="x-default">${options.title}</rdf:li>
               </rdf:Alt>
            </dc:title>
            <dc:subject>
              <rdf:Bag>
                ${options.keywords
                  .map((keyword) => `<rdf:li>${keyword}</rdf:li>`)
                  .join('\n')}
              </rdf:Bag>
            </dc:subject>
          </rdf:Description>

          <rdf:Description rdf:about="" xmlns:xmp="http://ns.adobe.com/xap/1.0/">
            <xmp:CreatorTool>${options.creatorTool}</xmp:CreatorTool>
            <xmp:CreateDate>${options.documentCreationDate.toISOString()}</xmp:CreateDate>
            <xmp:ModifyDate>${options.documentModificationDate.toISOString()}</xmp:ModifyDate>
            <xmp:MetadataDate>${options.metadataModificationDate.toISOString()}</xmp:MetadataDate>
          </rdf:Description>

          <rdf:Description rdf:about="" xmlns:pdf="http://ns.adobe.com/pdf/1.3/">
            <pdf:Subject>${options.subject}</pdf:Subject>
            <pdf:Producer>${options.producer}</pdf:Producer>
          </rdf:Description>

        </rdf:RDF>
      </x:xmpmeta>
      ${whitespacePadding}
    <?xpacket end="w"?>
  `.trim();

  const metadataStreamDict = PDFDictionary.from(
    {
      Type: PDFName.from('Metadata'),
      Subtype: PDFName.from('XML'),
      Length: PDFNumber.fromNumber(metadataXML.length),
    },
    pdfDoc.index,
  );

  const metadataStream = PDFRawStream.from(
    metadataStreamDict,
    typedArrayFor(metadataXML),
  );

  const metadataStreamRef = pdfDoc.register(metadataStream);

  pdfDoc.catalog.set('Metadata', metadataStreamRef);
};

const pdfDoc = PDFDocumentFactory.create();
const [TimesRomanFont] = pdfDoc.embedStandardFont('Times-Roman');
const [HelveticaFont] = pdfDoc.embedStandardFont('Helvetica');

const contentStream = pdfDoc.createContentStream( ... );

const page = pdfDoc
  .createPage([500, 600])
  .addFontDictionary('Helvetica', HelveticaFont)
  .addFontDictionary('TimesRoman', TimesRomanFont)
  .addContentStreams(pdfDoc.register(contentStream));

pdfDoc.addPage(page);

addMetadataToDoc(pdfDoc, {
  author: 'Humpty Dumpty',
  title: 'The Life of an Egg',
  subject: 'An Epic Tale of Woe',
  keywords: ['eggs', 'wall', 'fall', 'king', 'horses', 'men'],
  producer: `Your App's Name Goes Here`,
  creatorTool:
    'pdf-lib pdf-lib_version_goes_here (https://github.com/Hopding/pdf-lib)',
  documentCreationDate: new Date(),
  documentModificationDate: new Date(),
  metadataModificationDate: new Date(),
});

const pdfBytes = PDFDocumentWriter.saveToBytes(pdfDoc);

  • Here is the resulting PDF file: the_life_of_an_egg.pdf
  • And here is a screenshot of the resulting PDF in Acrobat, with the "File -> Properties" window opened:
    screen shot 2018-12-17 at 8 52 09 am
  • Finally, here is the complete Node.js script (the .txt extension is to make GitHub happy): humpty_dumpty.js.txt

Please let me know if this is what you're looking for!

Related Issues:

6
pdf lib [Feature Request]: opacity option for drawText() method
Hello @akaanish! pdf-lib does not currently provide an API for changing text/shape/image opacity How...
5
pdf lib Add metadata
Version 1.2.0 is now published Hello Is it possible to add metadata to the PDF? Thanks! ...
4
pdf lib v1.0.0 Beta
Hello again everybody! I've just finished creating a project site for pdf-lib: https://pdf-lib.js.or...
63
copy webpack plugin New files are not being copied in watch-mode
I found the root cause after reading thru change log and code of clean-webpack-plugin Since clean-we...
44
copy webpack plugin Does not copy files to actual output folder when webpack-dev-server is used
I had the same problem with v4.0.1 (files not copied to output folder) After seeing the Breaking Cha...
13
copy webpack plugin [Feature] Support manifest file
I do thank you a lot for the code that removes the hash (see under this text) from the file names ...
11
node fs extra Documentation for copy() options.filter function
@stephen-last You may have the same puzzle as I had When copying directory and use the filter to inc...
6
pandoc Specify command-line options using YAML metadata
+1 I use pandoc for a lot of things but one set is producing brief write ups letters and envelopes T...
21
oni Oni does not launch Neovim.
Fixed by creating ~/.config/oni/config.js with following content: Oni Version: 0.3.6 Neovim Version ...
3831
axios Axios catch error returns javascript error not server response
I have exactly the same environment Try this: Modify from console.log(error) to console.log(error.re...
2346
jest Bug: Watch mode on Linux causes a ENOSPC Node.js error
From my findings its not related to Jest at all On Linux (or Mac) we have a max number of system wat...
1975
react RFClarification: why is setState asynchronous?
So here’s a few thoughts This is not a complete response by any means but maybe this is still more h...
1745
react Preventing rerenders with React.memo and useContext hook.
This is working as designed There is a longer discussion about this in #14110 if you're curious ...
1400
TypeScript Quick fix for 'unions can't be used in index signatures, use a mapped object type instead'
You can do this: Though Bar has no index signature (i.e. you can't then do (obj as Bar)[value as Foo...
811
webpack Cannot assign to read only property 'exports' of object '#<Object>' (mix require and export)
The code above is ok You can mix require and export You can't mix import and module.exports. ...
778
yarn Yarn Debian key expiry date updated (EXPKEYSIG 23E7166788B63E1E)
sudo apt-key adv --refresh-keys --keyserver keyserver.ubuntu.com also works to fix this issue for ma...
727
webpack How to exclude node_modules but one
@borm: a solution: Subj as example I create some module in another folder ( /projects/MY_MODULE ) MY...
720
yarn GPG error: https://dl.yarnpkg.com/debian stable InRelease NO_PUBKEY E074D16EB6FF4DE3
Doing curl -sS https://dl.yarnpkg.com/debian/pubkey.gpg | sudo apt-key add - again was enough. ...
611
react React Fire: Modernizing React DOM
I love every of these points except the className change For latest status see an update from June 5...
608
angular Angular5.x lazyLoad problem, undefined is not a function
For others that find this issue via Google as i did: I had the same problem when trying to lazy load...
595
react starter kit How to call child component method from parent?
For example you can use Refs to Components approach like so: Demo: https://jsfiddle.net/frenzzy/z9c4...
561
react How should we set up apps for HMR now that Fast Refresh replaces react-hot-loader?
Okay here goes What Is Fast Refresh? It's a reimplementation of hot reloading with full support from...
548
svgo no such file or directory .svgo.yml
I noticed this problem with Yarn after someone had run yarn clean Deleting the .yarnclean file delet...
521
ant motion 模版代码下载下来导入到dva搭建的项目里面,启动时报错(npm start)
开启 JavaScript 就可以了 你好,我下载的Home项目引入到项目工程里面,为了方便,我全部放到了components下面,引入和基本流程没有问题。在家里的win10上面启动没有报错,在win...
516
react native gesture handler Unsupported top level event type "onGestureHandlerStateChange" dispatched
Because my navigators were created asynchronously the handler was registered too late and thus throw...
506
electron Requiring electron outside of main.js causes a TypeError
For anyone encountering this problem in the future and reading this thread Electron version: 1.3.5 O...
499
babel ReferenceError regeneratorRuntime is not defined
I had this issue using rollup with babel I just used this babel config to resolve it : ...
488
webpack nodejs 17: digital envelope routines::unsupported
workaround: Bug report What is the current behavior? Other relevant information: webpack version: 5....
474
meteor [1.4.2.1] Error: ENFILE: file table overflow
I was getting the same after an upgrade to macOS Sierra Turns out macOS have a harsh limit on number...
473
webpack TypeError: Data must be a string or a buffer
Here is a workaround to help you to find the wrong import Using the latest 2.2.0 release although th...
429
vue router how to change document.title in vue-router?
Hi thanks for filling this issue You can simply define title in route's meta I really want set title...
425
babel eslint ESLint: 2.10.0 - Parsing error: Unexpected token =
parser: babel-eslint is OK! I'm using: and getting the following error: Parsing error: Unexpected to...
425
jest Error in Async Example: ReferenceError: regeneratorRuntime is not defined
This worked for me to fix ReferenceError: regeneratorRuntime is not defined in Jest: Then in .babelr...
417
jest babel-jest does not transpile import/export in node_modules when Babel 7 is used
For the record 🐛 Bug Report I started getting the dreaded SyntaxError: Unexpected token import erro...
413
react Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object.
You're exporting a React element not a component Change to Alternatively at the call site change <Co...
411
react Trigger simulated input value change for React 16 (after react-dom 15.6.0 updated)?
After some research of react source code I got a hack method for react 16: NOTICE: JUST A HACK ...
408
jest "Syntax Error: Invalid or unexpected token" with .png
I had the same error and resolved it by creating a assetsTransformer.js: Then add this to your jest ...
407
jest Watch mode stopped working on macOS Sierra
I had the same issue Upgrading watchman with brew install watchman to v4.7.0 fixed it. ...
397
material ui Module not found: Can't resolve 'material-ui-icons/Menu' Martial Next
For anyone else experiencing this issue: npm install @material-ui/icons https://www.npmjs.com/packag...
391
javascript How to configure React Native (Expo) project to use AirBnB's React rules via ESLint?
This is what I do in React and React Native: Step 1 Step 2 Backup your eslintrc file in case you wan...
383
yarn ERROR: There are no scenarios; must have at least one.
You've got the wrong yarn 😄 The Yarn you're executing comes from the cmdtest package: http://manpag...
378
webpacker localIdentName option moved in css-loader configuration
I faced same issue after upading css-loader but I solved it If you check css-loader readme ...
376
react native gesture handler Execution failed for task ':react-native-gesture-handler:compileDebugJavaWithJavac'
@zmGitHub npm i jetifier npx jetify fixed it for me on rn 0.6 I am fixing a incompatibility issue re...
358
atom Sometimes opening a file, Atom does not open in a new tab
This feature is called Pending Pane Items (formerly known as Preview Tabs) – this allows you to quic...
352
axios POST request works in Browser but not on Node
This might be considered a duplicate of #789 I was able to use the form-data package with Axios in n...
348
angular Cyclic dependency error with HttpInterceptor
I resolved simply not setting authService in constructor but getting in the intercept function. ...
337
lodash Find if array includes all elements from another array
You can do _.difference(subset superset).length === 0 to achieve this currently ...
333
fetch Error when POST file multipart/form-data
Setting the Content-Type header manually means it's missing the boundary parameter Remove that heade...
328
amplify js Uncaught ReferenceError: global is not defined in latest Angular 6 RC
Just for reference I have passed through this issue with adding these lines on my index.html head: ...
328
yarn Installation Problem: .yarn-metadata.json: Unexpected end of JSON input
I triggered this condition after a failed install of lodash.isfunction: If you trigger this you can ...