Skip to content
TheChatArchiveThe Chat Archive
gpt-3.5-turbo-0613· OpenAIAi2 WildChat-4.8M (AI2)

给出一段React页面转PDF的代码

  1. User

    给出一段React页面转PDF的代码

  2. Assistant

    以下是一个示例的React页面转PDF的代码:

    import React, { useRef } from 'react';
    import html2canvas from 'html2canvas';
    import jsPDF from 'jspdf';
    
    const App = () => {
      const contentRef = useRef(null);
    
      const handleDownloadPDF = () => {
        html2canvas(contentRef.current).then(canvas => {
          const imgData = canvas.toDataURL('image/png');
          const pdf = new jsPDF();
          pdf.addImage(imgData, 'PNG', 0, 0);
          pdf.save('page.pdf');
        });
      };
    
      return (
        <div>
          <h1>React页面转PDF</h1>
          <div ref={contentRef}>
            <p>这是要转换为PDF的页面内容</p>
            <p>可以添加任意的React组件和HTML元素</p>
          </div>
          <button onClick={handleDownloadPDF}>下载PDF</button>
        </div>
      );
    };
    
    export default App;
    

    在上述代码中,我们使用了html2canvas库将React页面内容转换为Canvas元素,然后使用jsPDF库将Canvas转换为PDF文件。在handleDownloadPDF函数中,首先使用html2canvas(contentRef.current)将contentRef.current中的内容转换为Canvas元素,然后使用toDataURL方法获取Canvas的图像数据。接下来,使用jsPDF创建一个PDF实例,并使用addImage方法将Canvas图像添加到PDF中。最后,使用save方法将PDF保存为page.pdf文件。

    请注意,为了确保PDF转换正确,需要将整个要转换为PDF的内容包裹在一个ref引用的div中,该div将在handleDownloadPDF函数中作为参数传递给html2canvas。然后,将该ref引用传递给需要转换为PDF的内容的最外层元素上(上述示例中为div)。

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.