开发者问题收集

[TypeError:null 不是对象(正在评估‘_reactNativePdfLib.default.getDocumentsDirectory’)]

2021-04-18
1430

我正在尝试使用 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);
}

};

有什么线索可以解决该问题吗?

2个回答

我已切换到这个库...似乎更新且更易于使用 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);
    }
}
o0bnji0o
2021-08-27

PDFLib 对象似乎有问题。

这样可以正确导入吗?

import PDFLib, { PDFDocument, PDFPage } from 'react-native-pdf-lib';
greggailly
2021-04-18