我正在尝试使用 jsPDF 和 TinyMCE 生成 PDF,但生成的 PDF 包含 HTML 标签。我试过使用 doc.html(),但输出与预期不符。它显示一个白色文本,所有单词都在一个新行中。
另一方面,如果我使用 doc.text(),我无法使用 TinyMCE 的工具栏将文本居中或更改文本大小。
如何使用 TinyMCE 和 jsPDF 生成内容格式正确的 PDF?
这是我的代码:
import React, { useRef } from "react";
import { Editor } from "@tinymce/tinymce-react";
import jsPDF from "jspdf";
function Home() {
const editorRef = useRef(null);
const handlePrint = () => {
if (editorRef.current) {
const content = editorRef.current.getContent();
// Create new PDF document
const doc = new jsPDF({
orientation: "landscape",
unit: "mm",
format: [297, 210],
});
// Add content to PDF document
doc.setFont("helvetica", "normal");
doc.setFontSize(14);
doc.text(content, 20, 20);
// Open PDF document in a new tab
window.open(doc.output("bloburl"), "_blank");
}
};
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",
}}
apiKey=""
tinymceScriptSrc="https://cdn.tiny.cloud/1/no-api-key/tinymce/5/tinymce.min.js"
style={{
display: "flex",
justifyContent: "center",
alignItems: "center",
}}
/>
<button onClick={handlePrint} style={{ marginTop: "1rem" }}>
Generate PDF
</button>
</div>
</div>
);
}
export default Home;