使用 Socket.io + Puppeteer + Node.js 使用 HTML 和 CSS 创建 PDF

Creating PDF with HTML and CSS using Socket.io + Puppeteer + Node.js

我目前正在尝试在服务器端使用来自 HTML 的 Node.js 创建一个 PDF 文件,但 CSS 仍在工作。然后我想把它附加到一封电子邮件中,但我还没有找到如何附加的,但我遇到了一个更大的问题。

我是 Node.js 的新手,我无法进入函数。服务器端有我的代码。

const fs = require('fs');
const puppeteer = require('puppeteer')
const ConnectionPort = 8080;
const path = require('path');
const app = require('express')();
const http = require('http').createServer(app);
const io = require('socket.io')(http);

io.on('connection', (socket) => {

  console.log('a user connected'); 

  socket.on('disconnect', () => {
    console.log('user disconnected');   
  });
  socket.on('Creation of PDF Document', (PageHTML, NumberOfTheFile, HeadHTML) => {
    console.log('A creation was requested'); // I see that on the console
    (async function(){
      try{
        console.log('Got in the try') // I can't see that on the console
        const browser = await puppeteer.launch();
        const page = await browser.newPage();

        await page.setContent('<head>' + HeadHTML + '</head><body>' + PageHTML + '</body>');
        await page.emulateMedia('screen');
        await page.pdf({
          path: path.join(__dirname, 'Files', NumberOfTheFile + '.pdf'),
          format: "Legal",
          printBackground: true
        });

        console.log('Creation done!');
        await browser.close();
        process.exit();

      } catch (e)
      {
        console.log('Error: ', e)
      }
    })
  });
  ///////////////   Other stuff I was going for that works   ////////////////////
  socket.on('Asking ID', () => {

    console.log('a user is trying to ask for an ID');

    var array = fs.readFileSync('ID_Liste.txt').toString().split("\n");
    var i = 0;
    
    for(i in array) 
    {
        console.log(array[i]);
    }
    
    var ID_BonCommande = parseInt(array[i]) + 1;
    
    fs.appendFile('ID_Liste.txt', " \n  \n  \n" + "Operation Time  : " + "\n" + Date() + "  \n\n"  + "ID_BonCommande : " + "\n"  + ID_BonCommande + '', function (err) {
     if (err) throw err;
     console.log('ID added : ' + ID_BonCommande);
    });

    
    io.emit('Reception ID', ID_BonCommande);
  });
////////////////////////////////////////////////////////////////////////////////
});

http.listen(ConnectionPort , () => {
  console.log('listening on *: ' +ConnectionPort );
});

这是我在客户端调用函数的方式:

 socket.emit('Creation of PDF Document',
     document.getElementById('Page').innerHTML, 
     document.getElementById(NumberOfThePage).innerHTML, 
     document.getElementsByTagName('head').innerHTML // I need the head for the CSS
);

function AddID()
{           
    socket.emit('Asking ID');   
}
        
var receive = function(ID_Receved){
        
document.getElementById('PlaceToPutID').innerHTML = ID_Receved.toString();
            
}
socket.on('Reception ID', receive)

The Youtube video that helped me

我试过这个:

  socket.on('Creation of PDF Document', (PageHTML, NumberOfTheFile, HeadHTML) => {
    console.log('A creation was requested'); // can't go further
    
    async function Test(){
      try{
        console.log('Got in the try')
        const browser = await puppeteer.launch();
        const page = await browser.newPage();
    
        await page.setContent('<head>' + HeadHTML + '</head><body>' + PageHTML + '</body>');
        await page.emulateMedia('screen');
        await page.pdf({
          path: path.join(__dirname, 'Files', NumberOfTheFile + '.pdf'),
          format: "Legal",
          printBackground: true
        });
    
        console.log('Creation done!');
    
      } catch (e)
      {
        console.log('Error: ', e)
      }
    }
    Test();
  });

它没有按预期工作...我没有在 PDF 上得到我的 CSS,但它仍然有点工作。

我需要 CSS 才能真正使用它。我们可以像这样在客户端使用标签名称样式吗:

document.getElementsByTagName('style').innerHTML 

或任何可以将 CSS 传输到服务器的东西。我的 CSS 目前在标签 Style 中,但我不确定这是正确的决定。

我走错方向了?

已编辑*

知道了!

我只是把style标签放在了body里面就可以用了