使用純 CSS 和 HTML 在 React JS 中建立 PDF


在本文中,我們將瞭解如何使用 React JS 建立 PDF。PDF 是一種通用的文件格式,用於各種目的,例如報告、資料共享、資料儲存等。如果我們能夠透過簡單的 CSS 在 React 中建立 PDF,那將非常有幫助。

示例

首先建立一個 React 應用 -

npx create-react-app pdfviewer

安裝 **react-pdf** 包

npm i @react-pdf/renderer

我們將使用此包在我們的 React 前端使用 DOM 元素和 CSS 建立 PDF。

將以下程式碼片段插入 **App.js** 中 -

import React from "react";
import {
   Document,
   Page,
   Text,
   View,
   StyleSheet,
   PDFViewer,
} from "@react-pdf/renderer";

// Create styles
   const styles = StyleSheet.create({
      page: {
      flexDirection: "column",
      backgroundColor: "green",
   },

   title: {
      margin: 20,
      fontSize: 25,
      textAlign: 'center',
      backgroundColor: '#E4E4E4',
      textTransform: 'uppercase',
   },

   section: {
      margin: 10,
      padding: 10,
      fontSize:25,
   },
});

// Create Document Component
const MyDocument = () => (
   <Document>
      <Page size="A4" style={styles.page}>
         <View style={styles.title}>
            <Text>Welcome to Tutorialspoint...</Text>
         </View>
         <View style={styles.section}>
            <Text>Create PDF using React</Text>
         </View>
         <View style={styles.section}>
            <Text>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididuntut labore et dolore magna aliqua. Ut enimad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum.</Text>
         </View>
      </Page>
   </Document>
);
export default function App() {
   return (
      <PDFViewer>
         <MyDocument />
      </PDFViewer>
   );
}

解釋

讓我們簡要了解一下這段程式碼 -

  • **<Document>** 定義了我們將要建立 PDF,

  • **<Page>** 定義了 PDF 的單個頁面,以及

  • <Page> 內的內容將是 PDF 單個頁面的內容。

您可以新增任何型別的樣式;這完全取決於您。更好的設計將使 PDF 更加美觀。

輸出

執行後,將生成以下輸出 -

更新於: 2021年9月29日

917 次檢視

開啟您的 職業生涯

透過完成課程獲得認證

立即開始
廣告