Reputation: 31
I have use @react-pdf/renderer library to download map in pdf.
import html2canvas from "html2canvas";
import {
PDFDownloadLink,
Page,
Text,
View,
Document,
Image,
} from "@react-pdf/renderer";
import Link from "@/icons/Link";
export default function Map(props: MapProps) {
const [mapImage, setMapImage] = useState<string | null>(null);
const [isDownloading, setIsDownloading] = useState(false);
const handlePrint = async () => {
if (!isDownloading) {
setIsDownloading(true);
await handlePrintMapPDFButtonClick();
const downloadLink = document.getElementById('pdfDownloadLink');
if (downloadLink) {
downloadLink.click();
} else {
console.error("Download link not found");
}
setIsDownloading(false);
}
};
const handlePrintMapPDFButtonClick = async () => {
if (mapRef.current) {
try {
const canvas = await html2canvas(mapRef.current.getMap().getCanvas(), {
useCORS: true,
logging: true
});
const imgData = canvas.toDataURL("image/png");
setMapImage(imgData);
} catch (error) {
console.error("Error capturing map image:", error);
}
} else {
console.error("Map reference is not available");
}
};
const MyDocument = () => (
<Document>
<Page size="A4">
{mapImage ? (
<Image
src={mapImage}
style={{ width: "1920px", height: "590px" }}
/>
) : (
<Text>No image available</Text>
)}
</Page>
</Document>
);
return (
<DeckGL
layers={layers}
views={mapView}
>
<ReactMap
ref={mapRef}
mapboxAccessToken={import.meta.env.VITE_MAPBOX_ACCESS_TOKEN}
mapLib={import("mapbox-gl")}
reuseMaps
mapStyle={getMapboxMapStyle(theme.palette.mode === "dark", props.style)}
projection={{ name: "mercator" }}
onLoad={onRender}
/>
<button style={{ position: "absolute", top: "20rem" }} onClick={handlePrint}>
Download PDF
<PDFDownloadLink
id="pdfDownloadLink"
document={<MyDocument />}
fileName="map.pdf"
style={{ display: 'none', height: "100%", width: "100%" }}
>
<Link />
</PDFDownloadLink>
</button>
</DeckGL>
);
1] I had tried pass the proper token to got the map.
2] Log the mapImage here I got the response too when i Copy response and paste in new tab so on this tab also show the blank page.
3] My expectation is when user download the pdf so it's not show the blank pdf instead of it shows the map image in downloaded pdf.
Upvotes: 1
Views: 40