繁体   English   中英

如何在本地保存使用带节点的 html2pdf 生成的 pdf?

[英]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由客户端,但我需要在我的服务器上有一个副本,我尝试使用 output 参数但我没有实现任何目标,这是我当前的代码:

 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)); 
        });
    });

但我不知道如何将 pdf 发送到服务器或直接从前端保存,有谁知道如何保存在我的服务器上生成的 pdf? 非常感谢。

您需要在后端服务器上创建例如 PUT 端点,并将生成的文件从客户端发送到服务器。

可以使用以下方式发送数据:

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);
        });
    });

有用的帖子:

在@mojoaxel给出的设置文件发送后。首先你必须设置文件存储操作。我使用multer存储pdf你可以使用其他库。 请参阅下面的代码以配置文档保存功能。

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
})

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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