feat: add PDF embed support with first-page preview generation

- Implement PdfToImageConverter using pdf-to-img CLI for PDF-to-image conversion
- Add PDF embed detection and processing in MarkdownPreprocessor
- Generate first-page preview images for PDF embeds in exported documents
- Copy generated images to vault location for Typst accessibility
- Add --embed-resources flag to Pandoc for proper resource embedding
- Support both image and PDF attachments in exported documents

Fixes issue where PDF exports only contained text without attachments.
PDF embeds now show visual previews like Obsidian's native behavior.

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
Jarvis committed 2025-08-31 14:39:57 +02:00
1 parent d765f09402
commit b9fb1a455f
10 files changed
+1943 -265

No files matched your search

+31 -4
View File
@@ -28,6 +28,14 @@ export interface PreprocessingResult {
frontmatter?: Record<string, any>;
title?: string;
wordCount: number;
pdfEmbeds?: Array<{
originalPath: string;
sanitizedPath: string;
fileName: string;
baseName: string;
options?: string;
marker: string;
}>;
};
/** Processing errors and warnings */
errors: string[];
@@ -504,16 +512,35 @@ export class MarkdownPreprocessor {
}
/**
* Process PDF embeds
* Process PDF embeds - Convert to image preview with PDF attachment
*/
private processPdfEmbed(pdfPath: string, options: string | undefined, result: PreprocessingResult): string {
const sanitizedPath = this.sanitizeFilePath(pdfPath);
// PDFs can be handled similarly to documents
// For now, we'll mark this for async processing and return a placeholder
// The actual conversion will be handled in the main export process
const fileName = pdfPath.substring(pdfPath.lastIndexOf('/') + 1);
result.warnings.push(`PDF embed converted to link: ${pdfPath}`);
const baseName = fileName.replace(/\.[^/.]+$/, ""); // Remove extension
return `[📖 ${fileName}](${sanitizedPath})`;
// Create a marker that the export process can detect and replace
const marker = `PDF_EMBED_MARKER:${pdfPath}:${baseName}:${options || ''}`;
// Add to processing queue for later conversion
if (!result.metadata.pdfEmbeds) {
result.metadata.pdfEmbeds = [];
}
result.metadata.pdfEmbeds.push({
originalPath: pdfPath,
sanitizedPath: sanitizedPath,
fileName: fileName,
baseName: baseName,
options: options,
marker: marker
});
result.warnings.push(`PDF embed queued for image conversion: ${pdfPath}`);
return marker;
}
/**
+299
View File
@@ -0,0 +1,299 @@
/**
* PDF to Image Converter using pdf-to-img
* Converts PDF files to PNG images for preview in Typst exports
*/
import * as fs from 'fs/promises';
import * as path from 'path';
export interface PdfConversionOptions {
/** Quality/scale factor for the rendered image (default: 2.0 for HiDPI) */
scale?: number;
/** Maximum width in pixels (default: 800) */
maxWidth?: number;
/** Maximum height in pixels (default: 600) */
maxHeight?: number;
/** Output format (default: 'png') */
format?: 'png' | 'jpeg';
/** JPEG quality if using jpeg format (default: 90) */
quality?: number;
}
export interface PdfConversionResult {
/** Path to the generated image file */
imagePath: string;
/** Original PDF dimensions */
originalDimensions: {
width: number;
height: number;
};
/** Generated image dimensions */
imageDimensions: {
width: number;
height: number;
};
/** Success status */
success: boolean;
/** Error message if conversion failed */
error?: string;
}
export class PdfToImageConverter {
private static instance: PdfToImageConverter;
private constructor() {}
public static getInstance(): PdfToImageConverter {
if (!PdfToImageConverter.instance) {
PdfToImageConverter.instance = new PdfToImageConverter();
}
return PdfToImageConverter.instance;
}
/**
* Convert the first page of a PDF to an image
*/
public async convertFirstPageToImage(
pdfPath: string,
outputDir: string,
options: PdfConversionOptions = {}
): Promise<PdfConversionResult> {
try {
// Set default options
const opts: Required<PdfConversionOptions> = {
scale: options.scale || 2.0,
maxWidth: options.maxWidth || 800,
maxHeight: options.maxHeight || 600,
format: options.format || 'png',
quality: options.quality || 90
};
// Ensure the PDF file exists
try {
await fs.access(pdfPath);
} catch (error) {
return {
imagePath: '',
originalDimensions: { width: 0, height: 0 },
imageDimensions: { width: 0, height: 0 },
success: false,
error: `PDF file not found: ${pdfPath}`
};
}
// Ensure output directory exists
await fs.mkdir(outputDir, { recursive: true });
// Generate 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);
// Use the CLI to convert PDF to images
const { exec } = require('child_process');
const { promisify } = require('util');
const execAsync = promisify(exec);
// 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 possiblePluginDirs = [
// Strategy 1: From process.cwd() if it's in the vault
path.join(process.cwd(), '.obsidian', 'plugins', 'obsidian-typst-pdf-export'),
// Strategy 2: Assuming we're running from vault root
path.join('.obsidian', 'plugins', 'obsidian-typst-pdf-export'),
// Strategy 3: Direct path if running in development
'/Users/alex/Obsidian/Dev/.obsidian/plugins/obsidian-typst-pdf-export'
];
// 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');
console.log(`Plugin directory: ${pluginDir}`);
console.log(`PDF2IMG path: ${pdf2imgPath}`);
// Check if the binary exists
const fs2 = require('fs');
if (!fs2.existsSync(pdf2imgPath)) {
return {
imagePath: '',
originalDimensions: { width: 0, height: 0 },
imageDimensions: { width: 0, height: 0 },
success: false,
error: `PDF2IMG binary not found at: ${pdf2imgPath}`
};
}
// Build the CLI command - the pdf2img binary is already executable
const cliCommand = [
`"${pdf2imgPath}"`,
`"${pdfPath}"`,
'--scale', opts.scale.toString(),
'--output', `"${outputDir}"`,
'--pages', '1' // Only convert the first page
].join(' ');
console.log(`PDF conversion command: ${cliCommand}`);
try {
// Set environment variables to ensure node can be found
const env = {
...process.env,
PATH: process.env.PATH + ':/opt/homebrew/bin:/usr/local/bin:/usr/bin'
};
const result = await execAsync(cliCommand, { env });
console.log(`PDF conversion stdout: ${result.stdout}`);
if (result.stderr) {
console.warn(`PDF conversion stderr: ${result.stderr}`);
}
} catch (cliError) {
console.error(`PDF conversion error: ${cliError.message}`);
return {
imagePath: '',
originalDimensions: { width: 0, height: 0 },
imageDimensions: { width: 0, height: 0 },
success: false,
error: `PDF CLI conversion failed: ${cliError.message}`
};
}
// Check if the expected output file exists
try {
await fs.access(expectedOutputPath);
} catch (error) {
return {
imagePath: '',
originalDimensions: { width: 0, height: 0 },
imageDimensions: { width: 0, height: 0 },
success: false,
error: `Generated image file not found: ${expectedOutputPath}`
};
}
// Rename to our desired format if needed
const finalOutputFileName = `${pdfBaseName}_preview.${opts.format}`;
const finalOutputPath = path.join(outputDir, finalOutputFileName);
let buffer: Buffer;
if (opts.format === 'jpeg') {
// Convert PNG to JPEG if needed
try {
const sharp = require('sharp');
const inputBuffer = await fs.readFile(expectedOutputPath);
buffer = await sharp(inputBuffer)
.jpeg({ quality: opts.quality })
.toBuffer();
await fs.writeFile(finalOutputPath, buffer);
// Clean up the original PNG
await fs.unlink(expectedOutputPath);
} catch (sharpError) {
console.warn('Sharp not available for JPEG conversion, keeping PNG format');
// Just rename the file
await fs.rename(expectedOutputPath, finalOutputPath);
buffer = await fs.readFile(finalOutputPath);
}
} else {
// Keep as PNG, just rename
await fs.rename(expectedOutputPath, finalOutputPath);
buffer = await fs.readFile(finalOutputPath);
}
// Get image dimensions
let imageDimensions = { width: opts.maxWidth, height: opts.maxHeight };
try {
const sharp = require('sharp');
const metadata = await sharp(buffer).metadata();
imageDimensions = {
width: metadata.width || opts.maxWidth,
height: metadata.height || opts.maxHeight
};
} catch (sharpError) {
// Fallback to estimated dimensions if sharp is not available
console.warn('Sharp not available for image metadata, using estimated dimensions');
}
return {
imagePath: finalOutputPath,
originalDimensions: imageDimensions, // Estimate based on converted image
imageDimensions,
success: true
};
} catch (error) {
return {
imagePath: '',
originalDimensions: { width: 0, height: 0 },
imageDimensions: { width: 0, height: 0 },
success: false,
error: `PDF conversion failed: ${error.message}`
};
}
}
/**
* Check if a file is a valid PDF
*/
public async isValidPdf(filePath: string): Promise<boolean> {
try {
const buffer = await fs.readFile(filePath);
// Check PDF signature
const signature = buffer.subarray(0, 4).toString();
return signature === '%PDF';
} catch (error) {
return false;
}
}
/**
* Get PDF metadata (page count, dimensions, etc.)
*/
public async getPdfInfo(filePath: string): Promise<{
pageCount: number;
dimensions: { width: number; height: number };
success: boolean;
error?: string;
}> {
try {
// pdf-to-img doesn't provide metadata directly
// We'll use a basic approach with the PDF signature check
const isValid = await this.isValidPdf(filePath);
if (!isValid) {
return {
pageCount: 0,
dimensions: { width: 0, height: 0 },
success: false,
error: 'Invalid PDF file'
};
}
// For now, return basic info since pdf-to-img focuses on conversion
// In a real implementation, you might want to use pdf-parse or similar for metadata
return {
pageCount: 1, // We only handle first page anyway
dimensions: { width: 612, height: 792 }, // Standard letter size estimate
success: true
};
} catch (error) {
return {
pageCount: 0,
dimensions: { width: 0, height: 0 },
success: false,
error: error.message
};
}
}
}
+110 -221
View File
@@ -2,244 +2,103 @@ import { App, normalizePath, TFile, TFolder, Notice } from 'obsidian';
import { Template, TemplateVariable, TemplateMetadata, TemplateValidationResult, SubstitutionContext } from './types';
import { TemplateSubstitution } from './template-substitution';
import { TemplateValidator } from './template-validator';
import * as path from 'path';
/**
* Manages Typst templates, including built-in and custom user templates
*/
export class TemplateManager {
private app: App;
private builtInTemplates: Map<string, string> = new Map();
private pluginDir: string;
private builtInTemplateNames: string[] = ['default.typ', 'article.typ', 'report.typ', 'single-page.typ'];
private customTemplates: Map<string, Template> = new Map();
private customTemplateDirectory: string = 'Typst Templates';
constructor(app: App, customTemplateDirectory?: string) {
constructor(app: App, pluginDir: string, customTemplateDirectory?: string) {
this.app = app;
this.pluginDir = pluginDir;
if (customTemplateDirectory) {
this.customTemplateDirectory = customTemplateDirectory;
}
this.initializeBuiltInTemplates();
}
/**
* Initialize built-in Typst templates with modern 0.11+ syntax
* Get the absolute path to a built-in template file
*/
private initializeBuiltInTemplates(): void {
// Default template - basic document
this.builtInTemplates.set('default.typ', `#set page(
paper: "a4",
margin: (x: 2.5cm, y: 2cm)
)
#set text(
font: "Liberation Serif",
size: 12pt,
lang: "en"
)
#set par(justify: true, leading: 0.65em)
#set heading(numbering: "1.")
private getBuiltInTemplatePath(templateName: string): string {
return path.join(this.pluginDir, 'templates', templateName);
}
#if "$title$" != "" [
#align(center, text(18pt, weight: "bold")[$title$])
#v(1em)
]
/**
* Check if a file exists using Node.js fs (for built-in templates)
*/
private async fileExists(filePath: string): Promise<boolean> {
try {
const fs = require('fs').promises;
await fs.access(filePath);
return true;
} catch {
return false;
}
}
#if "$author$" != "" [
#align(center, text(14pt)[$author$])
#v(0.5em)
]
/**
* Read a file using Node.js fs (for built-in templates)
*/
private async readFile(filePath: string): Promise<string> {
const fs = require('fs').promises;
return await fs.readFile(filePath, 'utf8');
}
#if "$date$" != "" [
#align(center, text(12pt)[$date$])
#v(2em)
]
$body$`);
// Article template - academic paper style
this.builtInTemplates.set('article.typ', `#set page(
paper: "a4",
margin: (x: 2.5cm, y: 2cm),
numbering: "1"
)
#set text(
font: "Liberation Serif",
size: 11pt,
lang: "en"
)
#set par(justify: true, leading: 0.65em, first-line-indent: 1.2em)
#set heading(numbering: "1.")
#show heading.where(level: 1): it => block(
width: 100%,
below: 1.5em,
above: 2em,
)[
#set align(center)
#set text(16pt, weight: "bold")
#it.body
]
#show heading.where(level: 2): it => block(
width: 100%,
below: 1em,
above: 1.5em,
)[
#set text(13pt, weight: "bold")
#it
]
#if "$title$" != "" [
#align(center, text(20pt, weight: "bold")[$title$])
#v(1em)
]
#if "$author$" != "" [
#align(center, text(14pt)[$author$])
#v(0.5em)
]
#if "$date$" != "" [
#align(center, text(12pt)[$date$])
#v(2em)
]
$body$`);
// Report template - formal report style
this.builtInTemplates.set('report.typ', `#set page(
paper: "a4",
margin: (x: 2.5cm, y: 2.5cm),
numbering: "1",
header: context {
if counter(page).get().first() > 1 [
#align(right)[$title$]
#line(length: 100%)
]
}
)
#set text(
font: "Liberation Serif",
size: 12pt,
lang: "en"
)
#set par(justify: true, leading: 0.65em)
#set heading(numbering: "1.")
#show heading.where(level: 1): it => pagebreak(weak: true) + block(
width: 100%,
below: 2em,
above: 0pt,
)[
#set align(center)
#set text(18pt, weight: "bold")
#counter(heading).display()
#h(0.5em)
#it.body
]
#show heading.where(level: 2): it => block(
width: 100%,
below: 1em,
above: 1.5em,
)[
#set text(14pt, weight: "bold")
#it
]
// Title page
#page()[
#align(center + horizon)[
#if "$title$" != "" [
#text(24pt, weight: "bold")[$title$]
#v(2em)
]
#if "$author$" != "" [
#text(16pt)[$author$]
#v(1em)
]
#if "$date$" != "" [
#text(14pt)[$date$]
]
]
]
$body$`);
// Single-page template - auto-adjusting height
this.builtInTemplates.set('single-page.typ', `#set page(
paper: "a4",
margin: (x: 2.5cm, y: 2cm),
height: auto
)
#set text(
font: "Liberation Serif",
size: 12pt,
lang: "en"
)
#set par(justify: true, leading: 0.65em)
#set heading(numbering: "1.")
#show heading.where(level: 1): it => block(
width: 100%,
below: 1.5em,
above: 1.5em,
)[
#set text(16pt, weight: "bold")
#it
]
#show heading.where(level: 2): it => block(
width: 100%,
below: 1em,
above: 1em,
)[
#set text(14pt, weight: "bold")
#it
]
#if "$title$" != "" [
#align(center, text(18pt, weight: "bold")[$title$])
#v(1em)
]
#if "$author$" != "" [
#align(center, text(14pt)[$author$])
#v(0.5em)
]
#if "$date$" != "" [
#align(center, text(12pt)[$date$])
#v(2em)
]
$body$`);
/**
* Initialize built-in Typst templates (now reads from disk)
*/
private async initializeBuiltInTemplates(): Promise<void> {
// Built-in templates are now stored as files in templates/ directory
// This method verifies they exist and are accessible
}
/**
* Get available template names
*/
getAvailableTemplates(): string[] {
const builtIn = Array.from(this.builtInTemplates.keys());
async getAvailableTemplates(): Promise<string[]> {
const builtIn: string[] = [];
console.log('TemplateManager: Getting available templates...');
console.log('Plugin dir:', this.pluginDir);
// Check which built-in templates exist
for (const templateName of this.builtInTemplateNames) {
const templatePath = this.getBuiltInTemplatePath(templateName);
console.log(`Checking template: ${templateName} at path: ${templatePath}`);
const exists = await this.fileExists(templatePath);
console.log(`Template ${templateName} exists: ${exists}`);
if (exists) {
builtIn.push(templateName);
}
}
const custom = Array.from(this.customTemplates.keys()).map(name => `${name}.typ`);
console.log('Built-in templates found:', builtIn);
console.log('Custom templates found:', custom);
return [...builtIn, ...custom];
}
/**
* Get template content by name
* Get template file path by name (for use with Pandoc)
*/
getTemplate(templateName: string): string | null {
getTemplatePath(templateName: string): string | null {
// Check built-in templates first
if (this.builtInTemplates.has(templateName)) {
return this.builtInTemplates.get(templateName) || null;
if (this.builtInTemplateNames.includes(templateName)) {
// Return relative path for Typst templates (not absolute)
// This is because Pandoc + Typst expects relative paths
return `templates/${templateName}`;
}
// Check custom templates
const customKey = templateName.replace('.typ', '');
if (this.customTemplates.has(customKey)) {
const template = this.customTemplates.get(customKey);
// For custom templates, we'll need to load the file content
// This will be implemented in the next subtask
return template?.filePath || null;
}
@@ -249,26 +108,39 @@ $body$`);
/**
* Check if a template exists
*/
hasTemplate(templateName: string): boolean {
return this.builtInTemplates.has(templateName) ||
this.customTemplates.has(templateName.replace('.typ', ''));
async hasTemplate(templateName: string): Promise<boolean> {
// Check built-in templates
if (this.builtInTemplateNames.includes(templateName)) {
const templatePath = this.getBuiltInTemplatePath(templateName);
return await this.fileExists(templatePath);
}
// Check custom templates
return this.customTemplates.has(templateName.replace('.typ', ''));
}
/**
* Get template metadata
*/
getTemplateInfo(templateName: string): Partial<Template> | null {
if (this.builtInTemplates.has(templateName)) {
return {
name: templateName.replace('.typ', ''),
variables: this.extractVariables(this.builtInTemplates.get(templateName) || ''),
metadata: {
author: 'Obsidian Typst PDF Export',
version: '1.0.0',
description: this.getBuiltInDescription(templateName),
compatibility: ['0.11.0', '0.12.0']
}
};
async getTemplateInfo(templateName: string): Promise<Partial<Template> | null> {
if (this.builtInTemplateNames.includes(templateName)) {
try {
const templatePath = this.getBuiltInTemplatePath(templateName);
const content = await this.readFile(templatePath);
return {
name: templateName.replace('.typ', ''),
variables: this.extractVariables(content),
metadata: {
author: 'Obsidian Typst PDF Export',
version: '1.0.0',
description: this.getBuiltInDescription(templateName),
compatibility: ['0.11.0', '0.12.0']
}
};
} catch (error) {
console.error(`Error reading built-in template ${templateName}:`, error);
return null;
}
}
const customKey = templateName.replace('.typ', '');
@@ -598,8 +470,14 @@ $body$`;
*/
async getTemplateContent(templateName: string): Promise<string | null> {
// Check built-in templates first
if (this.builtInTemplates.has(templateName)) {
return this.builtInTemplates.get(templateName) || null;
if (this.builtInTemplateNames.includes(templateName)) {
try {
const templatePath = this.getBuiltInTemplatePath(templateName);
return await this.readFile(templatePath);
} catch (error) {
console.error(`Error reading built-in template ${templateName}:`, error);
return null;
}
}
// Check custom templates
@@ -664,9 +542,20 @@ $body$`;
const customResults = new Map<string, TemplateValidationResult>();
// Validate built-in templates
for (const [templateName, content] of this.builtInTemplates) {
const result = TemplateValidator.validateTemplate(content);
builtInResults.set(templateName, result);
for (const templateName of this.builtInTemplateNames) {
try {
const templatePath = this.getBuiltInTemplatePath(templateName);
const content = await this.readFile(templatePath);
const result = TemplateValidator.validateTemplate(content);
builtInResults.set(templateName, result);
} catch (error) {
builtInResults.set(templateName, {
isValid: false,
errors: [`Error loading template: ${error.message}`],
warnings: [],
variables: []
});
}
}
// Validate custom templates
@@ -780,7 +669,7 @@ $body$`;
validation: TemplateValidationResult;
}> {
const templateContent = await this.getTemplateContent(templateName);
const info = this.getTemplateInfo(templateName);
const info = await this.getTemplateInfo(templateName);
if (!templateContent) {
throw new Error(`Template '${templateName}' not found`);