尝试渲染pdf时出现React-pdf错误

3

我完全不了解ReactJs。

我正在尝试从HTML创建PDF。我想在浏览器中显示文档,然后能够下载它。我正在使用react-pdf https://react-pdf.org/

我有下面的代码,其中我创建了我的PDF文档,然后我想用PDFViewer显示我的文档。这个页面不是我的主要“App”页面 - 它是一个“客户详细信息”页面,我可以导航到该页面。

当我运行此代码时,我会得到以下错误:

类型错误:无法构造“Text”:请使用“new”操作符,此DOM对象构造函数无法作为函数调用。

错误出现在这里:renderWithHooks C:/Users/Marileen/Downloads/react-material-dashboard-master (1)/react-material-dashboard-master/node_modules/@react-pdf/renderer/node_modules/react-reconciler/cjs/react-reconciler.development.js:5671,具体是第5671行:var children = Component(props, refOrContext);

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

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

const ClientDetails = () => {
    return (<PDFViewer>
        <PdfDocument />
    </PDFViewer>);
}
export default ClientDetails;

我尝试了不同的库,安装了babel,但我不知道如何在Reactjs中解决问题。请帮忙吗?

错误在<Text>中。你从哪里导入它的? - Atin Singh
2个回答

4

在查看了react-pdf文档之后,似乎您没有从库中导入Text,但您正在组件中使用它。

这就是为什么当您在此行使用未导入的文本时会抛出错误的原因 -

<Text>Section #1</Text>

改变你的 -
import { Document, Page, View } from '@react-pdf/renderer'; //add Text here//

转至 -

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

哦我的天哪。这是一个新手错误吧。非常感谢。 - PouncingPoodle

0

我可能有点晚了,但我找到了一个最近的解决方案,如下所示:

import React from 'react';
import {Document, Page, pdfjs} from 'react-pdf';
import "react-pdf/dist/esm/Page/AnnotationLayer.css" // Blocks blank TextLayers.

pdfjs.GlobalWorkerOptions.workerSrc = `//cdnjs.cloudflare.com/ajax/libs/pdf.js/${pdfjs.version}/pdf.worker.js`; // Fix your issue.

function PdfFileReader() {
  const yourFileUrl_Or_Base64 = 'https://www.orimi.com/pdf-test.pdf'
  
  return(
    <Document
      file={yourFileUrl_Or_Base64}
    >
      <Page
        pageNumber={pages}
        renderTextLayer={false} // Blocks blank TextLayer
      />
    </Document>
  )
}


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接