Create a PDF document after click a button in React - reactjs

I want to generate a PDF document that is generated after user click "Create PDF document" for my current React page. The document I want to generate will have the following:
Some, but not all component in the current page
Selectable
Only download the document when clicking and nowhere else
I have spent 3 hours researching on this trivial task, but somehow all library I have looking up for only allow their pre-defined component, or not selectable, or both. I know that this task is very trivial, but how exactly I could do that?

The best way to do this is, having a separate component that only contains what data need to be downloaded. And you can pass all necessary data using props.
I recommend using this library React-PDF.
App.js
import { PDFDownloadLink } from '#react-pdf/renderer';
import Document from './Document.js'
export default function App() {
const data = {/* Pass your data here */}
return (
<div className="App">
<PDFDownloadLink document={<MyDocument data={data}/>} fileName="somename.pdf">
{({ blob, url, loading, error }) =>
loading ? 'Loading document...' : 'Download now!'
}
</PDFDownloadLink>
</div>
);
}
Document.js
import React from 'react';
import { Document, Page, Text, View, StyleSheet } from '#react-pdf/renderer';
// Create styles
const styles = StyleSheet.create({
page: {
flexDirection: 'row',
backgroundColor: '#E4E4E4'
},
section: {
margin: 10,
padding: 10,
flexGrow: 1
}
});
// Create Document Component
const MyDocument = ({ data }) => ( //
<Document>
<Page size="A4" style={styles.page}>
<View style={styles.section}>
<Text>{data.something}</Text>
</View>
<View style={styles.section}>
<Text>{data.something}</Text>
</View>
</Page>
</Document>
);
In the main component, you will have a Download now! button. Your PDF will only contain data that you pass through props

Related

reading image from src/assets folder at runtime using props in React

I want to display image randomly in React.
Images are placed inside src/assets folder.
I have to display them using props.
Row.js:
import React from 'react'
import {View, Text } from 'react-native';
const Row = (props) => (
<View style={{flex:1, flexDirection: 'row'}}>
<img src={require(props.value)}> //Error: Cannot find module '../assets/icondelivery.PNG'
</img>
<Text>{props.value}</Text>
</View>
)
export default Row
props.value contains : ../assets/icondelivery.PNG
Hierarchy is : src/assets/icondelivery.PNG
Note: If I pass <img src={require('../assets/icondelivery.PNG')}> , it works.
Put assets folder in public folder. Change path from ../assets/icondelivery.PNG to ./assets/icondelivery.PNG
Use this code:
import React from 'react'
import {View, Text } from 'react-native';
const Row = (props) => (
<View style={{flex:1, flexDirection: 'row'}}>
<img src={process.env.PUBLIC_URL + props.value}/>
<Text>{props.value }</Text>
</View>
)
export default Row
For dynamic image sources that are known then you can use require() in your definitions instead of within the img src itself.
For example
<Row value={require('../assets/icondelivery.PNG')} />
Then in the component:
<img src={props.value}>
If you have a structure containing the images like an array you could put require() there:
const images = [
{ name: 'delivery', src: requiure('../assets/icondelivery.PNG')}
...
...
]

Can't generate pdf download link with react-pdf

I'm new with react. I want to create a website that can generate pdf file to download. I use React with Vite and Tailwind. I found this in internet: https://react-pdf.org/advanced#on-the-fly-rendering.
I try it in my code but nothing shows up.
import {Document, Page, PDFDownloadLink, StyleSheet, Text, View} from "#react-pdf/renderer";
import React from "react";
// Create styles
const styles = StyleSheet.create({
page: {
flexDirection: "row",
backgroundColor: "#E4E4E4",
},
section: {
margin: 10,
padding: 10,
flexGrow: 1,
},
});
// Create Document Component
const MyDoc = () => (
<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>
);
const Dashboard = () => (
<div>
<PDFDownloadLink
className=" bg-slate-600"
document={<MyDoc />}
fileName="somename.pdf"
>
{({ blob, url, loading, error }) =>
<button className=" bg-slate-500">Loading document...</button>
) : (
<button className=" bg-slate-500">Download now!</button>
)
}
</PDFDownloadLink>
</div>
);
export default Dashboard;
And i call this from my App.jsx file
import Dashboard from "./Dashboard";
function App() {
return (
<div className=" bg-slate-500">
<Dashboard />
</div>
);
}
export default App;
This is how it's look when run
This is when i inspect
I run it from brave browser, but it still the same when i run it from google browser.
Anyone know why this is happen? Any help is appreciated
So after a lot of searching, i found that my problem is caused by vite. This post pretty much solve it

