[hummus pageModifier]: невозможно завершить PDF (случайно) - PullRequest
0 голосов
/ 03 сентября 2018

Мое изображение в формате png. Проблема случайная. Из 10, 5 раз выдает ошибку.

Вот пример кода ( fileStream.js ):

function generateSignedDoc(imageFilePath, signedDocFilePath, termCondFilePath, callback){
  try {
    var pdfWriter = hummus.createWriterToModify(termCondFilePath, {modifiedFilePath: signedDocFilePath});
    var pageModifier = new hummus.PDFPageModifier(pdfWriter,4,true);
    var ctx = pageModifier.startContext().getContext();
    ctx.drawImage(70,180, imageFilePath, {transformation:{width:150,height:100, proportional:true}});
    pageModifier.endContext().writePage();
    pdfWriter.end();
    if(fs.existsSync(signedDocFilePath)){
      callback(null, "successfully created PDF");
    } else {
      callback("Error while creating document.");
    }
  } catch(e){
  console.log("try....catch.....e.....", e);
  callback(e);
  }
}

Контроллер ( user.js ):

req.busboy.on('file', function (fieldname, file, filename, encoding, mimetype) {
    var agreementFile = "UserAgreement_" +  new Date().getTime();
    filename = agreementFile + '.' + (filename.substring(filename.lastIndexOf('.')+1)).toLowerCase();
    signedDocFileName = agreementFile + '.pdf';
    paths.imageFilePath = __dirname + '/../../utility' + Constant.templocalbucket + filename;
    paths.termCondFilePath = __dirname + '/../../resource/Term&Cond.pdf';
    paths.signedDocFilePath = __dirname + '/../..' + Constant.tempSignedDocbucket + signedDocFileName;

    fstream = fs.createWriteStream(paths.imageFilePath);
    file.pipe(fstream);
  });

req.busboy.on('finish', function() {
  Q.nfcall(FileStreamService.generateSignedDoc, paths.imageFilePath, paths.signedDocFilePath, paths.termCondFilePath)
  .then(function(){
    if(fs.existsSync(paths.signedDocFilePath)){
      return true;
    } else {
      console.log("In else..... file path not found....");
      throw {message : 'System file path not found'};
    }
  })
  .catch(function(err){
    console.log("catch block.........", err);
    Logger.info(JSON.stringify(err));
    return res.status(500).send({
      code: 500,
      message: 'Internal server error.'
    });
  });
});

Ошибка:

try....catch.....e..... TypeError: Unable to end PDF
    at generateSignedDoc (/Users/hardik.shah/git/BE/fileStream/service/fileStream.js:38:15)
    at Promise.apply (/Users/hardik.shah/git/BE/node_modules/q/q.js:1185:26)
    at Promise.promise.promiseDispatch (/Users/hardik.shah/git/BE/node_modules/q/q.js:808:41)
    at /Users/hardik.shah/git/BE/node_modules/q/q.js:1411:14
    at runSingle (/Users/hardik.shah/git/BE/node_modules/q/q.js:137:13)
    at flush (/Users/hardik.shah/git/BE/node_modules/q/q.js:125:13)
    at _combinedTickCallback (internal/process/next_tick.js:131:7)
    at process._tickCallback (internal/process/next_tick.js:180:9)

Мне интересно, почему это происходит случайно?

1 Ответ

0 голосов
/ 27 сентября 2018

Проблема заключалась в том, что hummus обрабатывается до того, как fileStream закрывается изображение png. Итак, мне нужно сначала позаботиться о fstream закрытии события, а затем передать изображение хумусу.

req.busboy.on('finish', function() {
  fstream.on('close', function () { // This, I should take care about.
    Q.nfcall(FileStreamService.generateSignedDoc, paths.imageFilePath, paths.signedDocFilePath, paths.termCondFilePath)
    .then(function(){
      if(fs.existsSync(paths.signedDocFilePath)){
        return true;
      } else {
        throw {message : 'System file path not found'};
      }
    })
    .catch(function(err){
      return res.status(500).send({
        code: 500,
        message: 'Internal server error.'
      });
    });
   });
  });
...