Как поместить несколько изображений в PDF, используя pdfkit (node js)? - PullRequest
0 голосов
/ 10 января 2020

то, что я хотел, это вставить несколько изображений из многопользовательского URL. Для этого я загружаю и поочередно добавляю в pdf, но проблема в том, что код не синхронный. И я новичок в узле / javascript.

, вот мой код и ошибка, пожалуйста, помогите мне

var download = function(uri, filename, callback){
  request.head(uri, function(err, res, body){
    console.log('content-type:', res.headers['content-type']);
    console.log('content-length:', res.headers['content-length']);

    request(uri).pipe(fs.createWriteStream(filename)).on('close', callback);
  });
};

download('https://cdn.pixabay.com/ers90__340.png', 'google.png', function(){
  console.log('done');
});

// Create a document
const doc = new PDFDocument();

// Pipe its output somewhere, like to a file or HTTP response
// See below for browser usage
doc.pipe(fs.createWriteStream('out.pdf'));

// Embed a font, set the font size, and render some text
doc
  //.font('fonts/PalatinoBold.ttf')
  .fontSize(25)
  .text('Some text with an embedded font!', 100, 100);

// Add an image, constrain it to a given size, and center it vertically and horizontally
doc.image('google.png', {
  fit: [250, 300],
  align: 'center',
  valign: 'center'
});
// Apply some transforms and render an SVG path with the 'even-odd' fill rule
doc
  .scale(0.6)
  .translate(470, -380)
  .path('M 250,75 L 323,301 131,161 369,161 177,301 z')
  .fill('red', 'even-odd')
  .restore();

// Add some text with annotations
doc
  .addPage()
  .fillColor('blue')
  .text('Here is a link!', 100, 100)
  .underline(100, 100, 160, 27, { color: '#0000FF' })
  .link(100, 100, 160, 27, 'http://google.com/');

// Finalize PDF file
doc.end();

ошибка: это то, что я получаю при запуске перед загрузкой изображения pdfkit модуль запускает свой код, я не знаю, как синхронизировать

internal/fs/utils.js:230
    throw err;
    ^

Error: ENOENT: no such file or directory, open 'google.png'
    at Object.openSync (fs.js:457:3)
    at Object.readFileSync (fs.js:359:35)
    at Function.open (/Users/sharan/node_modules/pdfkit/js/pdfkit.js:4432:19)
    at PDFDocument.openImage (/Users/sharan/node_modules/pdfkit/js/pdfkit.js:4575:24)
    at PDFDocument.image (/Users/sharan/node_modules/pdfkit/js/pdfkit.js:4476:22)
    at Object.<anonymous> (/Users/sharan/Desktop/jsss/var8.js:32:5)
    at Module._compile (internal/modules/cjs/loader.js:1144:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1164:10)
    at Module.load (internal/modules/cjs/loader.js:993:32)
    at Function.Module._load (internal/modules/cjs/loader.js:892:14) {
  errno: -2,
  syscall: 'open',
  code: 'ENOENT',
  path: 'google.png'
}

1 Ответ

1 голос
/ 10 января 2020

вы можете попробовать это ....

ImagesUrlArr.forEach(function (el){
    doc.addPage().image(el.data, {fit: [500, 400], align: 'center',valign: 'center'})
})
...