Example #1
0
app.get('/simple', function(req, res, next) {
  var doc = new pdfDocument({size: "A4", margins : {top : 0, bottom : 0, left : 0, right : 0} });

  doc.pipe(res);
  doc.registerFont('arial', path.join(__dirname + '/Arial.ttf'), 'arial');
  doc.font('arial');

  doc.info.title = "My Booklet";

  // Stories
  doc
    .fontSize(14)
    .text('(A,诶,ēi) (B,比,bǐ) (C,西,xī)')
    .text('(D,迪,dí) (E,伊,yī) (F,艾弗,ài fú)')
    .text('(G,吉,jí) (H,艾尺,ài chǐ) (I,艾,ài)')
    .text('(J,杰,jié) (K,开,kāi) (L,艾勒,ài lè)')
    .text('(M,艾马,ài mǎ) (N,艾娜,ài nà) (O,哦,ó)')
    .text('(P,屁,pì) (Q,吉吾,jí wú) (R,艾儿,ài ér)')
    .text('(S,艾丝,ài sī) (T,提,tí) (U,伊吾,yī wú)')
    .text('(V,维,wéi) (W,豆贝尔维,dòu bèi ěr wéi)')
    .text('(X,艾克斯,yī kè sī) (Y,吾艾,wú ài) (Z,贼德,zéi dé)')
    .text('abcdefghijklmnopqrstuvwxyz')
    .text('ABCDEFGHIJKLMNOPQRSTUVWXYZ');

  doc.end();
});
Example #2
0
module.exports.genratePdf = function(data){
    var doc = new PDFDocument();
    console.log("Inside pdf genrator"+JSON.stringify(data));
    // Pipe its output somewhere, like to a file or HTTP response 
// See below for browser usage 
var filePath = data.reportPath;
var fileName = filePath.split("/")[2];
doc.pipe(fs.createWriteStream("test_reports/"+fileName));
 
doc.moveTo(300, 75)
   .lineTo(373, 301)
   .lineTo(181, 161)
   .lineTo(419, 161)
   .lineTo(227, 301)
   .fill('red', 'even-odd');  
   
var loremIpsum = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam in...';  

doc.y = 320;
doc.fillColor('black')
doc.text(loremIpsum, {
   paragraphGap: 10,
   indent: 20,
   align: 'justify',
   columns: 2
});  
 
// Finalize PDF file 
doc.end();
}
Example #3
0
	  	getSentence(job_id,copy_id).then(function outputPdf(sentence){
	  		console.log(sentence);
	  		console.log(job);
	  		doc.font('kochi-mincho-subst.ttf');
	  		doc.image("back.png", 30, 30, {fit:[521,383]});
	  		doc.fontSize(16).text(name,300,80);
				doc.fontSize(16).text(age+"歳",300,125);
				if(gender == "Male") gender = "男";
				else gender = "女";
				doc.fontSize(16).text(gender,470,125);
	  		doc.fontSize(16).text(job,310,165);

				var r=new RegExp(".{1,"+35+"}","g");
				var sentences = sentence.match(r);
				console.log(sentences);
				for(var i=0;i<sentences.length;i++){
					doc.fontSize(14).text(sentences[i],40,255 + (i*35));
				}

	  		doc.image("face.png", 30, 30, {fit:[170, 170]});
	  		doc.pipe(fs.createWriteStream('output.pdf'),{end:true}).on('finish', function () {
	  			console.log("complete");
	  			socket.broadcast.emit('showPdfFile',{url:"http://127.0.0.1:8000/output.pdf"});
	  			doc = new PDFDocument();
	  		});
	  		doc.end();

	  	});
Example #4
0
	.exec(function (err, meme) {
		if (err) {
			return next(err);
		}
		if (meme == null) {
			var err = new Error('Meme not found');
			err.status = 404;
			return next(err);
		}
		// Successful
		let svg = generate_svg(meme);
		// Set up new PDF document
		const doc = new PDFDocument();
		let filename = meme._id + '.pdf';
		// Set headers
		res.type('application/pdf');
		res.setHeader('Content-Disposition',
			'attachment; filename="' + filename + '"');
		// Write document contents
		doc.font('Times-Roman');
		doc.fontSize(24).text('MemeGen').moveDown(1);
		doc.fontSize(12).text(meme.name, {underline: true}).moveDown(1);
		doc.fontSize(10).text('SVG data').moveDown(1);
		doc.fontSize(10).text(svg).moveDown(1);
		doc.fontSize(10).text('JSON data').moveDown(1);
		doc.fontSize(10).text(JSON.stringify(meme));
		// Send PDF file
		doc.pipe(res);
		doc.end();
	});
