简体   繁体   English

允许用户将反应 web 页面导出为 pdf

[英]allowing user to export react web page as pdf

How do I allow users to export a customized react web page as pdf, image or share it using gmail.如何允许用户将自定义的反应 web 页面导出为 pdf,使用 gmail 进行映像或共享。 I created a template for a CV with editable components, and I'm trying to find a way for the user to export them as they are, so using jsPDF is not suitable.我为带有可编辑组件的 CV 创建了一个模板,我试图找到一种方法让用户按原样导出它们,因此不适合使用 jsPDF。

You can ue html2canvas for converting your page to a canvas then you can conver the canvas to pdf or img.Advantage of using html2canvas is you won't miss any styles applied to the content. You can ue html2canvas for converting your page to a canvas then you can conver the canvas to pdf or img.Advantage of using html2canvas is you won't miss any styles applied to the content.

here is a sample for generating img.这是生成img的示例。

import html2canvas from 'html2canvas';
import { saveAs } from 'file-saver';
GetImg() {
    html2canvas(document.querySelector("#root")).then(canvas => {
      var img = canvas.toDataURL()
      saveAs(img, "pretty image.png");
    });
  }

for pdf you can use jspdf along with html2canvas.对于 pdf,您可以使用 jspdf 和 html2canvas。 here is a sample这是一个样本

import * as jsPDF from 'jspdf';
getPdf(){
input= document.querySelector("#root")
html2canvas(input)
      .then((canvas) => {
        const imgData = canvas.toDataURL('image/png');
        const pdf = new jsPDF({
          orientation: 'landscape',
        });
        const imgProps= pdf.getImageProperties(imgData);
        const pdfWidth = pdf.internal.pageSize.getWidth();
        const pdfHeight = (imgProps.height * pdfWidth) / imgProps.width;
        pdf.addImage(imgData, 'PNG', 0, 0, pdfWidth, pdfHeight);
        pdf.save('download.pdf');
      });}

So basically you need to convert HTML and CSS into a pdf.所以基本上你需要将 HTML 和 CSS 转换为 pdf。 Javascript doesn't have anything to do with the pdf, and React is javascript, so we need to extract the HTML actually. Javascript 和 pdf 没有任何关系,而 React 是 javascript,所以我们实际上需要提取 Z4C4AD5FCA2E7A81AA474

What you could do is keep a ref on the wrapper element that wraps the CV, then do a ref.current.innerHTML to get the HTML code of your CV.您可以做的是在包装 CV 的包装器元素上保留一个 ref,然后执行ref.current.innerHTML以获取您的 CV 的 HTML 代码。 Also get your CSS, and use jsPDF to convert the HTML and the CSS into a pdf.还要获取您的 CSS,并使用 jsPDF 将 HTML 和 CSS 转换为 Z437175.41912494D9003

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

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