在 react-admin 仪表板中下载包含从 api 获取的数据的 pdf

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

我基于 react-admin 创建了一个应用 和使用 json-server

的假服务器

我的文件结构如下:

client ( here goes the react app ) 
node_modules
db.json
package-lock.json
pachake.json
range.js

然后我创建了产品和订单列表并显示页面: 订单显示页面的 link 是(例如订单 3): http://localhost:3000/#/orders/3/show 它显示了订单数据 我想做的是下载一个包含这些细节的 pdf 文件,我尝试了以下代码作为起点:

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

有了这个我得到了以下输出:

当我点击立即下载!内容为“详细信息必须放在此处”的 pdf,但我想要的不是关于当前订单的数据

尝试查看 useShowController:https://marmelab.com/react-admin/Show.html#useshowcontroller

通过使用它,我认为您将能够从当前显示的记录访问数据,并从那里构建 PDF。

我是这样做的,效果很好:

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>);
  }
}