I'm currently trying to use react-pdf to generate and save a pdf to disk. Rendering to a webpage works, but the method that I need to invoke to save a pdf to disc,
ReactPDF.render()
does not work within the npm start (react-scripts) way of running React that I've used in the past to create webpages. From reading this issue, it seems that it needs to be run as a "Node only api". So my question is, what dependencies, commands, and steps do I need to take to run some react code and save a pdf to disk with something like
> node index.js
currently when I run the above command I get
import React from 'react';
^^^^^
SyntaxError: Unexpected identifier
Then, running
node --experimental-modules index.mjs
I get
ReactPDF.render(<App />, `${__dirname}/output/test.pdf`);
^
SyntaxError: Unexpected token <
Here are my two files:
index.js
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import ReactPDF from '@react-pdf/renderer';
ReactPDF.render(<App />, `${__dirname}/output/test.pdf`);
//ReactDOM.render(<App />, document.getElementById('root'));
App.js
import React, { Component } from 'react';
import { Document, Page, Text, View, StyleSheet } from '@react-pdf/renderer'
class App extends Component {
render() {
const styles = StyleSheet.create({
page: {
flexDirection: 'row',
backgroundColor: '#E4E4E4'
},
section: {
margin: 10,
padding: 10,
flexGrow: 1
}
});
return (
<Document>
<Page size="A4" style={styles.page}>
<View style={styles.section}>
<Text>Section #1</Text>
</View>
<View style={styles.section}>
<Text>Section #2</Text>
</View>
</Page>
</Document>
);
}
}
export default App;
package.json
{
"name": "ccv-generator-react",
"version": "0.1.0",
"private": true,
"dependencies": {
"@react-pdf/renderer": "^1.4.2",
"react": "^16.8.5",
"react-dom": "^16.8.5",
"react-scripts": "2.1.8",
"ts-pnp": "^1.0.1",
"typescript": "^3.3.4000"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": "react-app"
},
"browserslist": [
">0.2%",
"not dead",
"not ie <= 11",
"not op_mini all"
],
"devDependencies": {
"babel-preset-es2015": "^6.24.1",
"babel-preset-react": "^6.24.1"
}
}
A follow up question would be, Is what I am trying to do an anti-pattern?
it throws many errors.It might help if you tell us..