简体   繁体   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 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: 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)); 
        });
    });

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?但我不知道如何将 pdf 发送到服务器或直接从前端保存,有谁知道如何保存在我的服务器上生成的 pdf? 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.您需要在后端服务器上创建例如 PUT 端点,并将生成的文件从客户端发送到服务器。

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.在@mojoaxel给出的设置文件发送后。首先你必须设置文件存储操作。我使用multer存储pdf你可以使用其他库。 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
})

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

相关问题 如何通过 html-pdf-node 库、节点和 React JS 和 graphQL 下载生成的 PDF - How can I download generated PDF by html-pdf-node library, node and React JS and graphQL 如何在javascript中使用html2pdf从div HTML制作PDF,但对于移动和PC视图相同 - How can I make PDF from div HTML using html2pdf in javascript, but the same for mobile and pc views 如何在不影响页面的情况下指导 html2pdf 使用哪个样式表? - How can I direct html2pdf which stylesheet to use without affecting the page? 我可以从 html2pdf 在当前或新选项卡中打开 pdf 而不是下载它(打开弹出窗口) - can I open the pdf in current or new tab from html2pdf instead of downloading it (open pop up ) 如何将渲染的 pdf(从 html 生成)保存到我的计算机? - how can i save rendered pdf (generated from html) to my computer? 如何防止 HTML2PDF 自动下载 pdf? - How do I prevent HTML2PDF from auto-downloading the pdf? 如何将 html2pdf PDF 转换为 base64? - How do I convert html2pdf PDF to base64? 如何使用 html2pdf 从 dataURL 下载 PDF 格式的图像? - How do I download an image in PDF format from dataURL using html2pdf? 我正在使用 html2pdf 生成 pdf,我可以隐藏 html 以便用户看不到它吗? - I'm using html2pdf to generate a pdf, can I hide the html so the user doesn't see it? 将html2pdf生成的pdf发送回服务器 - Sending html2pdf generated pdf back to the server
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM