2

I'm using css, jquery and nodejs (with ejs and express) to create a website and I need to export a div with some text and some divs with a background-image as an image (jpg or png) but the best would be pdf. I tried to use html2canvas but then I read that it is not compatible with nodejs. I also tried with jspdf but it doesn't export the css in the pdf file. So I would like to know if anyone knows a solution that can do that with nodejs.

Here is an exemple of my ejs code :

<%for(var j = 0; j < rawData.scanner.length; ++j) {%>
<div class="grid" id="grid-<%= data.scanner[j].camera%>" 
    style="
    width : <%= parseFloat(data.widthScreen) + 17%>px; 
    height : <%= parseFloat(data.heightScreen) + 17%>px; 
    position : absolute;
    left : 0px;
    top : 60px;
    overflow-x : scroll;
    overflow-y : scroll;
    display : none;">
    <%for(var i = 0; i < data.scanner[j].parts; ++i) {%>
    <div class="fenetre" id=<%= data.scanner[j].name + "-img" + i%>
        style="
        background-image : url(<%= (data.scanner[j].imagePath)%>);
        width : <%= data.scanner[j].width%>px; 
        height : <%= data.scanner[j].height%>px; 
        position:absolute; 
        top: 0px; 
        left: <%= (i * data.scanner[j].left)%>px;"
    >
    </div>
    <%}%>
</div>
<%}%>
TheRelax
  • 35
  • 1
  • 6

2 Answers2

1

I know this question is old, but these days I'd try puppeteer

const puppeteer = require("puppeteer");

async function printPDF() {
  const browser = await puppeteer.launch({ headless: true });
  const page = await browser.newPage();
  await page.goto("http:///stackoverflow.com", {
    waitUntil: "networkidle0",
  });
  const pdf = await page.pdf({
    width: 1200,
    height: 1920,
    pageRanges: "1-2",
    path: "so.pdf",
  });

  await browser.close();
  return pdf;
}
printPDF();

Also see HTML to PDF with Node.js

Piotr Cierpich
  • 427
  • 2
  • 11
0

Try html-pdf, it export css in pdf file and it is also a npm package so it will compatible with nodejs.

Installation:

$ npm install -g html-pdf

Command-line example:

$ html-pdf test/businesscard.html businesscard.pdf

Code example:

var fs = require('fs');
var pdf = require('html-pdf');
var html = fs.readFileSync('./test/businesscard.html', 'utf8');
var options = { format: 'Letter' };

pdf.create(html, options).toFile('./businesscard.pdf', function(err, res) {
  if (err) return console.log(err);
  console.log(res); // { filename: '/app/businesscard.pdf' } 
});
Jared Chu
  • 2,757
  • 4
  • 27
  • 38