npm pdfjs 创建损坏的 PDF 文件

npm pdfjs creates corrupted PDF files

我正在尝试使用 npm 库 pdfjs https://www.npmjs.com/package/pdfjs 创建 PDF 文件。一旦文件的所有元素(段落)都附加到我创建文件的文档,但打开它时我收到一条消息,它说已损坏。

当我用doc.end()完成文件时,说没有功能。所以我使用了一个承诺,并尝试稍后使用这些信息。但是即使我得到一个包含所有数据的对象,我也无法使 .pdf 文件不被损坏。

这是我正在使用的代码:

const pdf = require('pdfjs')
const fs  = require('fs')

function createPDF(data, options){
  return new Promise((resolve, reject) => {
    var doc = new pdf.Document({ font: require('pdfjs/font/Helvetica') });
    var header = doc.header().table({ widths: [null, null], paddingBottom: 1*pdf.cm }).row()
    header.cell().image('/images/logo.png', { height: 2*pdf.cm })
    header.cell().text({ textAlign: 'right' })
    .add('Example.')
    .add('https://www.example.com', {
      link: 'https://www.example.com',
      underline: true,
      color: 0x569cd6
    })
    doc.footer()
    .pageNumber(async function(curr, total) { return curr + ' / ' + total }, { textAlign: 'center' });



    resolve(doc)

  });
}

var doc = createPDF();


doc.then(async (data) => {
  data.pipe(fs.createWriteStream('output.pdf'))
  console.log(data);
  await data.end();
})


日志数据:

