Files
convert/test/converters/imageToPdf.test.js
T

68 lines
2.3 KiB
JavaScript

import { describe, it, expect, beforeAll, afterAll } from 'vitest';
import fs from 'node:fs/promises';
import path from 'node:path';
import os from 'node:os';
import sharp from 'sharp';
import { registerImageToPdfConverter } from '../../src/converters/imageToPdf.js';
import { resolve, listTargetFormats } from '../../src/converters/registry.js';
import { detectInputMime } from '../../src/mime.js';
let tmpDir;
beforeAll(async () => {
registerImageToPdfConverter();
tmpDir = await fs.mkdtemp(path.join(os.tmpdir(), 'converter-image-to-pdf-'));
});
afterAll(async () => {
await fs.rm(tmpDir, { recursive: true, force: true });
});
describe('image to PDF converter', () => {
it('registers pdf as a target for every image format', () => {
expect(listTargetFormats('png')).toContain('pdf');
expect(listTargetFormats('jpg')).toContain('pdf');
});
it('converts a PNG fixture into a valid PDF', async () => {
const inputPath = path.join(import.meta.dirname, '..', 'fixtures', 'sample.png');
const outputPath = path.join(tmpDir, 'output.pdf');
const entry = resolve('png', 'pdf');
await entry.convert(inputPath, outputPath);
const detected = await detectInputMime(outputPath);
expect(detected.mime).toBe('application/pdf');
});
it('embeds a JPEG instead of a PNG when a quality is given, shrinking the output for a noisy image', async () => {
const inputPath = path.join(tmpDir, 'noisy.png');
await sharp({
create: {
width: 256,
height: 256,
channels: 3,
noise: { type: 'gaussian', mean: 128, sigma: 40 },
},
})
.png()
.toFile(inputPath);
const defaultOutputPath = path.join(tmpDir, 'default.pdf');
const compressedOutputPath = path.join(tmpDir, 'compressed.pdf');
const entry = resolve('png', 'pdf');
await entry.convert(inputPath, defaultOutputPath);
await entry.convert(inputPath, compressedOutputPath, { quality: 20 });
const compressedDetected = await detectInputMime(compressedOutputPath);
expect(compressedDetected.mime).toBe('application/pdf');
const [defaultStat, compressedStat] = await Promise.all([
fs.stat(defaultOutputPath),
fs.stat(compressedOutputPath),
]);
expect(compressedStat.size).toBeLessThan(defaultStat.size);
});
});