Example #5
0
ipc.on('certificates', function (event, students, promo, tab) {
  var path = ""
  if (process.platform == 'win32')
    path = app.getPath("documents")+"\\PromoBuilder\\"+folder+"\\"
  else
    path = app.getPath("documents")+"/PromoBuilder//"+folder+"/"
  if(!fs.existsSync(path)){
    fs.mkdirSync(path);
  }
  var doc = new pdfkit
  doc.pipe(fs.createWriteStream(path+tab.tab+" Certificates.pdf"))
  //var page = doc.addPage();
  var width = 600; 
  //console.log(page.height)   
  var height = 1000;
  for (var i = 0, len = students.length; i < len; i++) {
    addCertificate(students[i], promo, doc, width, height);
    if(i < len-1)
      doc.addPage({size:"letter"});
  }
  //doc.save()
  doc.end()
  shell.openItem(path+tab.tab+" Certificates.pdf");
  //doc.save(tab.tab+" Certificates.pdf");
});
Example #6
0
router.get('/:id', function(req, res, next) {
	var doc = new PDFDocument();
	//doc.pipe(fs.createWriteStream('file.pdf'));
	doc.text('Hello World and World again!!',100,100);
	doc.pipe(res);
	doc.end();
});
Example #7
0
exports.kitRepo2 = function(pathPDF, data, callback){
    var docOptions = {
        size: "A4",
        layout: "portrait",
        info: {
            Title: "Оценка объектов",
            Author: "Denis Grankin"
        }
    };

    var docs = new pdfDoc(docOptions);

    var config = {
        width : 450,
        height : 300,
        xPos : 0,
        yPos : 90,
        scaleOverlay : true,
        scaleOverride : false,
        scaleSteps : 5,
        scaleStepWidth : 1,
        scaleStartValue : 0,
        scaleLineColor : "gray",
        scaleLineWidth : 1,
        scaleShowLabels : true,
        scaleLabel : "Легенда",
        scaleFont : "fonts/FreeMono.ttf",
        scaleFontSize : 9,
        scaleFontColor : "black",
        scaleShowGridLines : true,
        scaleGridLineColor : "gray",
        scaleGridLineWidth : 0.1,
        barShowStroke : false,
        barStrokeWidth : 0,
        barValueSpacing : 2,
        barDatasetSpacing : 1,
        ManualFirstLabel : 0
    };

    docs.font(config.scaleFont);
    docs.fontSize(20);
    docs.text('Оценка работы по POS',config.xPos, 20, {align: 'center', width: config.width});
    docs.moveDown(0.2);

    barDiag(docs, config, data);

    docs.end();
    var ws = fs.createWriteStream(pathPDF);
    ws.on('open', function(){
        docs.pipe(ws);
    });

    ws.on('finish', function(){
        callback(null, pathPDF);
    });

};
Example #8
0
exports.createPDF = function(mail) {
	var doc = new pdfkit();
	doc.font('./styles/fonts/earwig factory rg.ttf');
	doc.fontSize(20);
	doc.text(mail.subject, {align: 'center'});
	doc.text(mail.text);
	doc.end();
	return doc;
}
module.exports = function (res, items) {
    const doc = new PdfDoc();
    doc.pipe(res);

    items.forEach(function (item) {
        addItem(doc, item);
    });

    doc.end();
};
Example #10
0
            .success(function (basket) {
                if (basket) {
                    var customer = insecurity.authenticatedUsers.from(req);
                    var orderNo = insecurity.hash(new Date() + '_' + id);
                    var pdfFile = 'order_' + orderNo + '.pdf';
                    var doc = new PDFDocument();
                    var fileWriter = doc.pipe(fs.createWriteStream(__dirname + '/../app/public/ftp/' + pdfFile));

                    doc.text('Juice-Shop - Order Confirmation');
                    doc.moveDown();
                    doc.moveDown();
                    doc.moveDown();
                    doc.text('Customer: ' + (customer ? customer.data ? customer.data.email : undefined : undefined));
                    doc.moveDown();
                    doc.text('Order #: ' + orderNo);
                    doc.moveDown();
                    doc.moveDown();
                    var totalPrice = 0;
                    basket.products.forEach(function (product) {
                        var itemTotal = product.price * product.basketItem.quantity;
                        doc.text(product.basketItem.quantity + 'x ' + product.name + ' ea. ' + product.price + ' = ' + itemTotal);
                        doc.moveDown();
                        totalPrice += itemTotal;
                    });
                    doc.moveDown();
                    var discount = insecurity.discountFromCoupon(basket.coupon);
                    if (discount) {
                        if (utils.notSolved(challenges.forgedCouponChallenge) && discount >= 80) {
                            utils.solve(challenges.forgedCouponChallenge);
                        }
                        var discountAmount = (totalPrice * (discount/100)).toFixed(2);
                        doc.text(discount + '% discount from coupon: -' + discountAmount);
                        doc.moveDown();
                        totalPrice -= discountAmount;
                    }
                    doc.text('Total Price: ' + totalPrice);
                    doc.moveDown();
                    doc.moveDown();
                    doc.text('Thank you for your order!');
                    doc.end();

                    if (utils.notSolved(challenges.negativeOrderChallenge) && totalPrice < 0) {
                        utils.solve(challenges.negativeOrderChallenge);
                    }

                    fileWriter.on('finish', function () {
                        basket.updateAttributes({coupon: null});
                        models.BasketItem.destroy({BasketId: id});
                        res.send('/public/ftp/' + pdfFile);
                    });
                } else {
                    next(new Error('Basket with id=' + id + ' does not exist.'));
                }
            }).error(function (error) {
Example #11
0
    }).then(function afterFind(record) {
      if (!record) return res.notFound('user.ticket.download.not.found');

      if (
        !record ||
        // other user ticket
        ( res.locals.currentUserTickets &&
          ( record.ownerId != req.user.id )
        )
      ) {
        return res.notFound('user.ticket.findOne.not.found');
      }

      var doc = new PDFDocument();
      doc.lineWidth(0.5);
      // stream to response
      doc.pipe(res);
      // QR Code
      doc.image(record.getQRCode(), 30, 30, { width: 130, height: 130 });
      // title
      doc.fontSize(15);
      doc.text(record.title, 175, 30, { width: 410 });
      // location
      doc.fontSize(10);
      doc.text(record.location, 175, 46, { width: 410, lineBreak: false });
      // ticket type name
      doc.fontSize(12);
      doc.text(record.typeName, 175, 72, { width: 410, lineBreak: false });
      // fullName
      doc.fontSize(16);
      doc.text(record.fullName, 175, 92, { width: 410 });
      // footer metadata
      var footer = record.id + ' - ' + record.typeIdentifier + ' - ' +
        res.locals.__('ticket.download.date.label')+ ' '+
        req.we.utils.moment(record.createdAt)
        .locale(res.locals.locale)
        .format('L HH:mm');
      // id / identifier
      doc.fontSize(10);
      doc.text(footer, 175, 153, { width: 410 });
      // ticket box
      doc.rect(20, 20, 570, 150)
      .stroke();
      // cutPDF line
      doc.lineWidth(1);
      doc.lineCap('butt')
        .dash(5, { space: 10 } )
        .moveTo(0, 185)
        .lineTo(650, 185)
        .stroke();
      // finalize the PDF and end the stream
      doc.end();
    }).catch(res.queryError);
