From 2ed18d241530ff37a2f938d9ef9df5b56ee55982 Mon Sep 17 00:00:00 2001 From: Jarvis Date: Wed, 10 Sep 2025 13:10:23 +0200 Subject: [PATCH] refactor: complete PdfToImageConverter.ts modularization MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Extract complex PDF-to-image conversion logic into specialized modules: - BinaryLocator.ts: pdf2img binary discovery and path resolution - EnvironmentUtils.ts: PATH setup and environment management - PdfCliExecutor.ts: CLI command execution and error handling - FileDiscovery.ts: output file discovery and pattern matching Reduces PdfToImageConverter.ts from 308 to 193 lines (37% reduction) while preserving all functionality and error handling. Improves maintainability by separating concerns: - Binary location strategy isolated from conversion logic - Environment setup centralized and reusable - CLI execution abstracted with proper error handling - File discovery logic handles pdf2img filename variations 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude --- src/converters/PdfToImageConverter.ts | 158 ++++-------------------- src/converters/pdf/BinaryLocator.ts | 103 ++++++++++++++++ src/converters/pdf/EnvironmentUtils.ts | 85 +++++++++++++ src/converters/pdf/FileDiscovery.ts | 163 ++++++++++++++++++++++++ src/converters/pdf/PdfCliExecutor.ts | 164 +++++++++++++++++++++++++ 5 files changed, 537 insertions(+), 136 deletions(-) create mode 100644 src/converters/pdf/BinaryLocator.ts create mode 100644 src/converters/pdf/EnvironmentUtils.ts create mode 100644 src/converters/pdf/FileDiscovery.ts create mode 100644 src/converters/pdf/PdfCliExecutor.ts diff --git a/src/converters/PdfToImageConverter.ts b/src/converters/PdfToImageConverter.ts index 632e236..9f234cc 100644 --- a/src/converters/PdfToImageConverter.ts +++ b/src/converters/PdfToImageConverter.ts @@ -7,6 +7,8 @@ import * as fs from 'fs/promises'; import * as path from 'path'; import { PdfProcessor } from './pdf/PdfProcessor'; import { ImageOptimizer } from './pdf/ImageOptimizer'; +import { PdfCliExecutor } from './pdf/PdfCliExecutor'; +import { FileDiscovery } from './pdf/FileDiscovery'; export interface PdfConversionOptions { /** Quality/scale factor for the rendered image (default: 2.0 for HiDPI) */ @@ -92,162 +94,46 @@ export class PdfToImageConverter { // Ensure output directory exists await fs.mkdir(outputDir, { recursive: true }); - // Calculate relative path from vault to temp directory for pdf2img - // pdf2img doesn't handle absolute paths correctly, needs relative paths - const vaultPath = process.cwd(); // This should be the vault directory - const relativeOutputDir = path.relative(vaultPath, outputDir); - - // Generate output file name for the first page + // Generate expected output file name for the first page const pdfBaseName = path.basename(pdfPath, path.extname(pdfPath)); - // pdf2img uses the pattern: "filename-1.png" for first page - const expectedOutputFileName = `${pdfBaseName}-1.png`; - const expectedOutputPath = path.join(outputDir, expectedOutputFileName); + const expectedOutputFileName = FileDiscovery.generateExpectedFilename(pdfBaseName, 1, 'png'); - // Use the CLI to convert PDF to images - const { exec } = require('child_process'); - const { promisify } = require('util'); - const execAsync = promisify(exec); + // Execute PDF to image conversion using CLI + const cliResult = await PdfCliExecutor.executePdf2Img( + pdfPath, + { + scale: opts.scale, + pages: '1', // Only convert the first page + outputDir: outputDir + }, + this.plugin + ); - // Get the plugin directory - need to handle Obsidian's environment - // In Obsidian, __dirname points to electron.asar, so we need to find the actual plugin path - let pluginDir: string; - - // Try multiple strategies to find the plugin directory - const pluginDirName = this.plugin?.manifest?.dir || 'typst-pdf-export'; - const configDir = this.plugin?.app.vault.configDir || '.obsidian'; - const possiblePluginDirs = [ - // Strategy 1: From process.cwd() if it's in the vault - path.join(process.cwd(), configDir, 'plugins', pluginDirName), - // Strategy 2: Assuming we're running from vault root - path.join(configDir, 'plugins', pluginDirName), - // Strategy 3: From vault base path if plugin is available - ...(this.plugin ? [path.join((this.plugin.app.vault.adapter as any).basePath, this.plugin.manifest.dir!)] : []) - ]; - - // Find the first directory that exists and has node_modules - pluginDir = possiblePluginDirs.find(dir => { - try { - const nodeModulesPath = path.join(dir, 'node_modules'); - return require('fs').existsSync(nodeModulesPath); - } catch { - return false; - } - }) || possiblePluginDirs[0]; // Fallback to first option - - const pdf2imgPath = path.join(pluginDir, 'node_modules', '.bin', 'pdf2img'); - - - // Check if the binary exists - const fs2 = require('fs'); - if (!fs2.existsSync(pdf2imgPath)) { + if (!cliResult.success) { return { imagePath: '', originalDimensions: { width: 0, height: 0 }, imageDimensions: { width: 0, height: 0 }, success: false, - error: `PDF2IMG binary not found at: ${pdf2imgPath}` + error: cliResult.error }; } - // Build the CLI command - the pdf2img binary is already executable - const cliCommand = [ - `"${pdf2imgPath}"`, - `"${pdfPath}"`, - '--scale', opts.scale.toString(), - '--output', `"${relativeOutputDir}"`, - '--pages', '1' // Only convert the first page - ].join(' '); - - - try { - // Set environment variables to ensure node can be found - // Use configured additional paths or fall back to defaults - const additionalPaths = this.plugin?.settings?.executablePaths?.additionalPaths || - ['/opt/homebrew/bin', '/usr/local/bin', '/usr/bin']; - - // Ensure Node.js paths are included for pdf2img execution - const nodePaths = [ - '/usr/local/bin', // Common Node.js installation - '/opt/homebrew/bin', // Homebrew on macOS - '/usr/bin', // System Node.js - '/usr/local/node/bin' // Alternative Node.js location - ]; - - const env = { - ...process.env, - PATH: [ - process.env.PATH, - ...nodePaths, - ...additionalPaths - ].filter(Boolean).join(':') - }; - - const result = await execAsync(cliCommand, { - env - }); - if (result.stderr) { - console.warn(`PDF conversion stderr: ${result.stderr}`); - } - } catch (cliError) { - console.error(`PDF conversion error: ${cliError.message}`); + // Find the generated image file (may have different name than expected) + const fileDiscovery = await FileDiscovery.findGeneratedFile(outputDir, expectedOutputFileName); + if (!fileDiscovery.found) { return { imagePath: '', originalDimensions: { width: 0, height: 0 }, imageDimensions: { width: 0, height: 0 }, success: false, - error: `PDF CLI conversion failed: ${cliError.message}` + error: fileDiscovery.error }; } - // Check if the expected output file exists - let actualOutputPath = expectedOutputPath; - try { - await fs.access(expectedOutputPath); - } catch (error) { - // Debug: List what files are actually in the output directory - try { - const files = await fs.readdir(outputDir); - - // Look for any PNG files that might match - const pngFiles = files.filter(f => f.endsWith('.png')); - if (pngFiles.length > 0) { - - // Try to find a file that matches the pattern (with or without exact name) - // pdf2img might sanitize filenames differently - const matchingFile = pngFiles.find(f => { - // Try exact match first - if (f === expectedOutputFileName) return true; - // Try partial match by removing special characters - const simplifiedExpected = expectedOutputFileName.replace(/[^a-zA-Z0-9.-]/g, ''); - const simplifiedActual = f.replace(/[^a-zA-Z0-9.-]/g, ''); - return simplifiedActual === simplifiedExpected; - }) || pngFiles[0]; // Fallback to first PNG file - - if (matchingFile) { - actualOutputPath = path.join(outputDir, matchingFile); - } - } - } catch (listError) { - console.error(`Failed to list output directory:`, listError); - } - - // Final check if we found an alternative file - try { - await fs.access(actualOutputPath); - } catch (finalError) { - return { - imagePath: '', - originalDimensions: { width: 0, height: 0 }, - imageDimensions: { width: 0, height: 0 }, - success: false, - error: `Generated image file not found: ${actualOutputPath}. Expected: ${expectedOutputPath}` - }; - } - } - // Use ImageOptimizer to handle format conversion and dimension detection const optimizationResult = await ImageOptimizer.optimizeImage( - actualOutputPath, + fileDiscovery.filePath, outputDir, pdfBaseName, { @@ -276,7 +162,7 @@ export class PdfToImageConverter { success: true }; - } catch (error) { + } catch (error: any) { return { imagePath: '', originalDimensions: { width: 0, height: 0 }, diff --git a/src/converters/pdf/BinaryLocator.ts b/src/converters/pdf/BinaryLocator.ts new file mode 100644 index 0000000..78caec3 --- /dev/null +++ b/src/converters/pdf/BinaryLocator.ts @@ -0,0 +1,103 @@ +/** + * Binary locator utilities for finding external tool binaries. + * Handles discovery of pdf2img and other CLI tools in the Obsidian environment. + */ + +import * as path from 'path'; + +export interface BinaryLocation { + /** Full path to the binary */ + binaryPath: string; + /** Whether the binary was found and is executable */ + exists: boolean; + /** Error message if binary was not found */ + error?: string; +} + +export class BinaryLocator { + /** + * Find the pdf2img binary in the plugin's node_modules directory. + * Handles the complex Obsidian environment where __dirname points to electron.asar. + * @param plugin The plugin instance for accessing manifest and settings + * @returns Binary location info + */ + public static async findPdf2ImgBinary(plugin?: any): Promise { + try { + // Get the plugin directory - need to handle Obsidian's environment + // In Obsidian, __dirname points to electron.asar, so we need to find the actual plugin path + let pluginDir: string; + + // Try multiple strategies to find the plugin directory + const pluginDirName = plugin?.manifest?.dir || 'typst-pdf-export'; + const configDir = plugin?.app.vault.configDir || '.obsidian'; + const possiblePluginDirs = this.getPossiblePluginDirs(plugin, pluginDirName, configDir); + + // Find the first directory that exists and has node_modules + pluginDir = possiblePluginDirs.find(dir => { + try { + const nodeModulesPath = path.join(dir, 'node_modules'); + return require('fs').existsSync(nodeModulesPath); + } catch { + return false; + } + }) || possiblePluginDirs[0]; // Fallback to first option + + const pdf2imgPath = path.join(pluginDir, 'node_modules', '.bin', 'pdf2img'); + + // Check if the binary exists + const exists = await this.validateBinaryExists(pdf2imgPath); + + if (!exists) { + return { + binaryPath: pdf2imgPath, + exists: false, + error: `PDF2IMG binary not found at: ${pdf2imgPath}` + }; + } + + return { + binaryPath: pdf2imgPath, + exists: true + }; + + } catch (error: any) { + return { + binaryPath: '', + exists: false, + error: `Failed to locate pdf2img binary: ${error.message}` + }; + } + } + + /** + * Get possible plugin directory locations based on different Obsidian environments. + * @param plugin Plugin instance + * @param pluginDirName Name of the plugin directory + * @param configDir Obsidian config directory (.obsidian) + * @returns Array of possible plugin directory paths + */ + private static getPossiblePluginDirs(plugin: any, pluginDirName: string, configDir: string): string[] { + return [ + // Strategy 1: From process.cwd() if it's in the vault + path.join(process.cwd(), configDir, 'plugins', pluginDirName), + // Strategy 2: Assuming we're running from vault root + path.join(configDir, 'plugins', pluginDirName), + // Strategy 3: From vault base path if plugin is available + ...(plugin ? [path.join((plugin.app.vault.adapter as any).basePath, plugin.manifest.dir!)] : []) + ]; + } + + /** + * Validate that a binary exists and is accessible. + * @param binaryPath Full path to the binary + * @returns True if binary exists, false otherwise + */ + private static async validateBinaryExists(binaryPath: string): Promise { + try { + const fs2 = require('fs'); + return fs2.existsSync(binaryPath); + } catch { + return false; + } + } +} \ No newline at end of file diff --git a/src/converters/pdf/EnvironmentUtils.ts b/src/converters/pdf/EnvironmentUtils.ts new file mode 100644 index 0000000..d5e8bba --- /dev/null +++ b/src/converters/pdf/EnvironmentUtils.ts @@ -0,0 +1,85 @@ +/** + * Environment utilities for setting up CLI tool execution environment. + * Handles PATH augmentation and environment variable setup for external tools. + */ + +export interface EnvironmentSetupOptions { + /** Additional paths to include in PATH */ + additionalPaths?: string[]; + /** Base environment to extend */ + baseEnvironment?: NodeJS.ProcessEnv; +} + +export class EnvironmentUtils { + /** + * Get augmented environment with extended PATH for CLI tool execution. + * Ensures Node.js and other common tool paths are available. + * @param settings Plugin settings containing additional paths + * @param options Additional environment setup options + * @returns Augmented environment with extended PATH + */ + public static getAugmentedEnvironment( + settings?: any, + options: EnvironmentSetupOptions = {} + ): NodeJS.ProcessEnv { + // Set environment variables to ensure node can be found + // Use configured additional paths or fall back to defaults + const additionalPaths = options.additionalPaths || + settings?.executablePaths?.additionalPaths || + ['/opt/homebrew/bin', '/usr/local/bin', '/usr/bin']; + + // Ensure Node.js paths are included for pdf2img execution + const nodePaths = this.getNodePaths(); + + const env = { + ...(options.baseEnvironment || process.env), + PATH: this.mergePathVariables([ + process.env.PATH, + ...nodePaths, + ...additionalPaths + ]) + }; + + return env; + } + + /** + * Get common Node.js installation paths. + * @returns Array of common Node.js binary paths + */ + private static getNodePaths(): string[] { + return [ + '/usr/local/bin', // Common Node.js installation + '/opt/homebrew/bin', // Homebrew on macOS + '/usr/bin', // System Node.js + '/usr/local/node/bin' // Alternative Node.js location + ]; + } + + /** + * Merge multiple PATH variables into a single PATH string. + * @param paths Array of path strings to merge + * @returns Merged PATH string + */ + private static mergePathVariables(paths: (string | undefined)[]): string { + return paths + .filter(Boolean) // Remove undefined/empty paths + .join(':'); + } + + /** + * Create environment for executing CLI commands with timeout. + * @param settings Plugin settings + * @param timeout Command timeout in milliseconds + * @returns Environment configuration object + */ + public static createCliEnvironment(settings?: any, timeout?: number) { + const env = this.getAugmentedEnvironment(settings); + + return { + env, + timeout: timeout || 30000, // 30 second default timeout + stdio: ['pipe', 'pipe', 'pipe'] as const + }; + } +} \ No newline at end of file diff --git a/src/converters/pdf/FileDiscovery.ts b/src/converters/pdf/FileDiscovery.ts new file mode 100644 index 0000000..36a055e --- /dev/null +++ b/src/converters/pdf/FileDiscovery.ts @@ -0,0 +1,163 @@ +/** + * File discovery utilities for finding generated PDF to image conversion outputs. + * Handles filename pattern matching when pdf2img generates files with different names. + */ + +import * as fs from 'fs/promises'; +import * as path from 'path'; + +export interface FileDiscoveryResult { + /** Path to the discovered file */ + filePath: string; + /** Whether the file was found successfully */ + found: boolean; + /** Error message if file was not found */ + error?: string; +} + +export class FileDiscovery { + /** + * Find the generated image file in the output directory. + * Handles cases where pdf2img sanitizes filenames differently than expected. + * @param outputDir Directory where files were generated + * @param expectedFileName Expected output filename + * @returns Discovery result with actual file path + */ + public static async findGeneratedFile( + outputDir: string, + expectedFileName: string + ): Promise { + const expectedOutputPath = path.join(outputDir, expectedFileName); + + // Check if the expected output file exists first + try { + await fs.access(expectedOutputPath); + return { + filePath: expectedOutputPath, + found: true + }; + } catch (error) { + // File not found with expected name, try to find alternatives + return await this.findAlternativeFile(outputDir, expectedFileName, expectedOutputPath); + } + } + + /** + * Find alternative files when the expected filename doesn't match. + * @param outputDir Output directory to search + * @param expectedFileName Expected filename for pattern matching + * @param expectedOutputPath Full expected output path + * @returns Discovery result with alternative file if found + */ + private static async findAlternativeFile( + outputDir: string, + expectedFileName: string, + expectedOutputPath: string + ): Promise { + try { + // Debug: List what files are actually in the output directory + const files = await fs.readdir(outputDir); + + // Look for any PNG files that might match + const pngFiles = files.filter(f => f.endsWith('.png')); + if (pngFiles.length === 0) { + return { + filePath: '', + found: false, + error: `No PNG files found in output directory: ${outputDir}` + }; + } + + // Try to find a file that matches the pattern (with or without exact name) + // pdf2img might sanitize filenames differently + const matchingFile = this.matchFilePattern(pngFiles, expectedFileName); + + if (matchingFile) { + const actualOutputPath = path.join(outputDir, matchingFile); + + // Final check if we found an alternative file + try { + await fs.access(actualOutputPath); + return { + filePath: actualOutputPath, + found: true + }; + } catch (finalError) { + return { + filePath: '', + found: false, + error: `Alternative file not accessible: ${actualOutputPath}` + }; + } + } else { + return { + filePath: '', + found: false, + error: `Generated image file not found: ${expectedOutputPath}. Available files: ${pngFiles.join(', ')}` + }; + } + + } catch (listError: any) { + console.error(`Failed to list output directory:`, listError); + return { + filePath: '', + found: false, + error: `Failed to search output directory: ${listError.message}` + }; + } + } + + /** + * Match files against expected filename patterns. + * Handles filename sanitization that pdf2img might apply. + * @param files Array of available filenames + * @param expectedFileName Expected filename pattern + * @returns Matching filename or null if no match found + */ + private static matchFilePattern(files: string[], expectedFileName: string): string | null { + // Try exact match first + const exactMatch = files.find(f => f === expectedFileName); + if (exactMatch) { + return exactMatch; + } + + // Try partial match by removing special characters + const simplifiedExpected = this.sanitizeFilename(expectedFileName); + const matchingFile = files.find(f => { + const simplifiedActual = this.sanitizeFilename(f); + return simplifiedActual === simplifiedExpected; + }); + + if (matchingFile) { + return matchingFile; + } + + // Fallback to first PNG file if no pattern matches + return files.length > 0 ? files[0] : null; + } + + /** + * Sanitize filename by removing special characters for pattern matching. + * @param filename Original filename + * @returns Sanitized filename for comparison + */ + private static sanitizeFilename(filename: string): string { + return filename.replace(/[^a-zA-Z0-9.-]/g, ''); + } + + /** + * Generate expected output filename for pdf2img conversion. + * pdf2img uses the pattern: "filename-1.png" for first page. + * @param pdfBaseName Base name of the PDF file (without extension) + * @param pageNumber Page number (1-based) + * @param format Output format ('png' or 'jpeg') + * @returns Expected output filename + */ + public static generateExpectedFilename( + pdfBaseName: string, + pageNumber: number = 1, + format: string = 'png' + ): string { + return `${pdfBaseName}-${pageNumber}.${format}`; + } +} \ No newline at end of file diff --git a/src/converters/pdf/PdfCliExecutor.ts b/src/converters/pdf/PdfCliExecutor.ts new file mode 100644 index 0000000..b442ec0 --- /dev/null +++ b/src/converters/pdf/PdfCliExecutor.ts @@ -0,0 +1,164 @@ +/** + * PDF CLI Executor for handling pdf2img command line operations. + * Executes external pdf2img binary to convert PDF pages to images. + */ + +import * as path from 'path'; +import { BinaryLocator } from './BinaryLocator'; +import { EnvironmentUtils } from './EnvironmentUtils'; + +export interface PdfCliOptions { + /** Scale factor for the rendered image */ + scale: number; + /** Page number to convert (1-based) */ + pages: string; + /** Output directory for generated images */ + outputDir: string; +} + +export interface PdfCliResult { + /** Whether the CLI execution succeeded */ + success: boolean; + /** Standard output from the command */ + stdout?: string; + /** Standard error from the command */ + stderr?: string; + /** Error message if execution failed */ + error?: string; +} + +export class PdfCliExecutor { + /** + * Execute pdf2img CLI command to convert PDF to images. + * @param pdfPath Path to the input PDF file + * @param options CLI execution options + * @param plugin Plugin instance for accessing settings + * @returns CLI execution result + */ + public static async executePdf2Img( + pdfPath: string, + options: PdfCliOptions, + plugin?: any + ): Promise { + try { + // Find the pdf2img binary + const binaryLocation = await BinaryLocator.findPdf2ImgBinary(plugin); + if (!binaryLocation.exists) { + return { + success: false, + error: binaryLocation.error + }; + } + + // Calculate relative path from vault to temp directory for pdf2img + // pdf2img doesn't handle absolute paths correctly, needs relative paths + const vaultPath = process.cwd(); // This should be the vault directory + const relativeOutputDir = path.relative(vaultPath, options.outputDir); + + // Build the CLI command + const cliCommand = this.buildCommand( + binaryLocation.binaryPath, + pdfPath, + relativeOutputDir, + options + ); + + // Execute the command + return await this.executeCommand(cliCommand, plugin); + + } catch (error: any) { + return { + success: false, + error: `PDF CLI execution failed: ${error.message}` + }; + } + } + + /** + * Build the pdf2img CLI command string. + * @param binaryPath Full path to pdf2img binary + * @param pdfPath Path to input PDF file + * @param outputDir Output directory (relative path) + * @param options CLI options + * @returns Command string ready for execution + */ + private static buildCommand( + binaryPath: string, + pdfPath: string, + outputDir: string, + options: PdfCliOptions + ): string { + // Build the CLI command - the pdf2img binary is already executable + return [ + `"${binaryPath}"`, + `"${pdfPath}"`, + '--scale', options.scale.toString(), + '--output', `"${outputDir}"`, + '--pages', options.pages // Only convert the specified page(s) + ].join(' '); + } + + /** + * Execute a CLI command with proper environment setup. + * @param command Command string to execute + * @param plugin Plugin instance for accessing settings + * @returns Command execution result + */ + private static async executeCommand( + command: string, + plugin?: any + ): Promise { + try { + const { exec } = require('child_process'); + const { promisify } = require('util'); + const execAsync = promisify(exec); + + // Get augmented environment for CLI execution + const env = EnvironmentUtils.getAugmentedEnvironment(plugin?.settings); + + const result = await execAsync(command, { env }); + + // Log stderr as warning if present, but don't treat as error + if (result.stderr) { + console.warn(`PDF conversion stderr: ${result.stderr}`); + } + + return { + success: true, + stdout: result.stdout, + stderr: result.stderr + }; + + } catch (cliError: any) { + console.error(`PDF conversion error: ${cliError.message}`); + return { + success: false, + error: `PDF CLI conversion failed: ${cliError.message}`, + stderr: cliError.stderr + }; + } + } + + /** + * Validate that pdf2img binary is available and working. + * @param plugin Plugin instance for accessing settings + * @returns Validation result + */ + public static async validatePdf2ImgAvailable(plugin?: any): Promise<{ + available: boolean; + error?: string; + }> { + try { + const binaryLocation = await BinaryLocator.findPdf2ImgBinary(plugin); + return { + available: binaryLocation.exists, + error: binaryLocation.error + }; + } catch (error: any) { + return { + available: false, + error: `Failed to validate pdf2img: ${error.message}` + }; + } + } +} \ No newline at end of file