Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to create pdf file in react-native?

error : null is not an object evaluating '_PDFLib.default.createPDF'

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

I use the pdf library, can you tell me why the error occurs?

If you use await(const docsDir = await PDFLib.getDocumentsDirectory();), you get an error message like this: error - Can not use keyword 'await' outside an async function.

If you know how to create a pdf file, please let me know.

    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!
      });
like image 401
김회준 Avatar asked Sep 20 '25 22:09

김회준


1 Answers

The pdfButton function must be an async function

pdfButton = async () => {
    ...
    const docsDir = await PDFLib.getDocumentsDirectory();
    const pdfPath = `${docsDir}/ex.pdf`;
}
like image 199
Vishnudev Avatar answered Sep 22 '25 14:09

Vishnudev