5

I am trying to understand how one might get PDF Kit working within React JS.

My simple requirement is to render a file in the browser using ReactJS and PDFKit.

Looking at the tutorials, there are references to a few options in which PDFKit can work in the browser, however it is unclear how this would apply in the world of React JS and in particular a Create React App based project...

http://pdfkit.org/demo/browser.html

https://www.npmjs.com/package/pdfkit#browser-usage

Has anyone come across a working example with Create React App based React JS and PDFKit?

Google seems to be a bit short on answers this evening.

SecretAgentMan
  • 2,856
  • 7
  • 21
  • 41
Keaton Victor
  • 91
  • 1
  • 5

2 Answers2

2

I manage to find an answer for this.

It's a combination of this and this.

But just to give an overview/key codes. In my react application, I have this (make a post request to my API server):

            <Button
              onClick={(e) => {
                const { _id } = record;
                fetch(`/api/pdf`, {
                  method: 'POST',
                  headers: {
                    'Content-Type': 'application/json',
                  },
                  body: JSON.stringify({
                    filename: "test",
                    content: "Testing Content"
                  }),
                }).then(async res => {
                  if (res.status === 200) {
                    const blob = await res.blob();
                    const file = new Blob(
                      [blob], 
                      {type: 'application/pdf'}
                    );
                    //Build a URL from the file
                    const fileURL = URL.createObjectURL(file);
                    //Open the URL on new Window
                    window.open(fileURL);  
                  }
                })
            >    
              Download
            </Button>

And in the API server (node express application), I have this:

const postMethod = () => async (req, res, next) => {
   const doc = new PDFDocument()
   let filename = req.body.filename
   // Stripping special characters
   filename = encodeURIComponent(filename) + '.pdf'
   // Setting response to 'attachment' (download).
   // If you use 'inline' here it will automatically open the PDF
   res.setHeader('Content-disposition', 'attachment; filename="' + filename + '"')
   res.setHeader('Content-type', 'application/pdf')
   const content = req.body.content
   doc.y = 300
   doc.text(content, 50, 50)
   doc.pipe(res)
   doc.end()
}

eastmael
  • 371
  • 3
  • 7
2

I wanted to do exactly this (PdfKit client-side rendering in a React app bootstrapped with create-react-app). I managed to get it working using pdfkit-webpack-example and customize-cra.

Source

Live Demo

Joseph Sturtevant
  • 13,194
  • 12
  • 76
  • 90