refactor: complete PdfToImageConverter.ts modularization

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 <noreply@anthropic.com>
This commit is contained in:
Jarvis committed 2025-09-10 13:10:23 +02:00
1 parent 3787703aab
commit 2ed18d2415
5 files changed
+537 -136

No files matched your search

+22 -136
View File
@@ -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 },