如何在react-native中创建pdf文件?

时间:2019-08-28 06:28:43

标签: react-native pdf pdflib

错误:null不是评估'_PDFLib.default.createPDF'的对象

https://github.com/Hopding/react-native-pdf-lib

我使用pdf库,您能告诉我为什么会发生错误吗?

如果您使用await(const docsDir = await PDFLib.getDocumentsDirectory();),则会收到如下错误消息:error-无法在异步函数外使用关键字“ await”。

如果您知道如何创建pdf文件,请告诉我。

    pdfButton = () => {
        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',
          });

//It's like a problem.
          // const docsDir = await PDFLib.getDocumentsDirectory();
          const pdfPath = './data/ex.pdf'; //path to create pdf folder
          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!
      });

1 个答案:

答案 0 :(得分:3)

pdfButton函数必须是异步函数

pdfButton = async () => {
    ...
    const docsDir = await PDFLib.getDocumentsDirectory();
    const pdfPath = `${docsDir}/ex.pdf`;
}