Example #12
0
  generatorPDF: function *() {
  // create a document and pipe to a blob
    var doc = new PDFDocument()

    // See below for browser usage
    // pipe the document to a blob
    //var stream = doc.pipe(blobStream());

    doc.pipe(fs.createWriteStream('contactPDF/output-2.pdf'))
    // draw some text
    //doc.font('Times-Roman')
    doc.font('myTTF.ttf', 20)
       .text('法国环欧旅游 接待合同', {align : 'center',})

    doc.moveDown()
          .fontSize(13)
          .text('合同编号:0707201501', 300) 

    doc.moveDown()
          .fontSize(10)
          .text ('根据国家有关旅游事业管理的规定,甲乙双方经协商一致,签订本合同,共同信守执行。 ' , 80)

    doc.moveDown()
       .moveDown()
       .fontSize(13)
       .text(txt1, {
         align: 'left',
         indent: 30,
       })

    doc.moveDown()
       //.font('Times-Roman')
       .text(txt2, {
         align: 'left',
         indent: 30,
       })

       
   
    // end and display the document in the iframe to the right
    doc.end()

  /*  stream.on ('finish',  function() {
      //get a blob you can do whatever you like with
      //blob = stream.toBlob('application/pdf')
      
      //or get a blob URL for display in the browser
      url = stream.toBlobURL('application/pdf')
      iframe.src = url
    })
   */
  },
