GithubHelp home page GithubHelp logo

juankuquintana / node-html-pdf-sample Goto Github PK

View Code? Open in Web Editor NEW

This project forked from itsmebhavin/node-html-pdf-sample

0.0 0.0 0.0 9.13 MB

Sample application for print pdf from node.js using middleware called 'node-html-pdf' and send it to angular.js client application.

JavaScript 20.72% HTML 79.28%

node-html-pdf-sample's Introduction

node-html-pdf-sample

Sample application for print pdf from node.js using middleware called 'node-html-pdf'.

Version

1.0.1

Tech

Middleware/libraries used in this sample project -

  • AngularJS - HTML enhanced for web apps!
  • node.js - evented I/O for the backend
  • Express - fast node.js network app framework @tjholowaychuk
  • node-html-pdf - Html to pdf converter in nodejs. It spawns a phantomjs process and passes the pdf as buffer or as filename.
  • Body-Parser - npm body-parser for node.js API
  • nunjucks - A rich and powerful templating language for JavaScript.
    • npm install --save nunjucks

Installation

$ npm install --save express
$ npm install --save body-parser
$ npm install --save html-pdf (main node-html-pdf npm command)
$ npm install --save nunjucks

Server side node.js API code

var express = require('express');
var http = require('http');
var fs = require('fs');
var bodyParser = require('body-parser');
var pdf = require('html-pdf');
//nunjucks templating 
var nunjucks = require('nunjucks');
//html file which you want to convert into pdf.
var html = fs.readFileSync('./businesscard_tmpl.html', 'utf8')

//Nunjucks is a product from Mozilla and we are using it as a template engine.
nunjucks.configure('public', {
    autoescape: true,
    express: app
});

app.get('/api/printpdf1', function (req, res) {
    console.log('request made....print 1 ');
    var today = new Date();
    var obj = {
        date: today,
        data:{
            ticketnum : 12121212,
            dateissued: '2014-04-02',
            officername: 'john doe',
            notes:'lorem epsum'
        }
    };

    var renderedHtml =  nunjucks.render('nunjucks.tmpl.html',obj);
    pdf.create(renderedHtml,report_options).toStream(function(err, stream){
        console.log(stream);
        stream.pipe(res);
    });
});

app.get('/api/printpdf2', function (req, res) {
    console.log('request made....print 1 ');
    pdf.create(html).toStream(function(err, stream){
        console.log(stream);
        stream.pipe(res);
    });
});

Client side angular.js code

 <!-- To display pdf inline on page inside div/container -->
 <object data="{{content}}" style="width:100%;height:700px;" type="application/pdf"></object>
 
 <!-- To open pdf on new tab/windows -->
 <button type="button" ng-click="printPdf()">Print PDF in new window</button>
//inject $scope, $q, $http, $sce to angular controller.
$scope.getPDF = function(){
                $scope.loading = true;
                var q = $q.defer();
                $http.defaults.headers.common['content-type']= 'application/pdf';
                $http.get('/api/printpdf1', {responseType:'arraybuffer'})
                        .success(function (response) {
                            console.log(response);
                            var file = new Blob([response], {type: 'application/pdf'});
                            var fileURL = URL.createObjectURL(file);
                            $scope.loading = false;
                            q.resolve(fileURL);
                        })
                        .error(function(err){
                            $scope.loading = false;
                            q.reject(err);
                        });
                return q.promise;
            };
            
            //To print pdf on new window/ Button_Click event.
            $scope.printPdf = function(){
                console.log('printing pdf...');
                $scope.getPDF().then(function(response){
                    console.log(response);
                    window.open(response);
                },function(err){
                    console.log('Error: ' + err);
                });
            };
                
            //Call this code to load pdf on same page inline
            $scope.getPDF().then(function(response){
                console.log(response);
                $scope.content = $sce.trustAsResourceUrl(response);
            },function(err){
                console.log('Error: ' + err);
            });
            

Todo's

  • Create report printing engine where we have to inject report template's html to node.js project.
  • Report html template will call node.js API to get data and fill html placeholder/{{}} using angular.
  • Read populated html file from node.js using fs.readFileSync and populate pdf.
  • Send that pdf stream to client

License

MIT

Happy Coding ...!!

Bhavin Patel [http://itsmebhavin.wordpress.com]

node-html-pdf-sample's People

Contributors

itsmebhavin avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.