Trình kết xuất React để tạo tệp PDF trên trình duyệt và máy chủ.

hovanban

Well-known member
1. Install React and react-pdf
Bắt đầu với Reac-pdf cực kỳ đơn giản.

Using Yarn[/B]
yarn add @react-pdf/renderer


Using npm[/B]
npm install @react-pdf/renderer --save


Vì trình kết xuất chỉ triển khai cách các phần tử hiển thị thành một thứ gì đó nên bạn vẫn cần có React để làm cho nó hoạt động (và React-dom để tạo tài liệu phía máy khách). Bạn có thể tìm thấy hướng dẫn về cách làm điều đó ở đây.

2. Create your PDF document
Đây là nơi mọi thứ bắt đầu trở nên thú vị. React-pdf xuất một tập hợp các nguyên hàm React cho phép bạn hiển thị mọi thứ vào tài liệu của mình một cách rất dễ dàng. Nó cũng có API để tạo kiểu cho chúng, sử dụng thuộc tính CSS và bố cục Flexbox.

Let's make the code speak for itself:

import React from 'react';
import { Page, Text, View, Document, 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 = () => (
<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>
);


Điều này sẽ tạo ra một tài liệu PDF với một trang duy nhất. Bên trong có hai khối khác nhau, mỗi khối hiển thị một văn bản khác nhau. Đây không phải là những nguyên thủy hợp lệ duy nhất bạn có thể sử dụng. Vui lòng tham khảo phần Thành phần hoặc Ví dụ để biết thêm thông tin.

3. Choose where to render the document
React-pdf cho phép bạn hiển thị tài liệu trong ba môi trường khác nhau: web và máy chủ. Quá trình này về cơ bản là giống nhau, nhưng đáp ứng nhu cầu của từng môi trường.

Save in a file
import ReactPDF from '@react-pdf/renderer';

ReactPDF.render(<MyDocument />, `${__dirname}/example.pdf`);


Render to a stream
import ReactPDF from '@react-pdf/renderer';

ReactPDF.renderToStream(<MyDocument />);

Render in DOM
import React from 'react';
import ReactDOM from 'react-dom';
import { PDFViewer } from '@react-pdf/renderer';

const App = () => (
<PDFViewer>
<MyDocument />
</PDFViewer>
);

ReactDOM.render(<App />, document.getElementById('root'));


CÔNG TY TNHH TƯ VẤN TRUYỀN THÔNG MINARA
ĐỊA CHỈ:
- 182 Trần Bình Trọng, P.3, Q.5, Tp.HCM
- 27 Đường số 16, Trung Tâm Hành Chính Dĩ An, Bình Dương.
Điện thoại: 097.777.1060
Email: info@minara.vn
Website: www.minara.vn
 
Chỉnh sửa lần cuối:
Bên trên