【问题标题】:How can I save locally the pdf that I have generated with html2pdf with node?如何在本地保存使用带节点的 html2pdf 生成的 pdf?
【发布时间】:2021-02-21 18:44:28
【问题描述】:

我正在使用 html2pdf 生成 pdf,并且我已经设法生成了 pdf,但是现在我需要将此 pdf 发送到节点中的服务器或将其直接保存在我服务器上的文件夹中,现在 pdf 已下载到客户端指示的路径,但我需要在我的服务器上有一个副本,我已经尝试使用输出参数但我没有实现任何目标,这是我当前的代码:

 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?非常感谢。

【问题讨论】:

  • 我认为用 FS 来做这件事很聪明,祝你好运
  • 谢谢,FS 是什么??

标签: javascript node.js ajax email html2pdf


【解决方案1】:

您需要创建例如后端服务器上的 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);
        });
    });

有用的帖子:

【讨论】:

  • 非常感谢,但是我怎样才能在服务器中阅读 pdf 文件呢?谢谢
  • 为什么是 data.append 而不是 formdata.append??
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 2023-03-08
    • 2012-11-29
    • 2013-03-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-22
    • 1970-01-01
    相关资源
    最近更新 更多