Web前端开发网

fly63.com

首页 资源 工具 文章 教程 栏目
  • 在线搜索
  • 文章标签
  • 广告合作
  • 赞助一下
  • 关于我们
资源推荐
阿里云优惠券
卓越的云计算技术和服务提供商
腾讯云优惠券
云服务器,云数据库,CDN,域名注册等多种云计算服务
扣子Coze
创建属于你的 AI 应用,AI Agent智能办公平台
豆包AI
字节跳动旗下 AI 智能助手
即梦AI
一站式智能创作平台,即刻造梦
AiPPT
全智能AI一键生成 PPT
堆友AI
零门槛,多风格AI绘画免费生成,电商海报设计神器
蜂小推
不扣量的项目推广平台
SpeedAI
一键去重、降AIGC率、数据可视化、论文写作

资源分类

AI智能 酷站推荐 招聘/兼职 框架/库 模块/管理 移动端UI框架 Web-UI框架 Js插件 Jquery插件 CSS相关 IDE环境 在线工具 图形动效 游戏框架 node相关 调试/测试 在线学习 社区/论坛 博客/团队 前端素材 图标/图库 建站资源 设计/灵感 IT资讯
网站收录 / 问题反馈

react-pdf

分享
复制链接
新浪微博
QQ 好友

扫一扫分享

网站地址:https://react-pdf.org/
GitHub:https://github.com/diegomura/react-pdf
网站描述:一个使用 React 创建 PDF 文件的工具
访问官网
GitHub

react PDF 是一个使用 React 创建 PDF 文件的工具,支持在浏览器、移动设备和服务器上创建PDF文件。

可以用它们轻松地将内容呈现到文档中,我们可以使用 css 属性进行样式设置,使用 flexbox 进行布局,它支持渲染文本、图像、 svg 等等,详情可以参考官网。

初始化项目

yarn create next-app --example with-ant-design next-resume 
cd next-resume
yarn add @react-pdf/renderer

React-pdf 渲染需要一些额外的依赖项和 webpack5 配置。

yarn add process browserify-zlib stream-browserify util buffer assert

这一步骤是因为 React-pdf 构建在 PDFKit 的基础之上,在使用浏览器时需要使用两个 node.js api polyfill。而 webpack 5 不再包括自动引入 nodejs polyfill ,我们必须选择进入所有我们想要的 polyfill。为了做到这一点,我们必须为我们的项目添加一些依赖项:

在根目录下创建一个 next.config.js

module.exports = {
  reactStrictMode: true,
  webpack: (config, { buildId, dev, isServer, defaultLoaders, webpack }) => {
    config.resolve.fallback = {
      ...config.resolve.fallback,
      module: "empty",
      dgram: "empty",
      dns: "mock",
      fs: "empty",
      http2: "empty",
      net: "empty",
      tls: "empty",
      child_process: "empty",
      process: require.resolve("process/browser"),
      zlib: require.resolve("browserify-zlib"),
      stream: require.resolve("stream-browserify"),
      util: require.resolve("util"),
      buffer: require.resolve("buffer"),
      asset: require.resolve("assert"),
    };
    config.plugins.push(
      new webpack.ProvidePlugin({
        Buffer: ["buffer", "Buffer"],
        process: "process/browser",
      })
    );
    return config;
  },
};

实现逻辑

新建在 App.js 将用户输入实时绑定到 state 中,然后时时渲染预览页面

