简体   繁体   中英

How can I save locally the pdf that I have generated with html2pdf with node?

I am generating a pdf with html2pdf, and I have managed to generate the pdf, but now I need to send this pdf to my server in node or save it directly in a folder on my server, now the pdf is downloaded in the path indicated by the client, but II need to have a copy on my server, I have tried with the output parameter but I have not achieved anything, this is my current code:

 document.addEventListener("DOMContentLoaded", () => {
        // Escuchamos el click del botón
        const $boton = document.querySelector("#btnCrearPdf");
        $boton.addEventListener("click", () => {
            const $elementoParaConvertir = document.body; // <-- Aquí puedes elegir cualquier elemento del DOM
            html2pdf()
                .set({
                    margin: 1,
                    filename: 'documento.pdf',
                    image: {
                        type: 'jpeg',
                        quality: 0.98
                    },
                    html2canvas: {
                        scale: 3, // A mayor escala, mejores gráficos, pero más peso
                        letterRendering: true,
                    },
                    jsPDF: {
                        unit: "in",
                        format: "a3",
                        orientation: 'portrait' // landscape o portrait
                    }
                })
                .from($elementoParaConvertir)
                .save()
                .output('./123123123.pdf', 'f')
                .then(pdfResult => {
                     console.log(pdfResult);
                })
                .catch(err => console.log(err)); 
        });
    });

But I can't figure out how to send the pdf to the server or save it directly from the frontend, does anyone know how I can save the pdf that is generated on my server? Thanks a lot.

You need to create eg a PUT endpoint on you backend-server and send the generated file from the client to the server.

The data could be send using something like this:

const filename = 'documento.pdf';

html2pdf()
    .set({
        filename,
        // other options...
    })
    .from($elementoParaConvertir)
    .toPdf()
    .output('datauristring')
    .then(function(pdfBase64) {
        const file = new File(
            [pdfBase64],
            filename,
            {type: 'application/pdf'}
        ); 

        const formData = new FormData();        
        formData.append("file", file);

        fetch('/upload', {
          method: 'PUT',
          body: formData,
        })
        .then(response => response.json())
        .then(result => {
          console.log('Success:', result);
        })
        .catch(error => {
          console.error('Error:', error);
        });
    });

Helpful posts:

After setup file sending given by @mojoaxel.Firstly you have to setup document storing operation.I am using multer to storing pdf you can use other libraries. See below code for configuring document save functionality.

var multer = require("multer");
var fs = require('fs');
    var Storage = multer.diskStorage({
     destination: function (req, file, cb) {
      let dir = 'document/' + 'Home'; // Your directory
      if (!fs.existsSync(dir)) {         // check whether directory exists or not if not then create new directory
        fs.mkdirSync(dir);
      }
      cb(null, dir);
     },

    filename: function (req, file, cb) {
      let inputData = Common.isEmpty(req.body.data) === false ?  JSON.parse(req.body.data) : req.body; // check if you send formData or not if yes then parsing data else send as it is
      cb(null, file.originalname);
    }

});

var upload = multer({
  storage: Storage
});

router.post("/callurl", upload.array('file') ,function(req, res){
 // your code here
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM