3

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 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

2 Comments

That only applies when using the next/image component directly, which doesn't seem the case here.
@juliomalves You're right. The thing is, react-pdf generates a svg image from the PDF file.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.