【问题标题】:[TypeError: null is not an object (evaluating '_reactNativePdfLib.default.getDocumentsDirectory')][TypeError: null is not an object (evaluating '_reactNativePdfLib.default.getDocumentsDirectory')]
【发布时间】:2021-04-18 03:43:32
【问题描述】:

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

[TypeError: null 不是对象(评估'_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);
}

};

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

【问题讨论】:

  • 您能否提供更多有关错误显示的信息?喜欢正在记录的线路或其他信息?我相信这会更容易找出错误发生的位置。
  • @AndréGuimarãesAragon 我在控制台中从 catch 中得到的唯一错误是`LOG [TypeError: null is not an object (evalating '_reactNativePdfLib.default.getDocumentsDirectory')]`这是我唯一的错误

标签: javascript reactjs react-native


【解决方案1】:

我切换到了这个库...似乎更新了并且更易于使用 https://github.com/Anyline/react-native-image-to-pdf

import RNImageToPdf from 'react-native-image-to-pdf';

const myAsyncPDFFunction = async () => {
    try {
        const options = {
            imagePaths: imagePaths: ['/path/to/image1.png','/path/to/image2.png'],
            name: name: 'PDFName',
            maxSize: { // optional maximum image dimension - larger images will be resized
                width: 900,
                height: Math.round(deviceHeight() / deviceWidth() * 900),
            },
            quality: .7, // optional compression paramter
        };
        const pdf = await RNImageToPdf.createPDFbyImages(options);
        
        console.log(pdf.filePath);
    } catch(e) {
        console.log(e);
    }
}

【讨论】:

  • 请添加更多详细信息以扩展您的答案,例如工作代码或文档引用。
  • 我可以合并图像和 pdf 并从中创建一个新的 pdf 吗?
【解决方案2】:

似乎是 PDFLib 对象的问题。

这样导入正确吗?

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

【讨论】:

    猜你喜欢
    • 2020-04-05
    • 2022-12-21
    • 2023-02-18
    • 2022-12-03
    • 2019-11-02
    • 2020-07-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多