我使用两个插件1react-pdf来生成 pdf 和一个插件html-to-image将 html 转换为图像。但问题是转换功能只有在创建pdf后才起作用。这是函数:
const downloadImage = async () => {
return await htmlToImage.toPng(testEl.current, {
cacheBust: false,
})
}
在此函数中,我返回一个 URL,并将其放入<Image />. 例如:
<Image src={downloadImage} cache={false} />
也许把函数放进去useEffect?请在这件事上给予我帮助。这是完整的代码:
import {PDFDownloadLink, Page, Text, View, Document,Image} from "@react-pdf/renderer";
import * as htmlToImage from "html-to-image";
export function CustomComponent() {
const testEl = useRef();
const downloadImage = async () => {
return await htmlToImage.toPng(testEl.current, {
cacheBust: false,
});
};
const MyDoc = () => (
<Document>
<Page>
<View>
<Image src={downloadImage} cache={false} />
</View>
</Page>
</Document>
);
return (
<>
<div ref={testEl} className="test">
Text
</div>
<PDFDownloadLink document={<MyDoc />} fileName="print-test.pdf">
{({ blob, url, loading, error }) =>
loading ? "Loading document..." : "Download now!"
}
</PDFDownloadLink>
</>
);
}
编辑
const downloadImage = () => {
return htmlToImage.toPng(testEl.current, {
cacheBust: false,
});
};
const MyDoc = () => {
return (
<Document>
<Page>
<View>
<Image src={downloadImage} cache={false} />
</View>
</Page>
</Document>
);
};
const asyncF = async () => {
await downloadImage();
await MyDoc();
};
useEffect(() => {
asyncF();
});
编辑2
import React, { useState, useEffect, useRef, Fragment } from "react";
import { usePDF, Page, Text, View, Document, Image } from "@react-pdf/renderer";
import * as htmlToImage from "html-to-image";
export function CustomComponent({}) {
const downloadImage = async () => {
return await htmlToImage.toPng(
document.querySelector(".test"),
{ cacheBust: false }
);
};
const myPdfDocument = (
<Document>
<Page>
<View>
<Image src={downloadImage} cache={false} />
</View>
</Page>
</Document>
);
function triggerDownload(url) {
const a = document.createElement("a");
a.href = url;
a.download = "test.pdf";
a.click();
}
const [pdfInstance, updatePdfInstance] = usePDF({});
const [isDownloading, setIsDownloading] = useState(false);
function initiateDownload() {
setIsDownloading(true);
updatePdfInstance(myPdfDocument);
}
useEffect(() => {
if (isDownloading && pdfInstance.url) {
triggerDownload(pdfInstance.url);
setIsDownloading(false);
}
}, [isDownloading, pdfInstance.url]);
return (
<>
<div className="test">Text</div>
<button onClick={initiateDownload} disabled={isDownloading}>
{isDownloading ? "Loading..." : "Download PDF"}
</button>
</>
)
}
有条件的...
尝试这个:
您只需要尝试是传递 downloadImage 函数返回的所有内容还是仅传递 .url