Render FontAwesome icon #1334
Replies: 5 comments 7 replies
-
I know this discussion is from a long time ago, but I was looking for a solution to this as well. For future reference, this is how I solved it:
components/pdf/FontAwesomeIcon.tsx
It should also work with duotone fonts. |
Beta Was this translation helpful? Give feedback.
-
eyyy, nice bro nice. it works perfectly. |
Beta Was this translation helpful? Give feedback.
-
any solution for material icons |
Beta Was this translation helpful? Give feedback.
-
I made a similar solution to the one by @trijpstra-fourlights, but for Material Icons. (cc @heredia95)
Usage
|
Beta Was this translation helpful? Give feedback.
-
Here's how to do it with
import { Circle, Path, Svg } from '@react-pdf/renderer';
import React, { useEffect, useState } from 'react';
import ReactDOMServer from 'react-dom/server';
import { createTw } from 'react-pdf-tailwind';
const tw = createTw({});
interface MaterialIconProps {
icon: React.ElementType;
size?: number;
color?: string;
className?: string;
}
export const MaterialIcon = ({ icon: Icon, size = 24, color = 'black', className = '' }: MaterialIconProps) => {
const [paths, setPaths] = useState<React.ReactNode[]>([]);
useEffect(() => {
// Render the icon to a string
const iconString = ReactDOMServer.renderToString(<Icon />);
// Create a temporary DOM element to parse the string
const parser = new DOMParser();
const doc = parser.parseFromString(iconString, 'image/svg+xml');
const svgElement = doc.querySelector('svg');
if (svgElement) {
const svgPaths = Array.from(svgElement.querySelectorAll('path')).map((path, index) => (
<Path key={index} d={path.getAttribute('d') || ''} fill={color} />
));
const svgCircles = Array.from(svgElement.querySelectorAll('circle')).map((circle, index) => (
<Circle
key={index}
cx={circle.getAttribute('cx') || ''}
cy={circle.getAttribute('cy') || ''}
r={circle.getAttribute('r') || ''}
fill={color}
/>
));
setPaths([...svgPaths, ...svgCircles]);
}
}, [Icon, color]);
return (
<Svg viewBox="0 0 24 24" style={[tw(className), { width: size, height: size }]}>
{paths}
</Svg>
);
}; And a usage example: <View style={tw('flex flex-row items-center')}>
<MaterialIcon icon={EnergySavingsLeafIcon} size={12} color="black" className="mr-1" />
<Text style={tw('text-xs')}>Carbon emissions estimate: 384 kg</Text>
</View> |
Beta Was this translation helpful? Give feedback.
-
Has anyone had success rendering FontAwesome icons within a Pdf document? What approach do you recommend?
Beta Was this translation helpful? Give feedback.
All reactions