[StackOverflow/reactjs] Render a pdf in react that supports multiple languages and download it
Sponsored Content
### ROOT CAUSE
The issue arises from the need to render PDFs with multiple languages in a React application and enable downloading. The root cause is the lack of a proper PDF rendering and handling library that supports Unicode and internationalization, combined with incorrect handling of file paths for PDF.js.
### CODE FIX
Use `react-pdf` (built on top of PDF.js) to render and handle PDFs. Ensure the correct worker path is set for PDF.js to avoid CORS or path errors.
```jsx
import { Document, Page, pdfjs } from 'react-pdf';
import 'react-pdf/dist/Page/TextLayer.css';
// Set the correct worker path (critical for PDF.js)
pdfjs.GlobalWorkerOptions.workerSrc = 'https://cdnjs.cloudflare.com/ajax/libs/pdf.js/3.4.120/pdf.min.js';
function PDFViewer({ file }) {
const [numPages, setNumPages] = useState(null);
const [pageNumber, setPageNumber] = useState(1);
const onDocumentLoadSuccess = ({ numPages }) => {
setNumPages(numPages);
};
return (
);
}
```
### Key Fixes:
1. **PDF.js Worker Path**: Explicitly set the worker source to avoid default path issues.
2. **Internationalization**: PDF.js inherently supports Unicode. Ensure PDFs are encoded with UTF-8.
3. **Download Handling**: Use `window.open` or a direct anchor tag for downloading.
**Note**: For server-side PDF generation, use libraries like `pdfkit` or `jspdf` with proper Unicode support (e.g., `pdfkit` with `fontkit`).