Skip to content

Instantly share code, notes, and snippets.

@nickbreaton
Created November 19, 2020 23:32
Show Gist options
  • Select an option

  • Save nickbreaton/efd29b1bc7ddb2bf0ee0ac9b0eccb70c to your computer and use it in GitHub Desktop.

Select an option

Save nickbreaton/efd29b1bc7ddb2bf0ee0ac9b0eccb70c to your computer and use it in GitHub Desktop.
import inBrowser from './inBrowser'
export const isFirefoxWithPDFJS = () => {
if (!inBrowser()) return false
const userAgent = navigator.userAgent
if (userAgent.indexOf('irefox') === -1) return false
// Firefox 19 or greater has PDF.js
return parseInt(userAgent.split('rv:')[1].split('.')[0], 10) > 18
}
export const supportsPdfs = () => {
if (!inBrowser()) return false
return isFirefoxWithPDFJS() || navigator.userAgent.indexOf('CriOS') > -1 || 'application/pdf' in navigator.mimeTypes
}
export const getPdfBlob = (data: string) => {
if (!inBrowser()) return null
const byteCharacters = atob(data)
const byteNumbers = byteCharacters.split('').map((_, i) => byteCharacters.charCodeAt(i))
const byteArray = new Uint8Array(byteNumbers)
return new Blob([byteArray], { type: 'application/pdf' })
}
export const openPdfObjectUrl = (data: string) => {
if (!inBrowser()) return null
const blob = getPdfBlob(data)
const url = window.URL.createObjectURL(blob)
window.open(url)
}
import { supportsPdfs, getPdfBlob, openPdfObjectUrl } from '../utils/pdf'
import { isDesktopChrome, isNativeAndroid } from '../utils/browserChecker'
import { isEmbedded, showNativePdf } from '../utils/embedded'
import navigate from '../utils/navigate'
import Routes from '../routes'
const PdfOpener = ({ children, url, data, mimeType, title = '', fileName }) => {
const dataUrl = `data:${mimeType};base64,${data}`
const openPdf = () => {
if (isEmbedded()) {
showNativePdf({ url, data, title })
} else if (isNativeAndroid()) {
navigate(Routes.PDF_UNAVAILABLE)
} else if (navigator.msSaveOrOpenBlob) {
//if IE save as blob
const msBlob = getPdfBlob(data)
navigator.msSaveOrOpenBlob(msBlob, fileName)
} else if (
supportsPdfs() &&
!isDesktopChrome() /* Desktop Chrome's CSP doesn't allow data urls in object tags */
) {
const win = window.open()
win.document.write(`
<!DOCTYPE html>
<head>
<title>${title}</title>
</head>
<body style="margin:0;">
<object
data="${dataUrl}"
type="${mimeType}"
style="float:left;width:100%;height:100vh;"
>
</object>
</body>
`)
} else {
openPdfObjectUrl(data)
}
}
const openNativePdfOnClick = (e) => {
if (isEmbedded()) {
e.preventDefault()
showNativePdf({ url, data, title })
return false
}
return true
}
return children({ openPdf, dataUrl, supportsPdfs, openNativePdfOnClick })
}
export default PdfOpener
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment