jsx-pdf icon indicating copy to clipboard operation
jsx-pdf copied to clipboard

Error: The root element must resolve to a <document>, actually resolved to undefined

Open KirankumarDafda opened this issue 3 years ago • 1 comments

I tried to generate pdf in my react js web app with the simple code

  const stream = PDFMake.createPdfKitDocument(
        JsxPdf.renderPdf(
            <document defaultStyle={{ font: 'OpenSans', fontSize: 12 }}>
                <content>This will appear in my PDF!</content>
            </document>,
        ),
      );
      
      // write the stream to a file; this could also be streamed to an HTTP connection, stdout etc
      stream.on('finish', () => console.log('PDF generated'));
      stream.pipe(fs.createWriteStream('test.pdf'));
      stream.end();

But I am getting error of Root element must be a < document >, so is there anything I am missing in the code? Please suggest a solution.

KirankumarDafda avatar Sep 03 '21 05:09 KirankumarDafda

I was able to get a PDF to render with the example (added some additional logging and changed "finish" to "end"):

import PDFMake from 'pdfmake';
import JsxPdf from 'jsx-pdf';
import { OpenSans } from './font-descriptors';
import fs from 'fs'

console.log("Running...");

const pdfMake = new PDFMake({
  OpenSans,
});

const stream = pdfMake.createPdfKitDocument(
  JsxPdf.renderPdf(
    <document defaultStyle={{ font: 'OpenSans', fontSize: 12 }}>
      <content>This will appear in my PDF!</content>
    </document>,
  ),
);

// write the stream to a file; this could also be streamed to an HTTP connection, stdout etc
stream.on('end', () => console.log('PDF generated'));
stream.on('error', (e) => console.log(e, 'asdf'));
const p = new Promise(fulfill => stream.on("end", () => fulfill()));
stream.pipe(fs.createWriteStream('./test.pdf'));
stream.end();

(async () => {
  console.log("Pending");
  await p;
  console.log("Done")
})();

rob-mccann avatar Feb 27 '22 12:02 rob-mccann