簡體   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