如何使用jsPDF与TinyMCE生成格式正确的PDF文档?
使用jsPDF和TinyMCE生成格式正确的PDF
问题现象
- 用
doc.text()生成PDF时,内容会显示HTML标签,且无法保留TinyMCE设置的格式(如文本居中、字号调整) - 用
doc.html()生成PDF时,文本显示为白色,且每个单词强制换行
解决方案
1. 安装依赖
jsPDF的html()方法需要依赖html2canvas来渲染HTML内容,执行以下命令安装:
npm install html2canvas --save
2. 修改代码逻辑
调整handlePrint函数,通过包裹样式容器解决白字和换行问题,同时正确使用doc.html()渲染带格式的内容:
import React, { useRef } from "react"; import { Editor } from "@tinymce/tinymce-react"; import jsPDF from "jspdf"; import html2canvas from "html2canvas"; // 新增导入 function Home() { const editorRef = useRef(null); const handlePrint = async () => { if (editorRef.current) { const content = editorRef.current.getContent(); // 创建带基础样式的临时容器,解决白字和换行问题 const tempContainer = document.createElement("div"); tempContainer.style.width = "257mm"; // 适配横向A4的内容宽度(297mm页面宽度减去左右各20mm边距) tempContainer.style.background = "#fff"; // 设置白色背景避免文本显示为白色 tempContainer.style.whiteSpace = "normal"; // 取消强制单词换行 tempContainer.style.padding = "0"; tempContainer.innerHTML = content; document.body.appendChild(tempContainer); // 创建PDF文档 const doc = new jsPDF({ orientation: "landscape", unit: "mm", format: [297, 210], }); // 使用html()方法渲染内容 await doc.html(tempContainer, { callback: function (pdf) { // 打开生成的PDF window.open(pdf.output("bloburl"), "_blank"); // 移除临时容器 document.body.removeChild(tempContainer); }, x: 20, y: 20, width: 257, // 内容宽度与临时容器一致 }); } }; return ( <div style={{ display: "flex", justifyContent: "center", alignItems: "center", height: "100vh", }} > <div style={{ width: "50%" }}> <Editor onInit={(evt, editor) => (editorRef.current = editor)} initialValue="This is the initial content of the editor" init={{ height: 500, menubar: true, plugins: [ "advlist autolink lists link image charmap print preview anchor", "searchreplace visualblocks code fullscreen", "insertdatetime media table paste code help wordcount", ], toolbar: "undo redo | formatselect | bold italic backcolor | \ alignleft aligncenter alignright alignjustify | \ bullist numlist outdent indent | removeformat | help", inline_styles: true, // 强制导出内联样式,确保PDF能识别格式 }} apiKey="" tinymceScriptSrc="https://cdn.tiny.cloud/1/no-api-key/tinymce/5/tinymce.min.js" /> <button onClick={handlePrint} style={{ marginTop: "1rem" }}> Generate PDF </button> </div> </div> ); } export default Home;
关键优化点
- 临时容器样式:通过设置白色背景、适配PDF宽度和取消强制换行,解决
doc.html()的显示异常问题 - 内联样式导出:启用TinyMCE的
inline_styles配置,确保文本格式(居中、字号、加粗等)以内联样式导出,被html2canvas正确识别 - 异步处理:使用
async/await等待doc.html()渲染完成,避免PDF生成不完整
内容的提问来源于stack exchange,提问作者dejonda
相关产品推荐
相关产品推荐