how to set Header and Footer in react-pdf/renderer?

I am building reactJs app, I am using react-pdf/renderer to render the pdf. I want to show Header in the pdf.
Below is the my code.
MainComponent.jsx
<Document>
<Page size="A4" style={styles.page}>
<MyFixedHeader style={{flex: 0.2}}/>
<Image style={styles.image} src={Logo} />
<Text style={styles.text}>
{pdfData}
</Text>
</Page>
</Document>
MyFixedHeader.jsx
import React, { useEffect, useState } from 'react';
export const MyFixedHeader = () => {
return (<>
hi
</>)
}
By using this code, I am getting blank screen.
Thanks.
I added a screenshot of how to add a footer on each page end. here is the link https://react-pdf.org/repl you can test it here
#mehak
are you applying these styles??
you can check here official site https://react-pdf.org/advanced
and there are many different other ways to create Header and Footer for react-pdf
Added Horizontal Line
How to register Font?

How to make vscode autocomplete props that are spread in a React functional component

I have a functional component in react native. It goes like this:
export const Row = ({ children, style, ...props }) => (
<View
style={[{ flexDirection: "row", alignItems: "center" }, style]}
{...props}
>
{children}
</View>
);
I am using it like this:
const App = () => {
return (
<Row>
<Text>Hello</Text>
</Row>
);
};
export default App;
How can I enable autocomplete of vscode while using Row component. For example, I want to use onMagicTap that is in View, how can see the autocomplete in Row. I have spread the props in View but I can't see the autocomplete. Any solution to this?
PS. I am use JS, not TS
you can try vs-code extensions, one I use "React Native Snippet"

downloading a pdf with data fetched from api in react-admin dashboard

i create an app based on react-admin
and a fake server using json-server
my file structure is the following :
client ( here goes the react app )
node_modules
db.json
package-lock.json
pachake.json
range.js
then i created products and orders lists and show page :
the link for the show page of an order is ( for example order 3 ) :
http://localhost:3000/#/orders/3/show
and it shows the orders datils
what i wanna do is to download a pdf file contains this details , i tried the following code as a starting point :
import * as React from "react";
import {useQuery, Show, SimpleShowLayout, TextField } from 'react-admin';
import { PDFDownloadLink, Document, Page , View , Text } from '#react-pdf/renderer'
const MyDoc = ({}) => {
return (
<Document>
<Page size="A4">
<View>
<Text>
details must go here
</Text>
</View>
</Page>
</Document>
)};
const OrderShow = (props) => (
<Show {...props}>
<SimpleShowLayout>
<TextField source='order_number' />
<TextField source='reference_number' />
<TextField source='status' />
<TextField source='payment' />
<TextField source='shipment' />
<TextField source='created_at' />
<div>
<PDFDownloadLink document={<MyDoc /> } fileName="somename.pdf">
{({ loading }) => (loading ? 'Loading document...' : 'Download now!')}
</PDFDownloadLink>
</div>
</SimpleShowLayout>
</Show>
);
export default OrderShow
with this i got the following output :
when i click on Download now! a pdf with the content ' details must go here ' but instead of that i want the data about the current order
Try having a look at useShowController: https://marmelab.com/react-admin/Show.html#useshowcontroller
By using that, I think you will be able to access the data from the currently shown record, and build the PDF from there.
i did it this way and it works fine :
import React, {Component, PropTypes} from 'react';
// download html2canvas and jsPDF and save the files in app/ext, or somewhere else
// the built versions are directly consumable
// import {html2canvas, jsPDF} from 'app/ext';
export default class Export extends Component {
constructor(props) {
super(props);
}
printDocument() {
const input = document.getElementById('divToPrint');
html2canvas(input)
.then((canvas) => {
const imgData = canvas.toDataURL('image/png');
const pdf = new jsPDF();
pdf.addImage(imgData, 'JPEG', 0, 0);
// pdf.output('dataurlnewwindow');
pdf.save("download.pdf");
})
;
}
render() {
return (<div>
<div className="mb5">
<button onClick={this.printDocument}>Print</button>
</div>
<div id="divToPrint" className="mt4" {...css({
backgroundColor: '#f5f5f5',
width: '210mm',
minHeight: '297mm',
marginLeft: 'auto',
marginRight: 'auto'
})}>
<div>Note: Here the dimensions of div are same as A4</div>
<div>You Can add any component here</div>
</div>
</div>);
}
}

Resources