0

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

};

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

4

2 回答 2

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);
    }
}
于 2021-08-27T09:56:39.683 回答
0

似乎是 PDFLib 对象的问题。

是这样正确导入的吗?

import PDFLib, { PDFDocument, PDFPage } from 'react-native-pdf-lib';
于 2021-04-18T09:01:02.850 回答