reactjs - React-pdf utf8 字体在即时渲染时不起作用,但在渲染时工作正常

标签 reactjs pdf react-pdf

我的问题是我试图用“on-fly-rendering”保存 pdf 文件,而 utf8 字体不起作用。但是在渲染中显示相同的 pdf 时效果很好。

创建 PDF:

Font.register({
  family: "Roboto",
  src:
    "https://cdnjs.cloudflare.com/ajax/libs/ink/3.1.10/fonts/Roboto/roboto-light-webfont.ttf"
});

const styles = StyleSheet.create({
  page: {
    flexDirection: 'row',
    backgroundColor: '#E4E4E4',
    fontFamily: "Roboto",
    
  },
  section: {
    margin: 10,
    padding: 10,
    flexGrow: 1
  }
});

显示并保存 pdf:

              <PDFViewer>
                <MyDocument data={data} />
              </PDFViewer>
              <PDFDownloadLink document={<MyDocument data={data}/>} fileName="lista_składników.pdf">
            {({ blob, url, loading, error }) => (loading ? 'Loading document...' : 'zapisz pdf')}
          </PDFDownloadLink>

使用 PDFViewer 输出: enter image description here

使用 PDFDownloadLink 输出:enter image description here

最佳答案

当只有第一个 PDFDownloadLink 注册了字体时,我遇到了同样的问题。在第二个字体中,字体不起作用。

我最终使用了一种更好的方法 - 通过单击按钮生成 PDF,而不是在加载组件时生成 PDF。

https://github.com/diegomura/react-pdf/issues/736

import { saveAs } from 'file-saver';
import { pdf, Page, Text, View, Document } from '@react-pdf/renderer';

const generatePdfDocument = async (fileName, pdfDocumentComponent) => {
    const blob = await pdf(pdfDocumentComponent).toBlob();
    saveAs(blob, fileName);
};

const MyDocument = () => (
    <Document>
        <Page size="A4">
            <View>
                <Text>Section #1</Text>
            </View>
        </Page>
    </Document>
);

const DownloadButton = () => (
    <button
        type="button"
        onClick={() => {
            generatePdfDocument('MyDocument.pdf', <MyDocument />);
        }}
    >
        Download PDF
    </button>
);

export default DownloadButton;

关于reactjs - React-pdf utf8 字体在即时渲染时不起作用,但在渲染时工作正常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69862884/

相关文章:

r - png 和 pdf 图的导出之间的差异

reactjs - 将 React 生成的 pdf 上传到谷歌驱动器

reactjs - 未处理的拒绝 (TypeError) : _nbind. externalList[num].dereference 不是函数

reactjs - 开 Jest 测试一个 React 类方法被 componentWillMount 调用

reactjs - react /AG-GRID : Dynamically setting columnDefs after retrieving data

javascript - Electron:如何安全地将全局变量注入(inject) BrowserWindow/BrowserView?

java - 如何使用 PDFBOX 从 pdf 中删除整个书签

css - 如何使用 CSS 在 ReactJS 中将图像居中

ruby-on-rails - 寻找网络 pdf 查看器,而不是 google 文档查看器

reactjs - react-pdf中EOF后出现错误: stream. push()