【问题标题】:React convert the component as pdf using jspdfReact 使用 jspdf 将组件转换为 pdf
【发布时间】:2021-10-06 03:47:28
【问题描述】:

当用户单击按钮时,我正在创建一个生成 pdf 的反应,我有五页 html 组件,我不需要显示组件浏览器,我只想显示在 pdf 中,请帮助并搜索了很多,但我不好运气,任何链接,想法对我有用

import { useRef } from "react";
import html2canvas from "html2canvas";
import { jsPDF } from "jspdf";
import Document from "./Doocument"


const App = () => {
  const inputRef = useRef(null);
  const printDocument = () => {
    html2canvas(inputRef.current).then((canvas) => {
      const imgData = canvas.toDataURL("image/png");
      const pdf = new jsPDF();
      pdf.addImage(imgData, "JPEG", 0, 0);
      pdf.save("download.pdf");
    });
  };
  return (
    <>
      <div className="App">
        <h1>Hello CodeSandbox</h1>
        <h2>Start editing to see some magic happen!</h2>
        <div className="mb5">
          <button onClick={printDocument}>Print</button>
        </div>
        <div id="divToPrint" ref={inputRef}>
            <Document/>
        </div>
      </div>
    </>
  );
};
export default App;

【问题讨论】:

  • 什么意思? I have issue data in the component show only in pdf and don`t need in webpage 我建议您在将 HTML 转换为 pdf 时应该使用另一种解决方案,因为使用 html2canvas,它不能用于大型 HTML 文件(像素损坏),而且您还会遇到缓冲区问题。

标签: javascript reactjs jspdf html2canvas html-to-pdf


【解决方案1】:

您可以在Document组件中编写导出pdf的功能,在App.js中您可以关注

const [clicked, setClicked] = React.useState(false)
  ....
  const printDocument = () => {
   setClicked(true)
   }
  const handleCallBack = () => {
  setClicked(false)
  }
  ....
  <div style={{visibility: "hidden", overflow: "hidden", height: 0}}>
    <Document exportPDF={clicked} parentCallBack={handleCallBack}/>
   </div>

 
 
  **in Docment Component follow** 

   useEffect(() => {
   if(clicked){
       const printPDF = async () => {
      **code export pdf here**
     await pdf.save("download.pdf");
      parentCallBack(false)
    }
       printPDF()
    }},[clicked])

【讨论】:

    猜你喜欢
    • 2014-10-03
    • 1970-01-01
    • 2014-11-16
    • 1970-01-01
    • 1970-01-01
    • 2014-09-14
    • 2019-01-05
    • 2022-08-10
    • 2017-12-25
    相关资源
    最近更新 更多