Example #13
0
		.then(function(proyecto){
			
			//pdfKit
			var doc = new PDFDocument({
				size: 'letter'
			});

			doc.pipe(res);

			doc.image('./public/img/accesoslogo.png', 380, 30, {width: 200});
			doc.font('Helvetica');
			doc.fontSize(14);

			doc.text('Fecha: ' + proyecto.createdAt, 65, 180)
				.moveDown();

			doc.text('Proyecto nombre: ' + proyecto.name)
				.moveDown();

			doc.text('Dirección: ' + proyecto.location)
				.moveDown();

			doc.text('Cliente: ' + proyecto.cliente)
				.moveDown();
			doc.text('E-mail: ');

			doc.text('Peso total aproximado:  ' + proyecto.peso + ' kg', 160, 400)
				.moveDown()
				.text('Diseño seleccionado:  ' + proyecto.portonNo + ' ' + proyecto.porton);

			doc.text('Ancho: ' + proyecto.ancho + ' cm', 220, 525);

			doc.text('Alto: ' + proyecto.alto + ' cm', 430, 640);

			doc.moveTo(35, 350)
				.lineTo(577, 350);

			doc.moveTo(35, 490)
				.lineTo(577, 490);

			doc.lineWidth(.5)
				.roundedRect(35, 120, 542, 640, 5)
				.stroke();

			doc.lineWidth(.5)
				.rect(150, 560, 260, 160)
				.fillAndStroke("white", "gray");

			doc.end();
			console.log('PDF created!');
		});
Example #14
0
	objConn.query('SELECT * FROM basic_information where empid = ? AND active_flag = ?', ['120698', 'Y'], function(error, rows) {
		console.log('Basic Information Data');
		console.log(rows.length);
		
		var doc = new PDFDocument();
		//doc.pipe(fs.createWriteStream('file.pdf'));
		doc.text(rows[0].FIRSTNAME + ' ' + rows[0].MIDDLENAME + ' ' + rows[0].LASTNAME, 100,100);

		doc.text('WeServ Systems International, Inc.',100,110);


		doc.pipe(res);
		doc.end();
  });
Example #15
0
Service.generatePDF = function (filename, events, classData, callback) {
    var path = 'public/upload/schedule/' + filename + '.pdf';
    var doc = new PDFDocument;
    schedule_title(doc, classData); // 课表pdf的title部分
    schedule_class(doc, classData); // 课表pdf的class列表部分
    schedule_week(doc, events); // 课表pdf的周日历部分
    var stream = doc.pipe(fs.createWriteStream(path)); // doc.pipe(res)
    doc.end();
    stream.once('close', function () {
        fs.exists(path, function () {
            callback(null, path);
        });
    });
};
exports.getPdf = function(req, res) {

  // create a document and pipe to a blob
  var doc = new PDFDocument();

  // write to PDF
  var createFs = fs.createWriteStream('permisos.pdf');

  doc.pipe(createFs);

  // draw some text
  doc.fontSize(25)
     .text('Heré is séme véctor graphics...', 100, 80);
     
  // some vector graphics
  doc.save()
     .moveTo(100, 150)
     .lineTo(100, 250)
     .lineTo(200, 250)
     .fill("#FF3300");
     
  doc.circle(280, 200, 50)
     .fill("#6600FF");
     
  // an SVG path
  doc.scale(0.6)
     .translate(470, 130)
     .path('M 250,75 L 323,301 131,161 369,161 177,301 z')
     .fill('red', 'even-odd')
     .restore();
     
  // and some justified text wrapped into columns
  doc.text('And here is some wrapped text...', 100, 300)
     .font('Times-Roman', 13)
     .moveDown()
     .text(lorem, {
       width: 412,
       align: 'justify',
       indent: 30,
       columns: 2,
       height: 300,
       ellipsis: true
     });

  // HTTP response
  doc.pipe(res);
  
  doc.end();
  return res.download('/permisos.pdf', 'permisos:///tmp/permisos.pdf');
};
module.exports = function(object) {
	var myDoc = new Pdf();
	myDoc.font('Times-Roman').fontSize(20).text('Favourites');
	myDoc.font('Times-Roman').fontSize(15);
	myDoc.pipe(fs.createWriteStream(FILE_NAME));
	for (var word in object) {
		if (object.hasOwnProperty(word)) {
			myDoc.text(word+': '+object[word]);
		}
		
	}
	console.log('PDF created.');
	myDoc.end();
	return './'+FILE_NAME;
};
Example #18
0
  function render() {
    doc.fontSize(10);

    renderHeader();

    if (options.table) {
      renderTable();
    }

    if (options.items || options.images) {
      renderItems();
    }

    doc.end();
  }
