π₯ π₯ π₯ A Free & Self-hostable Airtable Alternative
TypeScript airtableairtable-alternativeautomatic-apihacktoberfestlow-codeno-codeno-code-databaseno-code-platformpostgresqlrest-apirestful-apispreadsheetsqliteswagger
feat: add PDF thumbnail generation support
DarkPhoenix2704ce7a9264757f
diff --git a/packages/nocodb/src/Noco.ts b/packages/nocodb/src/Noco.tsindex 36c42ef1ca..cb8125044d 100644--- a/packages/nocodb/src/Noco.ts+++ b/packages/nocodb/src/Noco.ts@@ -23,6 +23,7 @@ import { getAppUrl } from '~/utils/appUrl';import { DataReflection, Integration } from '~/models';import { getRedisURL } from '~/helpers/redisHelpers';import { RedisIoAdapter } from '~/gateways/RedisIoAdapter';+import { definePDFJSModule } from 'unpdf';dotenv.config();declare const module: any;@@ -58,6 +59,8 @@ export default class Noco {protected requestContext: any;public static sharp: typeof Sharp;+ public static canvas: any;+ public static isPdfjsInitialized: boolean;constructor() {process.env.PORT = process.env.PORT || '8080';@@ -146,6 +149,17 @@ export default class Noco {);}+ try {+ this.canvas = await import('@napi-rs/canvas');+ await definePDFJSModule(() => import('pdfjs-dist/legacy/build/pdf.mjs'));+ this.isPdfjsInitialized = true;+ } catch (e) {+ console.error(e);+ console.error(+ 'Canvas is not available for your platform, thumbnail generation will be skipped',+ );+ }+if (process.env.NC_WORKER_CONTAINER === 'true') {if (!getRedisURL()) {throw new Error('NC_REDIS_URL is required');diff --git a/packages/nocodb/src/db/BaseModelSqlv2.ts b/packages/nocodb/src/db/BaseModelSqlv2.tsindex 8ab0c7e74d..e09eb37c80 100644--- a/packages/nocodb/src/db/BaseModelSqlv2.ts+++ b/packages/nocodb/src/db/BaseModelSqlv2.ts@@ -5609,7 +5609,7 @@ class BaseModelSqlv2 implements IBaseModelSqlV2 {}),);- if (!lookedUpAttachment.mimetype?.startsWith('image/')) {+ if (!lookedUpAttachment.mimetype?.startsWith('image/') && !lookedUpAttachment.mimetype.startsWith('application/pdf')) {continue;}@@ -5651,7 +5651,7 @@ class BaseModelSqlv2 implements IBaseModelSqlV2 {}),);- if (!lookedUpAttachment.mimetype?.startsWith('image/')) {+ if (!lookedUpAttachment.mimetype?.startsWith('image/') && !lookedUpAttachment.mimetype.startsWith('application/pdf')) {continue;}@@ -5692,7 +5692,7 @@ class BaseModelSqlv2 implements IBaseModelSqlV2 {}),);- if (!attachment.mimetype?.startsWith('image/')) {+ if (!attachment.mimetype?.startsWith('image/') && !attachment.mimetype.startsWith('application/pdf')) {continue;}diff --git a/packages/nocodb/src/modules/jobs/jobs/thumbnail-generator/thumbnail-generator.processor.ts b/packages/nocodb/src/modules/jobs/jobs/thumbnail-generator/thumbnail-generator.processor.tsindex 034e39aad4..d6bc5b2583 100644--- a/packages/nocodb/src/modules/jobs/jobs/thumbnail-generator/thumbnail-generator.processor.ts+++ b/packages/nocodb/src/modules/jobs/jobs/thumbnail-generator/thumbnail-generator.processor.ts@@ -2,6 +2,7 @@ import path from 'path';import { Readable } from 'stream';import { Logger } from '@nestjs/common';import slash from 'slash';+import { renderPageAsImage } from 'unpdf';import type { IStorageAdapterV2 } from '~/types/nc-plugin';import type { Job } from 'bull';import type { AttachmentResType, PublicAttachmentScope } from 'nocodb-sdk';@@ -13,6 +14,91 @@ import Noco from '~/Noco';export class ThumbnailGeneratorProcessor {private logger = new Logger(ThumbnailGeneratorProcessor.name);+ private isPdfFile(attachment: AttachmentResType): boolean {+ return (+ attachment.mimetype === 'application/pdf' ||+ (attachment.title && attachment.title.toLowerCase().endsWith('.pdf'))+ );+ }++ private async generatePdfThumbnail(+ file: Buffer,+ relativePath: string,+ storageAdapter: IStorageAdapterV2,+ ): Promise<{ [key: string]: string }> {+ try {+ const imageBuffer = await renderPageAsImage(+ new Uint8Array(file),+ 1,+ {+ canvasImport: () => Noco.canvas,+ scale: 4.0,+ },+ );++ const thumbnailPaths = {+ card_cover: path.join(+ 'nc',+ 'thumbnails',+ relativePath,+ 'card_cover.jpg',+ ),+ small: path.join('nc', 'thumbnails', relativePath, 'small.jpg'),+ tiny: path.join('nc', 'thumbnails', relativePath, 'tiny.jpg'),+ };++ const sharp = Noco.sharp;+ if (!sharp) {+ return null;+ }++ const sharpImage = sharp(Buffer.from(imageBuffer), {+ limitInputPixels: false,+ });++ for (const [size, thumbnailPath] of Object.entries(thumbnailPaths)) {+ let height;+ switch (size) {+ case 'card_cover':+ height = 512;+ break;+ case 'small':+ height = 128;+ break;+ case 'tiny':+ height = 64;+ break;+ default:+ height = 32;+ break;+ }++ const resizedImage = await sharpImage+ .resize(undefined, height, {+ fit: sharp.fit.cover,+ kernel: 'lanczos3',+ })+ .toBuffer();++ await (storageAdapter as any).fileCreateByStream(+ slash(thumbnailPath),+ Readable.from(resizedImage),+ {+ mimetype: 'image/jpeg',+ },+ );+ }++ return thumbnailPaths;+ } catch (error) {+ this.logger.error({+ message: `Failed to generate PDF thumbnail for ${relativePath}`,+ error: error?.message,+ });+ return null;+ }+ }+async job(job: Job<ThumbnailGeneratorJobData>) {const { attachments, scope } = job.data;@@ -57,6 +143,10 @@ export class ThumbnailGeneratorProcessor {scope,);+ if (this.isPdfFile(attachment)) {+ return await this.generatePdfThumbnail(file, relativePath, storageAdapter);+ }+const thumbnailPaths = {card_cover: path.join('nc',diff --git a/packages/nocodb/src/services/attachments.service.ts b/packages/nocodb/src/services/attachments.service.tsindex 2a0dd8b709..bc4fa90008 100644--- a/packages/nocodb/src/services/attachments.service.ts+++ b/packages/nocodb/src/services/attachments.service.ts@@ -36,7 +36,7 @@ interface AttachmentObject {signedUrl?: string;}-const thumbnailMimes = ['image/'];+const thumbnailMimes = ['image/', 'application/pdf'];// ref: https://docs.aws.amazon.com/AmazonS3/latest/userguide/object-keys.html - extended with some more charactersconst normalizeFilename = (filename: string) => {diff --git a/packages/nocodb/src/services/v3/data-attachment-v3.service.ts b/packages/nocodb/src/services/v3/data-attachment-v3.service.tsindex 8e6682b8d5..77f7661f5e 100644--- a/packages/nocodb/src/services/v3/data-attachment-v3.service.ts+++ b/packages/nocodb/src/services/v3/data-attachment-v3.service.ts@@ -30,7 +30,7 @@ const normalizeFilename = (filename: string) => {return filename.replace(/[\\/:*?"<>'`#|%~{}[\]^]/g, '_');};-const thumbnailMimes = ['image/'];+const thumbnailMimes = ['image/', 'application/pdf'];const mb = 1024 * 1024;