[TypeError: null is not an object (evaluating '_reactNativePdfLib.default.getDocumentsDirectory')]

时间:2021-04-18 03:43:32

标签: javascript reactjs react-native

我正在尝试使用 react-native-pdf-lib 在我的应用程序中创建 pdf,但我遇到了这个错误

[TypeError: null is not an object (evaluating '_reactNativePdfLib.default.getDocumentsDirectory')]

我的代码

 const page1 = PDFPage.create()
.setMediaBox(200, 200)
.drawText('You can add text and rectangles to the PDF!', {
  x: 5,
  y: 235,
  color: '#007386',
})
.drawRectangle({
  x: 25,
  y: 25,
  width: 150,
  height: 150,
  color: '#FF99CC',
})
.drawRectangle({
  x: 75,
  y: 75,
  width: 50,
  height: 50,
  color: '#99FFCC',
});
const handleCreatePdf = async () => {
try {
  const docsDir = await PDFLib.getDocumentsDirectory();
  const pdfPath = `${docsDir}/ex.pdf`;
  PDFDocument.create(pdfPath)
    .addPages(page1)
    .write() // Returns a promise that resolves with the PDF's path
    .then(path => {
      console.log('PDF created at: ' + path);
      // Do stuff with your shiny new PDF!
    })
    .catch(err => console.log(err));
} catch (error) {
  console.log(error);
}

};

任何线索是什么问题,或者可能的解决方案?

1 个答案:

答案 0 :(得分:0)

似乎是 PDFLib 对象的问题。

是否像这样正确导入?

import PDFLib, { PDFDocument, PDFPage } from 'react-native-pdf-lib';