Example #19
0
 function (err, result, field) {
   if (err) {
     throw err;
   }
   pdfdoc.pipe(fs.createWriteStream('public/pdfs/output.pdf'));
   pdfdoc.fontSize(25).text(year+'-'+month+'-'+day+" notebook", 100, 80);
   for(var i = 0; i < 3; i++){
     var iconv = require('Iconv');
     var conv = new iconv.Iconv('utf8', 'UTF-16BE');
     var bom = "\xFE\xFF";
     // pdfdoc.font('public/fonts/ume-hgo4.ttf').fontSize(8).text(bom + conv.convert(result[i].comment).toString());
     pdfdoc.font('public/fonts/ume-hgo4.ttf').fontSize(12).text("・"+result[i].comment);
   }
   // client.end();
   pdfdoc.end();
   io.to(socket.id).emit('pdf download', '');
 });
Example #20
0
    router.get('/:id', function(req, res, next) {
    doc.pipe(fs.createWriteStream('file.pdf'));
    doc.fontSize(20);
    doc.text(eName, {
      width:410,
      align:'center'
     });

    doc.fontSize(12);
    doc.text(headerQuali,100,90);
    doc.text(headerSpec,100,120);
    doc.text(headertrain,100,390);
    doc.text(headerCareer,100,490);
    doc.text(headerExp,100,590);
    doc.pipe(res);
    doc.end();

});
Example #21
0
http.createServer(function (req, res) {

    // Parse URL to get a filename

    var urlObj = url.parse(req.url, true);
    var filename = urlObj.query["filename"];


    //Create a PDF with PDFKit
    var doc = new PDFDocument();
    doc.pipe(fs.createWriteStream('output/' + filename + '.pdf'));

    doc.fontSize(22);
    doc.text('Your file: '+filename+'.pdf', 20, 20);
    doc.fontSize(16);
    doc.text('Was created successfully if you see this.', 20, 30);

    doc.save();
    doc.moveTo(100, 150);
    doc.lineTo(100, 250);
    doc.lineTo(200, 250);
    doc.fill("#FF3300");
    doc.restore();

    doc.end();


    // Render PNG with GhostScript

    exec("/usr/bin/gs -dQUIET -dPARANOIDSAFER -dBATCH -dNOPAUSE -dNOPROMPT -sDEVICE=png16m -dTextAlphaBits=4 -dGraphicsAlphaBits=4 -r72 -dFirstPage=1 -dLastPage=1 -sOutputFile=./output/"+filename+".png ./output/"+filename+".pdf", function (error, stdout, stderr) {

        if ( error !== null ) {
            console.log(error);
        }
        else {
            var img = fs.readFileSync('./output/'+filename+'.png');
            res.writeHead(200, {'Content-Type': 'image/png' });
            res.end(img, 'binary');
            console.log('Created PNG: '+filename+'.png');
        }
    });

}).listen(3000);
Example #22
0
const renderPdf = model => {
  console.log('Render: ', model);
  const pdf = new PdfDocument();
  const stream = pdf.pipe(blobStream());

  pdf.fontSize(20);
  pdf.text(model.title, {
    underline: true,
    align: 'center'
  });

  pdf.end();

  stream.on('finish', () => {
    const blob = stream.toBlob('application/pdf');
    const url = stream.toBlobURL('application/pdf');
    window.open(url);
  });
};
Example #23
0
		return new Promise(function(resolve, reject) {

			var doc = new PDFDocument();

			var target = config.get("target").replace("__dirname", __dirname);
			var file = new injects.TargetResolver("output.pdf").resolve();

			var stream = fs.createWriteStream(file);
			var resultStream = doc.pipe(stream);

			model.forEach(function(m) {
				m.render(doc);
			})

			doc.end();

			resultStream.on('finish', function() {
				resolve(fs.createReadStream(file));
			})

		})
	pdf: function (req, res) {
	var filename="report";
    var content="que ondiux";
	var doc = new PDFDocument(); // create instance of PDFDocument
	doc.fontSize(25).text('Hola', 100, 80);
	doc.text('And here is some wrapped text...', 100, 300).font('Times-Roman', 13).moveDown().text(content, {
	    width: 412,
	    align: 'justify',
	    indent: 30,
	    columns: 2,
	    height: 300,
	    ellipsis: true
	});
    doc.y = 320;
    doc.text(content,100,100);
    console.log(path.resolve(".")+'/PDF/'+filename+'.pdf');
    doc.pipe( fs.createWriteStream(path.resolve(".")+'/PDF/'+filename+'.pdf') );
	res.set('Content-Type', 'application/pdf');
	console.log(res.get('Content-Type'));
    res.redirect('/pdfGenerateDownload');
    doc.end();
	}
