Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@
"p-retry": "~4.6.0",
"tinyspawn": "~1.5.7",
"top-sites": "~1.1.224",
"unpdf": "~1.9.0"
"unpdf": "~2.1.0"
},
"devDependencies": {
"@browserless/test": "latest",
Expand Down Expand Up @@ -99,7 +99,7 @@
"typescript": "latest"
},
"engines": {
"node": ">= 22"
"node": ">= 24"
},
"files": [
"bin",
Expand Down
27 changes: 21 additions & 6 deletions src/pdf/media.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,11 @@ const { deflateSync } = require('node:zlib')
const MIN_SIDE = 16
const MAX_PIXELS = 400 * 400
const MAX_LOGO_SIDE = 256
const RGBA_CHANNELS = 4
const PNG_COLOR_TYPE_RGBA = 6
const PNG_BIT_DEPTH = 8
const OPAQUE = 255
const TRANSPARENT = 0

const crcTable = new Uint32Array(256)
for (let n = 0; n < 256; n++) {
Expand All @@ -30,19 +35,19 @@ const chunk = (type, data) => {
return Buffer.concat([length, body, crc])
}

/** Encode raw RGB/RGBA from unpdf into a PNG data URI. node:zlib only. */
const toPngDataUri = ({ width, height, channels, data }) => {
/** Encode the raw RGBA pixels unpdf extracts into a PNG data URI. node:zlib only. */
const toPngDataUri = ({ width, height, data }) => {
const source = Buffer.from(data.buffer, data.byteOffset, data.byteLength)
const stride = width * channels
const stride = width * RGBA_CHANNELS
const raw = Buffer.alloc((stride + 1) * height)
for (let y = 0; y < height; y++) {
source.copy(raw, y * (stride + 1) + 1, y * stride, y * stride + stride)
}
const ihdr = Buffer.alloc(13)
ihdr.writeUInt32BE(width, 0)
ihdr.writeUInt32BE(height, 4)
ihdr[8] = 8
ihdr[9] = channels === 4 ? 6 : 2
ihdr[8] = PNG_BIT_DEPTH
ihdr[9] = PNG_COLOR_TYPE_RGBA
const png = Buffer.concat([
Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]),
chunk('IHDR', ihdr),
Expand All @@ -52,6 +57,16 @@ const toPngDataUri = ({ width, height, channels, data }) => {
return `data:image/png;base64,${png.toString('base64')}`
}

/** An image mask has no color of its own: unpdf paints it opaque black on transparent. */
const isStencil = ({ data }) => {
for (let offset = 0; offset < data.length; offset += RGBA_CHANNELS) {
if (data[offset] || data[offset + 1] || data[offset + 2]) return false
const alpha = data[offset + 3]
if (alpha !== OPAQUE && alpha !== TRANSPARENT) return false
}
return true
}

const usable = images =>
images.filter(
img =>
Expand All @@ -60,7 +75,7 @@ const usable = images =>
img.width >= MIN_SIDE &&
img.height >= MIN_SIDE &&
img.width * img.height <= MAX_PIXELS &&
(img.channels === 3 || img.channels === 4)
!isStencil(img)
)

const isLogo = img =>
Expand Down
49 changes: 43 additions & 6 deletions test/pdf/helpers.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ const PAGE_WIDTH = 612
const PAGE_HEIGHT = 792
const TOP_MARGIN = 72
const LEFT_MARGIN = 72
const FIRST_IMAGE_OBJECT = 7
const MASK_ROW_PATTERN = ['00', 'ff']

const escapeText = text => text.replace(/([\\()])/g, '\\$1')

Expand All @@ -21,23 +23,58 @@ const toStream = lines => {
return operations.join('\n')
}

const toHex = byte => byte.toString(16).padStart(2, '0')

const imageSamples = ({ width, height, color, mask }) => {
if (mask) {
const rowBytes = Math.ceil(width / 8)
return Array.from({ length: height }, (_, row) =>
MASK_ROW_PATTERN[row % MASK_ROW_PATTERN.length].repeat(rowBytes)
).join('')
}
return color
.map(toHex)
.join('')
.repeat(width * height)
}

const imageObject = image => {
const samples = `${imageSamples(image)}>`
const format = image.mask
? '/ImageMask true /BitsPerComponent 1'
: '/ColorSpace /DeviceRGB /BitsPerComponent 8'
return `<< /Type /XObject /Subtype /Image /Width ${image.width} /Height ${image.height} ${format} /Filter /ASCIIHexDecode /Length ${samples.length} >>\nstream\n${samples}\nendstream`
}

const paintImages = images =>
images.map(
({ width, height }, index) =>
`q ${width} 0 0 ${height} ${LEFT_MARGIN} ${TOP_MARGIN} cm /Im${index} Do Q`
)

/**
* Builds a one page PDF out of `{ text, size }` lines, so tests exercise the
* real parser without committing binaries to the repository.
* Builds a one page PDF out of `{ text, size }` lines, plus optional
* `{ width, height, color: [r, g, b] }` images or `{ width, height, mask: true }`
* image masks, so tests exercise the real parser without committing binaries
* to the repository.
*/
const createPdf = (lines, { info = {} } = {}) => {
const stream = toStream(lines)
const createPdf = (lines, { info = {}, images = [] } = {}) => {
const stream = [toStream(lines), ...paintImages(images)].join('\n')
const xobjects = images
.map((_, index) => `/Im${index} ${FIRST_IMAGE_OBJECT + index} 0 R`)
.join(' ')
const infoEntries = Object.entries(info)
.map(([key, value]) => `/${key} (${escapeText(String(value))})`)
.join(' ')

const objects = [
'<< /Type /Catalog /Pages 2 0 R >>',
'<< /Type /Pages /Kids [3 0 R] /Count 1 >>',
`<< /Type /Page /Parent 2 0 R /MediaBox [0 0 ${PAGE_WIDTH} ${PAGE_HEIGHT}] /Resources << /Font << /F1 5 0 R >> >> /Contents 4 0 R >>`,
`<< /Type /Page /Parent 2 0 R /MediaBox [0 0 ${PAGE_WIDTH} ${PAGE_HEIGHT}] /Resources << /Font << /F1 5 0 R >> /XObject << ${xobjects} >> >> /Contents 4 0 R >>`,
`<< /Length ${stream.length} >>\nstream\n${stream}\nendstream`,
'<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>',
`<< ${infoEntries} >>`
`<< ${infoEntries} >>`,
...images.map(imageObject)
]

let pdf = '%PDF-1.4\n'
Expand Down
59 changes: 58 additions & 1 deletion test/pdf/index.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
'use strict'

const { extractPdfSafe, isPdf, isPdfLink, pdfToHtml } = require('../..')
const { inflateSync } = require('node:zlib')

const { extractPdf, extractPdfSafe, isPdf, isPdfLink, pdfToHtml } = require('../..')
const { runServer, test } = require('../helpers')
const { createPdf } = require('./helpers')
const { scrapePdf } = require('./scrape')
Expand Down Expand Up @@ -54,6 +56,61 @@ const JOURNAL = createPdf([
}
])

const JOURNAL_URL = 'https://journals.plos.org/plosone/article/file?id=10.1371/x&type=printable'
const FIGURE_SIDE = 32
const FIGURE_COLOR = [200, 30, 60]
const PNG_COLOR_TYPE_RGBA = 6

const decodePng = dataUri => {
const png = Buffer.from(dataUri.replace('data:image/png;base64,', ''), 'base64')
const idatLength = png.readUInt32BE(33)
return {
width: png.readUInt32BE(16),
height: png.readUInt32BE(20),
colorType: png[25],
scanlines: inflateSync(png.subarray(41, 41 + idatLength))
}
}

const PNG_FILTER_NONE = 0
const OPAQUE = 255

const solidScanlines = (side, color) => {
const row = [PNG_FILTER_NONE]
for (let column = 0; column < side; column++) row.push(...color, OPAQUE)
return Buffer.from(Array.from({ length: side }, () => row).flat())
}

const paperWith = image =>
createPdf([{ text: 'Figures of a paper', size: 14 }], {
images: [{ width: FIGURE_SIDE, height: FIGURE_SIDE, ...image }]
})

test('a picture painted on the first page is the image and the logo, as RGBA', async t => {
const { image, logo } = await extractPdf({
url: JOURNAL_URL,
pdf: paperWith({ color: FIGURE_COLOR })
})

t.is(logo, image)
t.deepEqual(decodePng(image), {
width: FIGURE_SIDE,
height: FIGURE_SIDE,
colorType: PNG_COLOR_TYPE_RGBA,
scanlines: solidScanlines(FIGURE_SIDE, FIGURE_COLOR)
})
})

test('an image mask is neither the image nor the logo', async t => {
const { image, logo } = await extractPdf({ url: JOURNAL_URL, pdf: paperWith({ mask: true }) })

t.is(image, null)
t.is(
logo,
`https://www.google.com/s2/favicons?domain_url=${encodeURIComponent(JOURNAL_URL)}&sz=128`
)
})

test('isPdfLink only accepts a PDF url', t => {
t.true(isPdfLink('https://arxiv.org/pdf/1706.03762v7'))
t.true(isPdfLink('https://example.com/paper.pdf'))
Expand Down
46 changes: 23 additions & 23 deletions test/pdf/snapshots/fixtures.js.md
Original file line number Diff line number Diff line change
Expand Up @@ -108,9 +108,9 @@ Generated by [AVA](https://avajs.dev).
author: 'Giovanni Colavizza',
date: '2020-04-21T03:37:32.000Z',
description: 'Efforts to make research results open and reproducible are increasingly reflected by journal policies encouraging or mandating authors to provide data availability statements. As a consequence of this, there has been a strong uptake of data availability statements in recent literature.',
image: 'data:image/png;base64…1810',
image: 'data:image/png;base64…1914',
lang: 'en',
logo: 'data:image/png;base64…1810',
logo: 'data:image/png;base64…1914',
publisher: 'PLOS ONE',
title: 'The citation advantage of linking publications to research data',
url: 'https://journals.plos.org/plosone/article/file?id=10.1371/journal.pone.0230416&type=printable',
Expand Down Expand Up @@ -220,9 +220,9 @@ Generated by [AVA](https://avajs.dev).
author: 'Qiang Zhang',
date: '2020-04-24T03:36:38.000Z',
description: 'Background: Influenza is a severe respiratory illness that continually threatens global health. It has been widely known that gut microbiota modulates the host response to protect against influenza infection, but mechanistic details remain largely unknown.',
image: 'data:image/png;base64…15142',
image: 'data:image/png;base64…14822',
lang: 'en',
logo: 'data:image/png;base64…342',
logo: 'data:image/png;base64…358',
publisher: 'Springer',
title: 'Influenza infection elicits an expansion of gut population of endogenous Bifidobacterium animalis which protects mice against infection',
url: 'https://link.springer.com/content/pdf/10.1186/s13059-020-02007-1.pdf',
Expand Down Expand Up @@ -300,9 +300,9 @@ Generated by [AVA](https://avajs.dev).
author: 'Zayra Elisa Carvajal-Portuguez',
date: '2013-01-01T00:00:00.000Z',
description: 'Enseñanza del inglés en secundaria: una propuesta innovadora. Educación Carvajal-Portuguez, Zayra Elisa vol. 37, núm. 2, julio-diciembre, 2013, pp. 79-101 Universidad de Costa Rica San Pedro, Montes de Oca, Costa Rica',
image: 'data:image/png;base64…2574',
image: 'data:image/png;base64…2658',
lang: 'es',
logo: 'data:image/png;base64…15010',
logo: 'data:image/png;base64…15278',
publisher: 'Redalyc',
title: 'Enseñanza del inglés en secundaria: una propuesta innovadora',
url: 'https://www.redalyc.org/pdf/440/44029444004.pdf',
Expand Down Expand Up @@ -364,9 +364,9 @@ Generated by [AVA](https://avajs.dev).
author: 'Nathalie Percie du Sert',
date: '2020-07-11T04:57:33.000Z',
description: 'Reproducible science requires transparent reporting. The ARRIVE guidelines (Animal Research: Reporting of In Vivo Experiments) were originally developed in 2010 to improve the reporting of animal research.',
image: 'data:image/png;base64…1810',
image: 'data:image/png;base64…1914',
lang: 'en',
logo: 'data:image/png;base64…1810',
logo: 'data:image/png;base64…1914',
publisher: 'PLOS BIOLOGY',
title: 'The ARRIVE guidelines 2.0: Updated guidelines for reporting animal research',
url: 'https://journals.plos.org/plosbiology/article/file?id=10.1371/journal.pbio.3000410&type=printable',
Expand Down Expand Up @@ -476,9 +476,9 @@ Generated by [AVA](https://avajs.dev).
author: 'Nandan Thakur',
date: '2021-04-01T00:00:00.000Z',
description: 'Existing neural information retrieval (IR) models have often been studied in homogeneous and narrow settings, which has considerably limited insights into their out-of-distribution (OOD) generalization capabilities.',
image: 'data:image/png;base64…11398',
image: 'data:image/png;base64…11782',
lang: 'en',
logo: 'data:image/png;base64…11398',
logo: 'data:image/png;base64…11782',
publisher: 'arXiv',
title: 'BEIR: A Heterogeneous Benchmark for Zero-shot Evaluation of Information Retrieval Models',
url: 'https://arxiv.org/pdf/2104.08663v4',
Expand Down Expand Up @@ -636,9 +636,9 @@ Generated by [AVA](https://avajs.dev).
author: 'Matthew J. Page',
date: '2021-03-24T09:31:13.000Z',
description: 'points complete, and accurate account of why the review was done, what they did, and what they found PLOS MEDICINE (UG1EY020522), National Institutes of Health, United States. LAM is supported by a National Institute for Health Research Doctoral Research Fellowship (DRF-2018-11-ST2-048).',
image: 'data:image/png;base64…1810',
image: 'data:image/png;base64…1914',
lang: 'en',
logo: 'data:image/png;base64…1810',
logo: 'data:image/png;base64…1914',
publisher: 'PLOS Medicine',
title: 'The PRISMA 2020 statement: An updated guideline for reporting systematic reviews',
url: 'https://journals.plos.org/plosmedicine/article/file?id=10.1371/journal.pmed.1003583&type=printable',
Expand All @@ -652,9 +652,9 @@ Generated by [AVA](https://avajs.dev).
author: 'Greg Wilson',
date: '2017-06-21T09:08:26.000Z',
description: 'Computers are now essential in all branches of science, but most researchers are never taught the equivalent of basic lab skills for research computing.',
image: 'data:image/png;base64…1070',
image: 'data:image/png;base64…1150',
lang: 'en',
logo: 'data:image/png;base64…1070',
logo: 'data:image/png;base64…1150',
publisher: 'PLOS Computational Biology',
title: 'Good enough practices in scientific computing',
url: 'https://journals.plos.org/ploscompbiol/article/file?id=10.1371/journal.pcbi.1005510&type=printable',
Expand Down Expand Up @@ -684,7 +684,7 @@ Generated by [AVA](https://avajs.dev).
author: 'Yu Xie',
date: '2020-01-21T06:02:46.000Z',
description: 'Networks, such as social networks, biochemical networks, and protein-protein interaction networks are ubiquitous in the real world.',
image: 'data:image/png;base64…1610',
image: 'data:image/png;base64…1978',
lang: 'en',
logo: 'https://www.google.com/s2/favicons?domain_url=https%3A%2F%2Fwww.frontiersin.org%2Farticles%2F10.3389%2Ffnins.2020.00001%2Fpdf&sz=128',
publisher: 'Frontiers in Neuroscience',
Expand Down Expand Up @@ -732,9 +732,9 @@ Generated by [AVA](https://avajs.dev).
author: 'Helen Le Sueur',
date: '2020-06-23T14:17:55.000Z',
description: 'Background: Individual clinical trials and cohort studies are a useful source of data, often under-utilised once a study has ended.',
image: 'data:image/png;base64…22214',
image: 'data:image/png;base64…21578',
lang: 'en',
logo: 'data:image/png;base64…302',
logo: 'data:image/png;base64…322',
publisher: 'Springer',
title: 'The challenges in data integration – heterogeneity and complexity in clinical trials and patient registries of Systemic Lupus Erythematosus',
url: 'https://link.springer.com/content/pdf/10.1186/s12874-020-01057-0.pdf',
Expand All @@ -748,9 +748,9 @@ Generated by [AVA](https://avajs.dev).
author: 'Josef Zelinka',
date: '2022-09-08T19:32:41.000Z',
description: 'For autonomous robots operating in an unknown environment, it is important to assess the traversability of the surrounding terrain to improve path planning and decision-making on where to navigate next in a cost-efficient way.',
image: 'data:image/png;base64…1658',
image: 'data:image/png;base64…1934',
lang: 'en',
logo: 'data:image/png;base64…26950',
logo: 'data:image/png;base64…27178',
publisher: 'CEUR-WS',
title: 'Deep Transfer Learning of Traversability Assessment for Heterogeneous Robots',
url: 'https://ceur-ws.org/Vol-3226/paper1.pdf',
Expand All @@ -764,9 +764,9 @@ Generated by [AVA](https://avajs.dev).
author: 'Begoña Martínez Domínguez',
date: '2009-01-01T00:00:00.000Z',
description: 'UNA OPORTUNIDAD PARA QUE JÓVENES QUE FRACASAN EN LA ESCUELA PUEDAN SALIR DE LA ZONA DE RIESGO DE EXCLUSIÓN. LA EXPERIENCIA DE LOS CENTROS DE INICIACIÓN PROFESIONAL EN LA COMUNIDAD AUTÓNOMA VASCA. Profesorado. Revista de Currículum y Formación de Profesorado Martínez Domínguez, Begoña; Mendizábal Ituarte, Amaia; Sostoa Gaztelu-Urrutia, Virginia P. vol. 13, núm. 3, 2009, pp. 239-271 Universidad de Granada Granada, España',
image: 'data:image/png;base64…2574',
image: 'data:image/png;base64…2658',
lang: 'es',
logo: 'data:image/png;base64…21742',
logo: 'data:image/png;base64…22014',
publisher: 'Redalyc',
title: 'UNA OPORTUNIDAD PARA QUE JÓVENES QUE FRACASAN EN LA ESCUELA PUEDAN SALIR DE LA ZONA DE RIESGO DE EXCLUSIÓN. LA EXPERIENCIA DE LOS CENTROS DE INICIACIÓN PROFESIONAL EN LA COMUNIDAD AUTÓNOMA VASCA',
url: 'https://www.redalyc.org/pdf/567/56712871011.pdf',
Expand All @@ -780,9 +780,9 @@ Generated by [AVA](https://avajs.dev).
author: 'Lucile Mégret',
date: '2020-02-24T02:45:03.000Z',
description: 'Background: MicroRNA (miRNA) regulation is associated with several diseases, including neurodegenerative diseases. Several approaches can be used for modeling miRNA regulation. However, their precision may be limited for analyzing multidimensional data.',
image: 'data:image/png;base64…34334',
image: 'data:image/png;base64…33190',
lang: 'en',
logo: 'data:image/png;base64…302',
logo: 'data:image/png;base64…322',
publisher: 'BMC',
title: 'Combining feature selection and shape analysis uncovers precise rules for miRNA regulation in Huntington’s disease mice',
url: 'https://bmcbioinformatics.biomedcentral.com/counter/pdf/10.1186/s12859-020-3418-9.pdf',
Expand Down
Binary file modified test/pdf/snapshots/fixtures.js.snap
Binary file not shown.
Loading
Loading