Displaying pdf file using react-pdf from external source with NextJs

Viewed 1512

Hi i was using NextJs and trying to display pdf file within the web, i was using react-pdf for the package. When using

<Document 
  file={"http://example.com/sample.pdf"}
  onSourceError={(err) => console.log('source err', err)}
  onLoadError={err => console.log('load err', err)}
  >
<Page
  pageNumber={pageNumber}
  width={width}
/>

i was having a CORS problem, so i was trying to solve it using NextJs API Routes

api/pdf.js

const request = require('request');

export default (req, res) => {
    return new Promise(resolve => {
        res.statusCode = 200
        res.setHeader('Content-Length', 99999);
        res.setHeader('Content-Type', 'application/pdf')
        res.setHeader('Content-Disposition', 'attachment; filename=quote.pdf');

        let { parentid } = req.headers;
        
        switch (true) {
            case req.method === 'GET':
                console.log('GET')
                request.get('http://example.com/sample.pdf', {}, function (err, response, body) {
                    if (err) {
                        console.log('err', err)
                        res.status(500).json({ code: 'Internal Server Error' })
                        resolve();
                    } else {
                        res.status(200).send(body)
                        resolve()
                    }

                })
                break;
            default:
                res.status(400).json({ code: 'MethodNotAllowed' })
                break;
        }
    })
}

I tried it in insomnia and i do get a pdf response, but the file is blank,

Does anybody know how to solve this? or there any other options than this? Thanks

1 Answers

react-pdf displays the pages as images. So, you have to add the domain example.com to Next image config as mentioned in https://nextjs.org/docs/basic-features/image-optimization#domains

Related