Example #25
0
    async.map(_getAllLabels(orders), request, function (err, results) {

      if(err) return callback(err);

      // build pdf with loaded images

      var doc = new pdfkit();

      doc.pipe(concat(function (data) {
        callback(null, data, range);
      }));

      results.forEach(function (result, index) {
        index === 0 || doc.addPage();
        doc.image(result.body, 20, 20, {
          width: 300
        });
      });

      doc.end();

    });
Example #26
0
////////////////////////////////////
function pdf_generate(Q_number,T_time,rows)
{

//PDF Creation
var PDF = require('pdfkit');            
var fs = require('fs');

//create pdf object
doc = new PDF();   

//create write object
var file = fs.createWriteStream('que_bank.pdf');
doc.pipe(file);   
doc.fontSize(20);//font size of the pdf file
doc.text("QUESTION BANK",205,300);
doc.text("MAXIMUM MARKS :"+Q_number,190,340);
doc.text("TOTAL TIME :"+T_time,220,380);
doc.moveDown().text("");
doc.text("NUMBER OF OBJECTIVE QUESTIONS :"+rows.length,100,410);
doc.text("NUMBER OF SUBJECTIIIVE QUESTION :3",100,440);
doc.addPage();

doc.fontSize(11.5);//font size of the pdf file

for(var j=0;j<rows.length;j++)
{
doc.text("Question ID :"+rows[j].id);  //adding the text to be written, 
doc.moveDown().text(rows[j].que);
doc.moveDown().text("(a) "+rows[j].opt1);
doc.moveDown().text("(b) "+rows[j].opt2);
doc.moveDown().text("(c) "+rows[j].opt3);
doc.moveDown().text("(d) "+rows[j].opt4);
doc.moveDown().text("");//for new line
}
doc.end();

}
Example #27
0
function makePDF(title, excel, image, defaultText) {
    var doc = new pdfkit();
    doc.pipe(fs.createWriteStream('./public/file.pdf'));

    // draw some text
    doc.fontSize(25)
        .text('Title: ' + title, 100, 80);

    // write text according to the uploaded excel
    var i = 0;
    var excelJson = readExcel(excel);
    var dynamicTextHeight = 0;
    for (p in excelJson) {
        doc.fontSize(20)
            .text('Product: ' + excelJson[p].product + ', Price: ' + excelJson[p].price, 100, 110 + i);
        i += 20;
    }
    dynamicTextHeight = 110 + i;

    doc.image('./' + image[0].path, 100, dynamicTextHeight, {fit: [100, 100]});
    dynamicTextHeight += 120;

    // and some justified text wrapped into columns
    doc.text('And here is some default text...', 100, dynamicTextHeight)
        .font('Times-Roman', 13)
        .moveDown()
        .text(defaultText, {
            width: 412,
            align: 'justify',
            indent: 30,
            columns: 2,
            height: 300,
            ellipsis: true
        });

    doc.end();
}
Example #28
0
exports.create = function (req, res) {
  var doc = new PDFDocument(),
    lorem = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam in suscipit' +
      'purus. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere' +
      'cubilia Curae; Vivamus nec hendrerit felis. Morbi aliquam facilisis risus eu lacinia.' +
      '  Sed eu leo in turpis fringilla hendrerit. Ut nec accumsan nisl. Suspendisse rhoncus' +
      'nisl posuere tortor tempus et dapibus elit porta. Cras leo neque, elementum a rhoncus' +
      'ut, vestibulum non nibh. Phasellus pretium justo turpis. Etiam vulputate, odio vitae' +
      'tincidunt ultricies, eros odio dapibus nisi, ut tincidunt lacus arcu eu elit. Aenean' +
      'velit erat, vehicula eget lacinia ut, dignissim non tellus. Aliquam nec lacus mi, sed' +
      'vestibulum nunc. Suspendisse potenti. Curabitur vitae sem turpis. Vestibulum sed' +
      'neque eget dolor dapibus porttitor at sit amet sem. Fusce a turpis lorem. Vestibulum' +
      'ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae;';
  doc.pipe(fs.createWriteStream('app/download/file.pdf'));
  doc
    .fontSize(18)
    .text('Hello world!', 100, 100)
    .fontSize(10)
    .text(lorem, {columns: 3, columnGap: 15, height: 100, width: 465, align: 'justify'});
  doc.end();
  //res.redirect('download/file.pdf');
  //res.sendfile('app/download/file.pdf');
  res.download('app/download/file.pdf');
};
Example #29
0
 }, function afterCreateThePDF(err) {
   if (err) return res.serverError(err);
   // finalize the PDF and end the stream
   doc.end();
 });