import Preview from './component/Preview'
import React, { useState } from 'react'
function App() {
  const [profile, setProfile] = useState({
    name: "狂奔滴小马",
    about: "分享 Javascript 热门\n框架,探索 web 极致\n优化体验。",
    email: "maqi1520@qq.com",
    avatar:"https://p6-passport.byteacctimg.com/img/user-avatar/585e1491713363bc8f67d06c485e8260~300x300.image",
  })

  const handleChange = (name, value) => {
    setProfile({ ...profile, [name]: value })
  }

  return (
    <div
      style={{
        width: '100%',
        height: '100vh',
        display: 'flex',
      }}
    >
      <div style={{ width: '50%' }}>
        <div>
          <label>姓名</label>
          <input
            name='name'
            defaultValue={profile.name}
            onChange={(e) => {
              handleChange(e.target.name, e.target.value)
            }}
          />
        </div>
        <div>
          <label>头像地址</label>
          <input
            name='avatar'
            defaultValue={profile.avatar}
            onChange={(e) => {
              handleChange(e.target.name, e.target.value)
            }}
          />
        </div>
        <div>
          <label>简介</label>
          <input
            name='about'
            defaultValue={profile.about}
            onChange={(e) => {
              handleChange(e.target.name, e.target.value)
            }}
          />
        </div>
        <div>
          <label>email</label>
          <input
            name='email'
            defaultValue={profile.email}
            onChange={(e) => {
              handleChange(e.target.name, e.target.value)
            }}
          />
        </div>
      </div>
      <Preview profile={profile} />
    </div>
  )
}

export default App

Preview.js 是页面的右侧部分,并嵌入我们将要创建的PDF文档。

另外我们还有 PDFDownloadLink,它可以用来下载 pdf 文件。

import React from 'react'
import { Document, Page, PDFViewer, PDFDownloadLink } from '@react-pdf/renderer'
import LeftSection from './LeftSection'
import  RightSection from './RightSection'
import styles from '../styles'

const Preview = ({ profile }) => {
  return (
    <div style={{ flexGrow: 1 }}>
      <PDFViewer
        showToolbar={false}
        style={{
          width: '100%',
          height: '95%',
        }}
      >
        <Template profile={profile} />
      </PDFViewer>
      <PDFDownloadLink
        document={<Template profile={profile} />}
        fileName='somename.pdf'
      >
        {({ loading }) => (loading ? 'Loading document...' : 'Download now!')}
      </PDFDownloadLink>
    </div>
  )
}
// 创建文档组件
const Template = ({ profile }) => {
  return (
    <Document>
      <Page size='A4' style={styles.page}>
        <LeftSection profile={profile} />
        <RightSection about={profile.about} />
      </Page>
    </Document>
  )
}

export default Preview

我们可以直接设置 PDF 为 A4 纸尺寸。

import { StyleSheet } from '@react-pdf/renderer'

export default StyleSheet.create({
  page: {
    display: 'flex',
    flexDirection: 'row',
  },
  section_right: {
    margin: 10,
    padding: 10,
    paddingTop: 20,
    width: '75%',
  },
  section_left: {
    width: '25%',
    height: '100%',
    backgroundColor: '#084c41',
  },
  profile_container: {
    display: 'flex',
    flexDirection: 'column',
    alignItems: 'center',
    marginTop: '20',
    marginBottom: '20px',
    height: '150',
  },
  name_text: {
    paddingTop: '10px',
    paddingBottom: '5px',
    fontSize: '14px',
    fontWeight: '900',
    color: 'white',
  }
})

通过 StyleSheet.create 创建 JavaScript 样式表

LeftSection.js 代码展示

import { View, Text, Image, } from '@react-pdf/renderer'
import styles from '../styles'

export const Profile = ({ profile }) => {
  return (
    <View style={styles.profile_container}>
      <Image style={styles.profile_img} src={profile.avatar} />

      <View
        style={{
          justifyContent: 'center',
        }}
      >
        <Text style={styles.name_text}>{profile.name}</Text>
      </View>
      <Text style={styles.profession_text}>{profile.about}</Text>
    </View>
  )
}

const LeftSection = ({ profile }) => {
  return (
    <View style={styles.section_left}>
      <Profile profile={profile} />
    </View>
  )
}

export default LeftSection

也可以直接写内联样式控制 PDF 内的样式。但是不支持 float 浮动属性,具体大家可以看官网

遇到问题

本以为这样就可以完成,没想到还有一个巨坑,不支持中文,中文在 pdf 中会显示乱码, 通过 issue 找到了答案

import { StyleSheet, Font } from "@react-pdf/renderer";

