Html component for react-pdf with CSS support optimized
npm install react-pdf-html-flabs-2 component for react-pdf
- Support for CSS via 1. Parses the HTML string into a JSON tree of nodes using node-html-parser `` ` const html = return ( const element = ( const html = ReactDOMServer.renderToStaticMarkup(element); return ( tags return ( return ( Reset browser default styles (see CSS reset) The default styesheet roughly matches browser defaults, using a rough emulation of ems: StyleSheet.create({ By default, the basis for the font size ems is based on the If this is not defined, it falls back to a default of tags and style attributes (limited to Style properties supported by react-pdf)
- Browser CSS defaults with option for style reset
- Basic (attempted using flex layouts)
and support
- Ability to provide custom renderers for any tagHow it Works
2. Parses any tags in the document and style attributes using css-tree
3. Renders all nodes using the appropriate react-pdf components, applying cascading styles for each node as an array passed to the style prop:
- block/container nodes using
- inline/text nodes using , with appropriate nesting and collapsing of whitepace
- nodes using
- nodes using Installation
bash`
npm i react-pdf-htmlUsage
tsx
import Html from 'react-pdf-html';
Heading 1
Heading 2
Heading 3
Heading 4
Paragraph with bold, italic, underline,
strikethrough,
and all of the above
Paragraph with image and
link
Text outside of any tags
Column 1
Column 2
Column 3
Foo
Bar
Foobar
Foo
Bar
Some longer thing
Even more content than before!
Even more content than before!
function myCode() {
const foo = 'bar';
}
;`
{html}
);`Rendering React Components
tsx`
import ReactDOMServer from 'react-dom/server';
Heading 1
Heading 2
...
);
{html}
);`Props
ts`
type HtmlProps = {
children: string; // the HTML
collapse?: boolean; // Default: true. Collapse whitespace. If false, render newlines as breaks
renderers?: HtmlRenderers; // Mapping of { tagName: HtmlRenderer }
style?: Style | Style[]; // Html root View style
stylesheet?: HtmlStyles | HtmlStyles[]; // Mapping of { selector: Style }
resetStyles?: false; // If true, style/CSS reset
};`Overriding Element Styles
$3
tsx`
const stylesheet = {
// clear margins for all
p: {
margin: 0,
},
// add pink background color to elements with class="special"
['.special']: {
backgroundColor: 'pink',
},
};
{html}
);`$3
tsx
const html = Foobar;`
{html}
);`Resetting Styles
tsx`
return (
{html}
);`Font Sizes
tsx`
const em = (em: number, relativeSize: number = fontSize) => em * relativeSize;
h1: {
fontSize: em(2),
marginVertical: em(0.67, em(2)),
fontWeight: 'bold',
},
...
});fontSize from props.style:`tsx`
return (
{html}
);18`