Example #30
0
            return new Promise(function (resolve, reject) {
                if (meta.project_type_class === "standard") {
                    // normalize input
                    var chapters = _.mapValues(_.groupBy(translation, function (obj) {
                        //console.debug('map chapter values', obj);
                        return obj.chunkmeta.chapterid;
                    }), function (chapter, key) {
                        var frames = _.mapKeys(chapter, function (obj) {
                            //console.debug('map chapter keys', obj);
                            return obj.chunkmeta.frameid;
                        });

                        var chapterObj = {
                            id: key,
                            title: frames.title || key,
                            reference: frames.reference === undefined ? null : frames.reference,
                            format: meta.format
                        };
                        delete frames.reference;
                        delete frames.title;
                        chapterObj.frames = _.sortBy(_.filter(frames, function (o) {
                            return o.transcontent !== '';
                        }), function (f) {
                            //console.debug('sort frames',f);
                            return f.chunkmeta.frame;
                        });
                        return chapterObj;
                    });
                    var project = {
                        format: meta.format,
                        title: chapters['00'].title
                    };
                    delete chapters['00'];
                    project.chapters = _.sortBy(_.filter(chapters, function (o) {
                        return o.frames.length > 0;
                    }), 'id');
                    chapters = null;

                    if (project.format === 'markdown') {

                        var doc = new PDFDocument({
                            bufferPages: true,
                            margins:{
                                top: 72,
                                bottom: 50,
                                left: 72,
                                right: 72
                            }
                        });
                        doc.pipe(fs.createWriteStream(filePath));
                        // default meta
                        if (project.title.transcontent !== "") {
                            doc.info.Title = project.title.transcontent;
                        } else {
                            doc.info.Title = project.title.projectmeta.project.name;
                        }

                        //doc.info.Author = 'Joel Lonbeck'; // todo: translators
                        //doc.info.Subject = 'an unrestricted, visual mini-Bible in any language'; // todo: project sub-title
                        doc.info.Keywords = meta.target_language.name;

                        // book title
                        doc.fontSize(25)
                            .font(targetfont)
                            .text(doc.info.Title, 72, doc.page.height / 2, {align: 'center'});

                        mythis.renderLicense(doc, "OBS_LICENSE.md");

                        // TOC placeholders
                        doc.addPage();
                        var lastTOCPage = doc.bufferedPageRange().count;
                        var tocPages = {
                            start: lastTOCPage - 1
                        };
                        doc.fontSize(25)
                            .text(' ', 72, 72)
                            .moveDown();
                        _.forEach(project.chapters, function (chapter) {
                            doc.fontSize(10)
                                .text(' ')
                                .moveDown();
                            var currPage = doc.bufferedPageRange().count;
                            if (lastTOCPage !== currPage) {
                                // record toc page split
                                tocPages[chapter.id] = currPage - 1;
                                lastTOCPage = currPage;

                                // give room for header on new page
                                doc.fontSize(25)
                                    .text(' ', 72, 72)
                                    .moveDown();
                            }
                        });

                        // book body
                        _.forEach(project.chapters, function (chapter) {
                            // chapter title
                            doc.addPage();
                            doc.fontSize(20)
                                .text(chapter.title.transcontent || chapter.title.chunkmeta.title, 72, doc.page.height / 2, {align: 'center'});
                            chapter.page = doc.bufferedPageRange().count;

                            // frames
                            if (options.doubleSpace === true) {
                                doc.lineGap(20);
                            }
                            doc.addPage();
                            _.forEach(chapter.frames, function (frame) {
                                if (options.includeIncompleteFrames === true || frame.completed === true) {
                                    doc.moveDown();
                                    if (options.includeImages === true) {
                                        //console.debug(meta);
                                        //console.debug(frame);
                                        // TRICKY: right now all images are en
                                        var imgPath = path.join(imagePath, meta.resource.id + "-en-" + frame.chunkmeta.chapterid + "-" + frame.chunkmeta.frameid + ".jpg");
                                        //check the position of the text on the page.
                                        // 792 (total ht of page) - 50 ( lower margin) - 263.25 (height of pic) = 478.75 (max amount of space used before image)
                                        if (doc.y > 478.75) {
                                            doc.addPage();
                                        }
                                       doc.image(imgPath, {width:doc.page.width - 72*2});
                                    }
                                    doc.fontSize(10)
                                        .text(frame.transcontent);
                                    if (options.includeImages === true) {
                                        doc.moveDown();//add extra line break after image and text as per github issue527
                                    }
                                }
                            });

                            // chapter reference
                            if (chapter.reference !== null) {
                                doc.moveDown()
                                    .fontSize(10)
                                    .text(chapter.reference.transcontent);
                            }
                        });

                        // number pages
                        var range = doc.bufferedPageRange();
                        for (var i = range.start; i < range.start + range.count; i ++) {
                            doc.switchToPage(i);
                            doc.fontSize(10)
                                .font(defaultfont)
                                .text(i + 1, 72, doc.page.height - 50 - 12, {align: 'center'});
                        }

                        // write TOC
                        var currTocPage = tocPages.start;
                        doc.switchToPage(currTocPage);
                        // TODO: display correct title of TOC based on the project
                        doc.fontSize(25)
                            .lineGap(0)
                            .text('Table of Contents', 72, 72)
                            .font(targetfont)
                            .moveDown();
                        _.forEach(project.chapters, function (chapter) {
                            if (tocPages[chapter.id] !== undefined && tocPages[chapter.id] !== currTocPage) {
                                currTocPage = tocPages[chapter.id];
                                doc.switchToPage(currTocPage);
                                doc.fontSize(10)
                                    .text(' ')
                                    .moveUp();
                            }
                            doc.switchToPage(currTocPage);
                            doc.fontSize(10)
                                .text(chapter.title.transcontent || chapter.title.chunkmeta.title)
                                .moveUp()
                                .text(chapter.page + '', {align: 'right'})
                                .moveDown();
                        });

                        doc.end();
                        resolve(true);
                    } else if (project.format === 'usfm') {

                         var doc = new PDFDocument({
                            bufferPages: true,
                            margins:{
                                top: 72,
                                bottom: 50,
                                left: 72,
                                right: 72
                            }
                        });
                        doc.pipe(fs.createWriteStream(filePath));

                        //set the title
                        doc.info.Title = translation[0].transcontent || meta.project.name;
                        doc.fontSize(25)
                            .font(targetfont)
                            .text(doc.info.Title, 72, doc.page.height / 2, {align: 'center'});

                        mythis.renderLicense(doc, "LICENSE.md");

                             // book body
                        _.forEach(project.chapters, function (chapter) {

                            doc.addPage();//start each chapter on new page

                            //list chapters (remove leading zeros in the numbers)
                            var chapterNum = chapter.id.replace(/\b0+/, '');
                            doc.fontSize(20)
                                .lineGap(10)
                                .text(chapterNum + ' ', {continued: true});
                            chapter.page = doc.bufferedPageRange().count;

                            // frames
                            if (options.doubleSpace === true) {
                                doc.lineGap(20);
                            }

                            _.forEach(chapter.frames, function (frame) {
                                if (options.includeIncompleteFrames === true || frame.completed === true) {
                                    var content = frame.transcontent.split(/[\\]*[\\||\/][v][ ]([0-9]+)/g);

                                    _.forEach(content, function (info) {
                                        let output = info;
                                       //superscript for verses not supported by pdfkit: https://github.com/devongovett/pdfkit/issues/15
                                       output = output.replace(/[\\][\\c][ ][0-9]+ /g, '');
                                        doc.fontSize(10)
                                            .text(output + ' ',  { continued: true});
                                    });
                                }
                                doc.moveDown()
                                    .text("");
                            });
                        });

                        // number pages
                        var range = doc.bufferedPageRange();
                        for (var i = range.start; i < range.start + range.count; i ++) {
                            doc.switchToPage(i);
                            doc.fontSize(10)
                                .font(defaultfont)
                                .text(i + 1, 72, doc.page.height - 50 - 12, {align: 'center'});
                        }

                        doc.end();
                        resolve(true);
                    } else {
                        reject('We only support printing OBS and Bible projects for now');
                    }
                } else {
                    // TODO: support exporting other target translation types if needed e.g. notes, words, questions
                    reject('We do not support printing that project type yet');
                }
            });