Document {
  _readableState:
   ReadableState {
     objectMode: false,
     highWaterMark: 16384,
     buffer: BufferList { head: null, tail: null, length: 0 },
     length: 0,
     pipes:
      WriteStream {
        _writableState: [Object],
        writable: true,
        domain: null,
        _events: [Object],
        _eventsCount: 5,
        _maxListeners: undefined,
        path: 'output.pdf',
        fd: null,
        flags: 'w',
        mode: 438,
        start: undefined,
        autoClose: true,
        pos: undefined,
        bytesWritten: 0 },
     pipesCount: 1,
     flowing: true,
     ended: false,
     endEmitted: false,
     reading: false,
     sync: true,
     needReadable: false,
     emittedReadable: false,
     readableListening: false,
     resumeScheduled: true,
     paused: false,
     emitClose: true,
     destroyed: false,
     defaultEncoding: 'utf8',
     awaitDrain: 0,
     readingMore: false,
     decoder: null,
     encoding: null },
  readable: true,
  domain: null,
  _events:
   { read: { [Function: bound onceWrapper] listener: [Function] },
     end: { [Function: bound onceWrapper] listener: [Function: onend] },
     data: [Function: ondata] },
  _eventsCount: 3,
  _maxListeners: undefined,
  version: '1.6',
  info: { id: '34d7f55c-5961-4caf-9814-1902b98bee3c' },
  width: 595.296,
  height: 841.896,
  _nextObjectId: 4,
  _xref: PDFXref { objects: [], trailer: null },
  _reading: false,
  _length: 0,
  _pending:
   [ [Function],
     [ [Function], [Array], [Array], [Function] ],
     [Function],
     [Function],
     [Function],
     [Function],
     current: Promise { <pending> } ],
  defaultFont:
   AFMFont {
     _data:
      { fontName: 'Helvetica',
        fullName: 'Helvetica',
        familyName: 'Helvetica',
        italicAngle: 0,
        characterSet: 'ExtendedRoman',
        fontBBox: [Array],
        underlinePosition: -100,
        underlineThickness: 50,
        capHeight: 718,
        xHeight: 523,
        ascender: 718,
        descender: -207,
        kerning: [Object],
        widths: [Array] },
     lineGap: 231,
     parent: [Circular] },
  defaultFontSize: 11,
  defaultColor: [ 0, 0, 0 ],
  defaultLineHeight: 1.15,
  _fonts: { '/F1': { f: [Object], o: [Object] } },
  _xobjects: {},
  _pageFonts: {},
  _annotations: [],
  _aliases: AliasGenerator { nextId: { F: 2 }, blocked: Set {} },
  _mapping: WeakMap {},
  _currentContent: null,
  _contents: [],
  _contentObjCreator: null,
  _finalize: [],
  _template: null,
  _footer: null,
  _header: null,
  paddingTop: 20,
  paddingBottom: 20,
  paddingLeft: 20,
  paddingRight: 20,
  _cursor:
   Cursor {
     width: 555.296,
     height: 801.896,
     x: 20,
     startX: 20,
     y: 821.896,
     startY: 821.896,
     _bottom: 20,
     bottomOffset: 0 },
  _pages: [ toString: [Function] ],
  _pagesObj:
  PDFObject {
     id: 2,
     rev: 0,
     properties: PDFDictionary { dictionary: [Object] },
     reference: PDFReference { object: [Getter] },
     content: 'stream\n!!!Djz!WW3#D/OH9;Fa%r=BSfM#MB(Z!#knQ!$hOd@:O@tzzzz!!!!"zz!!)`D!!*\'"!!(J"z\'&psr`WC#h?J?20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qzD.R-sz!!!!"zzzzz!!!!#=BSfMz!!!"j!!!"p!!!"S=BSfMz!!$r3!!#"O!!!+_F(o80z6W-l+A7]glz
!!!!N;IsHOEb0,uAKY#fATqj+B-9Q[DIdI\'Bl@l3Bl5%b77/1U0f_-M/M\n4zzzzzzzzzzzzzzzzzzzz=BSfMz!!)`D!!*\'"!!(J"FCf]=z6Z6phEbT0"F<F.mFCfK1@<?4%DII
?(6Z6dZEZd_fDKB`:FD5l7/0H]%0KB+5F(R3`z!!*Kr!!!2[s8V[;!!!7g!!)tYs8Vtis8W%l!!!,U!!\'fW~>\nendstream\n' },
  _currentColorSpace: '/CS1',
  _doc: [Circular],
  _parent: [Circular],
  _ended: false,
  _current:
   Footer {
     _doc: [Circular],
     _parent: [Circular],
     _cursor:
      ClonedCursor {
        width: 555.296,
        height: 801.896,
        bottomOffset: 0,
        startX: 20,
        startY: 821.896,
        _root: [Object] },
     _ended: false,
     _current: null,
     _pending:
      [ [Function],
        [Array],
        [Function],
        [Function],
        [Function],
        [Function],
        current: [Object] ],
     _objects: [],
     _pageNumbers: [] } }

看起来内容在那里,但无法获取。当 await data.end(); 为 运行 时,它显示下一个错误日志显示:

TypeError: Invalid value used as weak map key TypeError: Invalid value used as weak map key
    at WeakMap.set (native)
    at Document._useXObject (/home/developer1/Projects/bfreit_website/node_modules/pdfjs/lib/document.js:255:21)
    at module.exports (/home/developer1/Projects/bfreit_website/node_modules/pdfjs/lib/image/render.js:16:23)
    at _pending.push (/home/developer1/Projects/bfreit_website/node_modules/pdfjs/lib/fragment.js:143:30)
    at Document._next (/home/developer1/Projects/bfreit_website/node_modules/pdfjs/lib/document.js:169:36)
    at _pending.current.next.then (/home/developer1/Projects/bfreit_website/node_modules/pdfjs/lib/document.js:172:19)
    at <anonymous>
    at process._tickCallback (internal/process/next_tick.js:188:7)

预期的输出是一个正确的 .pdf 文件。但即使我的输出是 .pdf 文件,它也已损坏。

Unable to open document “file:///home/developer1/Projects/pdf/output.pdf”.
Error when trying to open the file:
PDF document is damaged

如果你能帮我解决这个问题,或者用你的知识库来帮助我解决这个问题,那就太棒了。

我找不到 pdfjs 库的解决方案。但是我找到了一个在我的项目中效果更好的库。它真的很容易使用。 简短示例:

const pdf = require('pdfkit');
const fs = require('fs');
const doc = new pdf();

doc.pipe(fs.createWriteStream('/my/path'));
doc.fontSize(10).text('Fontsize 10')
doc
      .fontSize(18)
      .text('Font Size 18 aligned right', {align: 'right'});
doc.moveDown();
doc.fontSize(14).text('Font size 14 aligned center',{align:'center' })
doc.end();