Font.register({
  family: "Alibaba-PuHuiTi-Light",
  src: "/Alibaba-PuHuiTi-Light.ttf",
});

export const styles = StyleSheet.create({
  page: {
    fontFamily: "Alibaba-PuHuiTi-Light",
    flexDirection: "row",
    display: "flex",
    ...
  },
})

然后就可以显示中文字体了。这边我下载了阿里巴巴普惠体。

重构

以上是一个简易版的实现,通过上面的代码示例,你应该至少看懂了原理,为了让整个简历数据丰富,我使用了antd 来实现丰富的表单列表。使用 react context 来管理我们的数据。下面展示下目录结构:

├── components
│   ├── app
│   │   └── index.tsx
│   ├── editor
│   │   ├── FormCreator.tsx
│   │   ├── conifg.js
│   │   └── index.tsx
│   ├── icon
│   │   └── index.tsx
│   └── preview
│       ├── avatar.tsx
│       ├── awardList.tsx
│       ├── educationList.tsx
│       ├── index.tsx
│       ├── profile.tsx
│       ├── projectList.tsx
│       ├── skillList.tsx
│       ├── style.ts
│       └── workExpList.tsx
├── context
│   └── resumeContext.ts
├── hooks
│   └── useResume
│       └── index.ts
├── pages
│   ├── _app.tsx
│   ├── api
│   │   └── hello.js
│   └── index.tsx
└── styles
    ├── logo.png
    └── globals.css

仅供个人学习参考/导航指引使用,具体请以第三方网站说明为准,本站不提供任何专业建议。如果地址失效或描述有误,请联系站长反馈~感谢您的理解与支持!

链接: https://fly63.com/nav/3607

更多»
热门资源
swiper
目前应用较广泛的移动端网页触摸内容滑动js插件
官网
GitHub
layer
layer是一款口碑极佳的web弹层组件
点击进入
GitHub
iScroll.js
IScroll是移动页面上被使用的一款仿系统滚动插件。
官网
GitHub
wangEditor
基于javascript和css开发的 Web富文本编辑器
官网
GitHub
ueditor
由百度web前端研发部开发所见即所得富文本web编辑器
官网
GitHub
highlight
Highlight.js 是一个用 JavaScript 写的代码高亮插件,在客户端和服务端都能工作。
官网
GitHub
UglifyJS
一个js 解释器、最小化器、压缩器、美化器工具集
官网
GitHub
lozad.js
高性能,轻量级,可配置的懒加载图片工具
官网
GitHub
Sortable.js
简单灵活的 JavaScript 拖放排序插件
官网
GitHub
validate.js
表单提供了强大的验证功能,让客户端表单验证变得更简单
官网
GitHub
Draggin.js
一款兼容移动手机的js拖拽插件
官网
GitHub
lazysizes.js
响应式图像延迟加载JS插件【懒加载】
官网
GitHub
类似于react-pdf的资源
iziToast
优雅、响应式、灵活和轻量级的通知插件没有任何依赖
官网
GitHub
vue-cute-timeline
一个漂亮的Vue.js时间轴组件
官网
GitHub
number-flip
一款 js 数字翻转切换插件
官网
GitHub
idb
一个基本IndexedDB很小的库
点击进入
GitHub
react-datasheet
类似 Excel 数据表格的 react 组件
官网
GitHub
Seen.js
将3D场景渲染成SVG或HTML 5 Canvas
官网
GitHub
clipboard.js
浏览器中复制文本到剪贴板的插件,不需要Flash,仅仅2kb
官网
GitHub
angular-async-local-storage
适用于Angular和渐进式Web应用(PWA)的高效异步本地存储模块
点击进入
GitHub
目录

手机扫一扫预览

》
分享组件加载中...
首页 技术导航 在线工具 技术文章 教程资源 前端标签 AI工具集 前端库/框架 实用工具箱 广告合作 关于我们

Copyright © 2018 Web前端开发网提供免费在线工具、编程学习资源(教程/框架/库),内容以学习参考为主,助您解决各类实际问题,快速提升专业能力。