From 70241a012c163e467ccfaca051138cb8ddcccdb8 Mon Sep 17 00:00:00 2001 From: Jarvis Date: Thu, 4 Sep 2025 22:15:08 +0200 Subject: [PATCH] feat: add PDF embedding and frontmatter display controls MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Add embedPdfFiles setting to control PDF attachment embedding - Add printFrontmatter setting to display frontmatter as formatted text - Implement frontmatter formatting with proper line breaks and bullet lists - Add settings toggles to both plugin settings and export modal - Fix filename sanitization for PDF preview images with spaces - Ensure modal export config includes new behavior settings - Always generate PDF preview images regardless of embedding setting The frontmatter display formats long comma-separated values (like email lists) as bulleted lists and adds proper line breaks after each property label. 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude --- main.ts | 227 ++++++++++++++--------- src/converters/MarkdownPreprocessor.ts | 160 ++++++++++++++-- src/converters/PandocTypstConverter.ts | 25 ++- src/core/settings.ts | 10 +- src/ui/modal/modalTypes.ts | 4 + src/ui/modal/sections/BehaviorSection.ts | 24 +++ src/ui/modal/state/ModalState.ts | 4 +- 7 files changed, 342 insertions(+), 112 deletions(-) diff --git a/main.ts b/main.ts index c574acd..f26ad2e 100644 --- a/main.ts +++ b/main.ts @@ -27,6 +27,7 @@ import { ModalSettingsHelper } from './src/core/ModalSettingsHelper'; import { ExportErrorHandler } from './src/core/ExportErrorHandler'; import { TempDirectoryManager } from './src/core/TempDirectoryManager'; import { PandocTypstConverter } from './src/converters/PandocTypstConverter'; +import { MarkdownPreprocessor } from './src/converters/MarkdownPreprocessor'; import { ExportConfigModal } from './src/ui/modal/ExportConfigModal'; import { ExportConfig, ExportConfigModalSettings } from './src/ui/modal/modalTypes'; import { TemplateManager } from './src/templates/TemplateManager'; @@ -451,32 +452,37 @@ export class obsidianTypstPDFExport extends Plugin { * Export a file with specific configuration */ private async exportFileWithConfig(file: TFile, config: ExportConfig): Promise { - // Get plugin directory and vault base path + const pluginDir = this.manifest.dir!; const vaultPath = (this.app.vault.adapter as any).basePath; + // Create controller for this export (allows cancellation) + this.currentExportController = new AbortController(); + try { - // Create abort controller for cancellation - this.currentExportController = new AbortController(); + // Create temp directory for conversion + const tempManager = new TempDirectoryManager({ vaultPath: vaultPath }); + const tempDir = tempManager.ensureTempDir('pandoc'); - // Show progress notice - const progressNotice = ExportErrorHandler.showProgressNotice('Exporting to PDF...'); - - // Read file content + // Load file content const content = await this.app.vault.read(file); - const pluginDir = path.join(vaultPath, '.obsidian', 'plugins', 'obsidian-typst-pdf-export'); - // Create temp directory manager and ensure temp directory exists - const tempManager = TempDirectoryManager.create(vaultPath); - const tempDir = tempManager.ensureTempDir('images'); + // Create progress notice with cancel button + const progressNotice = new Notice('', 0); + const cancelButton = progressNotice.noticeEl.createEl('button', { + text: 'Cancel', + cls: 'mod-warning' + }); + cancelButton.addEventListener('click', () => this.cancelExport()); + progressNotice.setMessage('Preprocessing markdown content...'); - // Preprocess the markdown content using MarkdownPreprocessor - const { MarkdownPreprocessor } = await import('./src/converters/MarkdownPreprocessor'); + // Preprocess markdown const preprocessor = new MarkdownPreprocessor({ vaultPath: vaultPath, options: { includeMetadata: true, - preserveFrontmatter: false, - baseUrl: undefined + preserveFrontmatter: config.printFrontmatter ?? this.settings.behavior.printFrontmatter, + baseUrl: undefined, + printFrontmatter: config.printFrontmatter ?? this.settings.behavior.printFrontmatter }, wikilinkConfig: { format: 'md', @@ -497,7 +503,8 @@ export class obsidianTypstPDFExport extends Plugin { // Process PDF embeds if any were found if (processedResult.metadata.pdfEmbeds && processedResult.metadata.pdfEmbeds.length > 0) { console.log(`Export: Processing ${processedResult.metadata.pdfEmbeds.length} PDF embeds`); - await this.processPdfEmbeds(processedResult, vaultPath, tempDir, file); + const embedPdfFiles = config.embedPdfFiles ?? this.settings.behavior.embedPdfFiles; + await this.processPdfEmbeds(processedResult, vaultPath, tempDir, file, embedPdfFiles); } // Process image embeds if any were found @@ -749,52 +756,65 @@ ${dependencyResult.allAvailable * @returns Object with relative paths for image and PDF */ private async copyImageToVaultTemp( - imagePath: string, - pdfPath: string, - baseName: string, - vaultBasePath: string - ): Promise<{ relativeImagePath: string; relativePdfPath: string }> { - const pathModule = require('path'); - const fs = require('fs'); - - // Copy image to vault temp directory for access - const vaultTempImagesDir = pathModule.join(vaultBasePath, '.obsidian', 'plugins', 'obsidian-typst-pdf-export', 'temp-images'); - await fs.promises.mkdir(vaultTempImagesDir, { recursive: true }); - - const imageFileName = `${baseName}_preview.png`; - const vaultImagePath = pathModule.join(vaultTempImagesDir, imageFileName); - await fs.promises.copyFile(imagePath, vaultImagePath); - - // Get relative paths from vault base - const relativeImagePath = pathModule.relative(vaultBasePath, vaultImagePath); - const relativePdfPath = pathModule.relative(vaultBasePath, pdfPath); - - return { relativeImagePath, relativePdfPath }; - } + imagePath: string, + pdfPath: string, + baseName: string, + vaultBasePath: string +): Promise<{ relativeImagePath: string; relativePdfPath: string }> { + const pathModule = require('path'); + const fs = require('fs'); + + // Copy image to vault temp directory for access + const vaultTempImagesDir = pathModule.join(vaultBasePath, '.obsidian', 'plugins', 'obsidian-typst-pdf-export', 'temp-images'); + await fs.promises.mkdir(vaultTempImagesDir, { recursive: true }); + + // Sanitize the basename for use in filename - replace problematic characters + const sanitizedBaseName = baseName + .replace(/[^a-zA-Z0-9\-_]/g, '_') // Replace non-alphanumeric chars with underscore + .replace(/_{2,}/g, '_') // Collapse multiple underscores + .replace(/^_+|_+$/g, ''); // Remove leading/trailing underscores + + const imageFileName = `${sanitizedBaseName}_preview.png`; + const vaultImagePath = pathModule.join(vaultTempImagesDir, imageFileName); + await fs.promises.copyFile(imagePath, vaultImagePath); + + // Get relative paths from vault base + const relativeImagePath = pathModule.relative(vaultBasePath, vaultImagePath); + const relativePdfPath = pathModule.relative(vaultBasePath, pdfPath); + + return { relativeImagePath, relativePdfPath }; +} private generatePdfEmbedContent( relativePdfPath: string, baseName: string, relativeImagePath?: string, - errorSuffix?: string + errorSuffix?: string, + embedPdfFiles: boolean = true ): string { const description = `${baseName}${errorSuffix ? ` ${errorSuffix}` : ''}`; - const attachmentNote = `*PDF attached: ${description} - check your PDF reader's attachment panel*`; - const content = [ - relativeImagePath ? `![${baseName} - Page 1](${relativeImagePath})` : null, - relativeImagePath ? '' : null, - '```{=typst}', - `#pdf.embed("${relativePdfPath}", description: "${description}", mime-type: "application/pdf")`, - '```', - '', - attachmentNote - ].filter(line => line !== null).join('\n'); + const content = []; - return content; + // Always include image preview if available + if (relativeImagePath) { + content.push(`![${baseName} - Page 1](${relativeImagePath})`); + content.push(''); + } + + // Only include PDF embedding and attachment note if embedPdfFiles is true + if (embedPdfFiles) { + content.push('```{=typst}'); + content.push(`#pdf.embed("${relativePdfPath}", description: "${description}", mime-type: "application/pdf")`); + content.push('```'); + content.push(''); + content.push(`*PDF attached: ${description} - check your PDF reader's attachment panel*`); + } + + return content.filter(line => line !== null).join('\n'); } - private async processPdfEmbeds(processedResult: any, vaultBasePath: string, tempDir: string, currentFile?: TFile): Promise { + private async processPdfEmbeds(processedResult: any, vaultBasePath: string, tempDir: string, currentFile?: TFile, embedPdfFiles: boolean = true): Promise { const { PdfToImageConverter } = await import('./src/converters/PdfToImageConverter'); const converter = PdfToImageConverter.getInstance(this); const pathModule = require('path'); @@ -840,22 +860,30 @@ ${dependencyResult.allAvailable vaultBasePath ); - // Create combined output with image and Typst pdf.embed using helper + // Create combined output with image and optionally Typst pdf.embed using helper const combinedOutput = this.generatePdfEmbedContent( relativePdfPath, pdfEmbed.baseName, - relativeImagePath + relativeImagePath, + undefined, + embedPdfFiles ); // Replace the placeholder with the combined output updatedContent = updatedContent.replace(pdfEmbed.marker, combinedOutput); - console.log(`Export: Successfully processed PDF embed with pdf.embed: ${pdfEmbed.baseName}`); + console.log(`Export: Successfully processed PDF embed: ${pdfEmbed.baseName}`); } else { console.warn(`Export: Failed to convert PDF to image: ${result.error}`); const relativePdfPath = pathModule.relative(vaultBasePath, fullPdfPath); - // Even without preview image, still embed the PDF - const fallbackOutput = this.generatePdfEmbedContent(relativePdfPath, pdfEmbed.baseName); + // Even without preview image, still embed the PDF if requested + const fallbackOutput = this.generatePdfEmbedContent( + relativePdfPath, + pdfEmbed.baseName, + undefined, + '(preview not available)', + embedPdfFiles + ); updatedContent = updatedContent.replace(pdfEmbed.marker, fallbackOutput); } } catch (error) { @@ -866,7 +894,8 @@ ${dependencyResult.allAvailable relativePdfPath, pdfEmbed.baseName, undefined, - '(error occurred)' + '(error occurred)', + embedPdfFiles ); updatedContent = updatedContent.replace(pdfEmbed.marker, fallbackOutput); } @@ -1418,38 +1447,58 @@ class ObsidianTypstPDFExportSettingTab extends PluginSettingTab { } private createBehaviorSection(containerEl: HTMLElement): void { - containerEl.createEl('h3', { text: 'Behavior' }); - - new Setting(containerEl) - .setName('Open after export') - .setDesc('Automatically open PDF after successful export') - .addToggle(toggle => toggle - .setValue(this.plugin.settings.behavior.openAfterExport) - .onChange(async (value) => { - this.plugin.settings.behavior.openAfterExport = value; - await this.plugin.saveSettings(); - })); - - new Setting(containerEl) - .setName('Preserve folder structure') - .setDesc('Maintain vault folder structure in output directory') - .addToggle(toggle => toggle - .setValue(this.plugin.settings.behavior.preserveFolderStructure) - .onChange(async (value) => { - this.plugin.settings.behavior.preserveFolderStructure = value; - await this.plugin.saveSettings(); - })); - - new Setting(containerEl) - .setName('Debug mode') - .setDesc('Enable verbose logging for troubleshooting') - .addToggle(toggle => toggle - .setValue(this.plugin.settings.behavior.debugMode) - .onChange(async (value) => { - this.plugin.settings.behavior.debugMode = value; - await this.plugin.saveSettings(); - })); - } + containerEl.createEl('h3', { text: 'Behavior' }); + + new Setting(containerEl) + .setName('Open after export') + .setDesc('Automatically open PDF after successful export') + .addToggle(toggle => toggle + .setValue(this.plugin.settings.behavior.openAfterExport) + .onChange(async (value) => { + this.plugin.settings.behavior.openAfterExport = value; + await this.plugin.saveSettings(); + })); + + new Setting(containerEl) + .setName('Preserve folder structure') + .setDesc('Maintain vault folder structure in output directory') + .addToggle(toggle => toggle + .setValue(this.plugin.settings.behavior.preserveFolderStructure) + .onChange(async (value) => { + this.plugin.settings.behavior.preserveFolderStructure = value; + await this.plugin.saveSettings(); + })); + + new Setting(containerEl) + .setName('Embed PDF files') + .setDesc('Include PDF files as attachments in the exported PDF (in addition to preview images)') + .addToggle(toggle => toggle + .setValue(this.plugin.settings.behavior.embedPdfFiles) + .onChange(async (value) => { + this.plugin.settings.behavior.embedPdfFiles = value; + await this.plugin.saveSettings(); + })); + + new Setting(containerEl) + .setName('Print frontmatter') + .setDesc('Display frontmatter as formatted text at the beginning of documents') + .addToggle(toggle => toggle + .setValue(this.plugin.settings.behavior.printFrontmatter) + .onChange(async (value) => { + this.plugin.settings.behavior.printFrontmatter = value; + await this.plugin.saveSettings(); + })); + + new Setting(containerEl) + .setName('Debug mode') + .setDesc('Enable verbose logging for troubleshooting') + .addToggle(toggle => toggle + .setValue(this.plugin.settings.behavior.debugMode) + .onChange(async (value) => { + this.plugin.settings.behavior.debugMode = value; + await this.plugin.saveSettings(); + })); +} // Helper methods for fonts private async getAvailableFonts(): Promise { diff --git a/src/converters/MarkdownPreprocessor.ts b/src/converters/MarkdownPreprocessor.ts index b1722d5..aa56cc4 100644 --- a/src/converters/MarkdownPreprocessor.ts +++ b/src/converters/MarkdownPreprocessor.ts @@ -10,6 +10,8 @@ export interface PreprocessorOptions { preserveFrontmatter: boolean; /** Base URL for relative link resolution */ baseUrl?: string; + /** Display frontmatter as formatted text at the beginning of the document */ + printFrontmatter?: boolean; } export interface WikilinkConfig { @@ -199,27 +201,51 @@ export class MarkdownPreprocessor { result.metadata.title = parsed.data.title.trim(); } + // Handle frontmatter preservation and display options + const finalFrontmatter = this.noteTitle ? + { ...parsed.data, title: this.noteTitle } : + parsed.data; + if (this.options.preserveFrontmatter) { // Keep the frontmatter in the content, but reconstruct it with the modified title - if (this.noteTitle) { - const yaml = require('js-yaml'); - const frontmatterCopy = { ...parsed.data }; - frontmatterCopy.title = this.noteTitle; - const newFrontmatter = yaml.dump(frontmatterCopy); - return `---\n${newFrontmatter}---\n${parsed.content}`; - } else { - return content; + const yaml = require('js-yaml'); + const newFrontmatter = yaml.dump(finalFrontmatter); + let processedContent = `---\n${newFrontmatter}---\n${parsed.content}`; + + // Add printed frontmatter if requested + if (this.options.printFrontmatter) { + const frontmatterDisplay = this.formatFrontmatterForDisplay(finalFrontmatter); + processedContent = `---\n${newFrontmatter}---\n\n${frontmatterDisplay}\n\n${parsed.content}`; } + + return processedContent; } else { // Return content without frontmatter, but add title as frontmatter for Pandoc + let processedContent: string; if (this.noteTitle) { const yaml = require('js-yaml'); const titleFrontmatter = yaml.dump({ title: this.noteTitle }); console.log('Replacing frontmatter with title:', titleFrontmatter); - return `---\n${titleFrontmatter}---\n${parsed.content}`; + processedContent = `---\n${titleFrontmatter}---\n${parsed.content}`; } else { - return parsed.content; + processedContent = parsed.content; } + + // Add printed frontmatter if requested + if (this.options.printFrontmatter) { + const frontmatterDisplay = this.formatFrontmatterForDisplay(finalFrontmatter); + // Insert after the title frontmatter but before content + const lines = processedContent.split('\n'); + if (lines[0] === '---' && lines.findIndex(line => line === '---') > 0) { + const endIndex = lines.findIndex((line, i) => i > 0 && line === '---'); + lines.splice(endIndex + 1, 0, '', frontmatterDisplay, ''); + processedContent = lines.join('\n'); + } else { + processedContent = `${frontmatterDisplay}\n\n${processedContent}`; + } + } + + return processedContent; } } else { // No frontmatter found - add title frontmatter if we have a noteTitle @@ -266,7 +292,18 @@ export class MarkdownPreprocessor { if (this.noteTitle) { const yaml = require('js-yaml'); const newFrontmatter = yaml.dump(frontmatter); - return content.replace(this.FRONTMATTER_PATTERN, `---\n${newFrontmatter}---\n`); + let processedContent = content.replace(this.FRONTMATTER_PATTERN, `---\n${newFrontmatter}---\n`); + + // Add printed frontmatter if requested + if (this.options.printFrontmatter) { + const frontmatterDisplay = this.formatFrontmatterForDisplay(frontmatter); + processedContent = processedContent.replace( + this.FRONTMATTER_PATTERN, + `---\n${newFrontmatter}---\n\n${frontmatterDisplay}\n\n` + ); + } + + return processedContent; } else { return content; } @@ -275,7 +312,18 @@ export class MarkdownPreprocessor { if (this.noteTitle) { const yaml = require('js-yaml'); const titleFrontmatter = yaml.dump({ title: this.noteTitle }); - return content.replace(this.FRONTMATTER_PATTERN, `---\n${titleFrontmatter}---\n`); + let processedContent = content.replace(this.FRONTMATTER_PATTERN, `---\n${titleFrontmatter}---\n`); + + // Add printed frontmatter if requested + if (this.options.printFrontmatter) { + const frontmatterDisplay = this.formatFrontmatterForDisplay(frontmatter); + processedContent = processedContent.replace( + this.FRONTMATTER_PATTERN, + `---\n${titleFrontmatter}---\n\n${frontmatterDisplay}\n\n` + ); + } + + return processedContent; } else { return content.replace(this.FRONTMATTER_PATTERN, ''); } @@ -288,6 +336,94 @@ export class MarkdownPreprocessor { return content; } } + + /** + * Format frontmatter as a readable display block + */ + private formatFrontmatterForDisplay(frontmatter: Record): string { + if (!frontmatter || Object.keys(frontmatter).length === 0) { + return ''; + } + + console.log('MarkdownPreprocessor: Formatting frontmatter for display:', frontmatter); + + const lines: string[] = []; + lines.push('**Document Information**'); + lines.push(''); + + // Format each frontmatter field + for (const [key, value] of Object.entries(frontmatter)) { + if (value !== undefined && value !== null && value !== '') { + // Format the key nicely (capitalize first letter, convert underscores to spaces) + const formattedKey = key.charAt(0).toUpperCase() + key.slice(1).replace(/_/g, ' '); + + // Handle different value types + let formattedValue: string; + if (Array.isArray(value)) { + // For arrays, put each item on its own line if there are many items + if (value.length > 3) { + formattedValue = '\n\n' + value.map(item => `- ${item}`).join('\n') + '\n'; + } else { + formattedValue = value.join(', '); + } + } else if (typeof value === 'object') { + formattedValue = JSON.stringify(value); + } else { + const valueStr = String(value); + // If the value is very long (like email lists), break it up + if (valueStr.length > 80 && valueStr.includes(',')) { + // Split on commas and format as a bulleted list + const items = valueStr.split(',').map(item => item.trim()); + if (items.length > 1) { + formattedValue = '\n\n' + items.map(item => `- ${item}`).join('\n') + '\n'; + } else { + formattedValue = valueStr; + } + } else if (valueStr.length > 100) { + // For other very long values, try to break at word boundaries + const words = valueStr.split(' '); + let currentLine = ''; + const wrappedLines: string[] = []; + + for (const word of words) { + if (currentLine.length + word.length + 1 > 80) { + if (currentLine) { + wrappedLines.push(currentLine); + currentLine = word; + } else { + wrappedLines.push(word); + } + } else { + currentLine += (currentLine ? ' ' : '') + word; + } + } + if (currentLine) { + wrappedLines.push(currentLine); + } + + formattedValue = '\n\n' + wrappedLines.join(' \n') + '\n'; + } else { + formattedValue = valueStr; + } + } + + // Add line break after the property label, then the value + if (formattedValue.startsWith('\n')) { + // Value already starts with newline (like lists), so just add the label + lines.push(`**${formattedKey}:**${formattedValue}`); + } else { + // Add a line break after the label for regular values + lines.push(`**${formattedKey}:**\n${formattedValue}`); + } + console.log(`MarkdownPreprocessor: Formatted ${key} ->`, JSON.stringify(formattedValue)); + } + } + + // Join with double newlines to ensure proper spacing between fields + const result = lines.join('\n\n'); + console.log('MarkdownPreprocessor: Final formatted frontmatter:', JSON.stringify(result)); + return result; +} /** * Extract tags from content diff --git a/src/converters/PandocTypstConverter.ts b/src/converters/PandocTypstConverter.ts index 09b3d3d..dc20911 100644 --- a/src/converters/PandocTypstConverter.ts +++ b/src/converters/PandocTypstConverter.ts @@ -99,6 +99,8 @@ export class PandocTypstConverter { // Create temporary markdown file await this.ensureTempDirectory(); const tempInputPath = path.join(this.tempDir!, `temp-${Date.now()}.md`); + + console.log('PandocTypstConverter: Writing markdown content to temp file:', JSON.stringify(content.substring(0, 1000))); await fsPromises.writeFile(tempInputPath, content, 'utf-8'); // Merge options @@ -141,7 +143,7 @@ export class PandocTypstConverter { /** * Process PDF embeds by converting them to images and creating combined output */ - async processPdfEmbeds(processedResult: any, vaultBasePath: string, tempDir: string): Promise { + async processPdfEmbeds(processedResult: any, vaultBasePath: string, tempDir: string, embedPdfFiles: boolean = true): Promise { const { PdfToImageConverter } = require('./PdfToImageConverter'); const converter = PdfToImageConverter.getInstance(this.plugin); @@ -164,7 +166,7 @@ export class PandocTypstConverter { continue; } - // Convert PDF to image + // Convert PDF to image (always happens regardless of embedPdfFiles setting) const conversionResult = await converter.convertFirstPageToImage( fullPdfPath, tempDir, @@ -180,13 +182,20 @@ export class PandocTypstConverter { // Get relative path for the generated image const relativeImagePath = path.relative(vaultBasePath, conversionResult.imagePath); - // Create combined output: image preview + PDF attachment link - const combinedOutput = [ - `![${pdfEmbed.fileName} - Page 1](${relativeImagePath})`, - `[📎 **Download PDF:** ${pdfEmbed.fileName}](${pdfEmbed.sanitizedPath})` - ].join('\n\n'); + // Create output based on embedPdfFiles setting + let combinedOutput: string; + if (embedPdfFiles) { + // Include both image preview and PDF attachment note + combinedOutput = [ + `![${pdfEmbed.fileName} - Page 1](${relativeImagePath})`, + `[📎 **Download PDF:** ${pdfEmbed.fileName}](${pdfEmbed.sanitizedPath})` + ].join('\n\n'); + } else { + // Only show image preview + combinedOutput = `![${pdfEmbed.fileName} - Page 1](${relativeImagePath})`; + } - // Replace marker with combined output + // Replace marker with output processedResult.content = processedResult.content.replace(pdfEmbed.marker, combinedOutput); console.log(`Export: Successfully converted PDF: ${pdfEmbed.fileName} -> ${path.basename(conversionResult.imagePath)}`); diff --git a/src/core/settings.ts b/src/core/settings.ts index db68da0..50a59f6 100644 --- a/src/core/settings.ts +++ b/src/core/settings.ts @@ -89,6 +89,10 @@ export interface obsidianTypstPDFExportSettings { exportConcurrency: number; /** Enable debug mode for verbose logging */ debugMode: boolean; + /** Whether to embed PDF files as attachments in the output PDF */ + embedPdfFiles: boolean; + /** Display frontmatter as formatted text at the beginning of the document */ + printFrontmatter: boolean; }; } @@ -145,6 +149,8 @@ export const DEFAULT_SETTINGS: obsidianTypstPDFExportSettings = { openAfterExport: true, preserveFolderStructure: true, exportConcurrency: 3, - debugMode: false + debugMode: false, + embedPdfFiles: true, + printFrontmatter: false } -};; \ No newline at end of file +};;;; \ No newline at end of file diff --git a/src/ui/modal/modalTypes.ts b/src/ui/modal/modalTypes.ts index aa89e96..5ee3e72 100644 --- a/src/ui/modal/modalTypes.ts +++ b/src/ui/modal/modalTypes.ts @@ -18,6 +18,10 @@ export interface ExportConfig { openAfterExport?: boolean; /** Preserve folder structure when exporting */ preserveFolderStructure?: boolean; + /** Whether to embed PDF files as attachments in the output PDF */ + embedPdfFiles?: boolean; + /** Display frontmatter as formatted text at the beginning of the document */ + printFrontmatter?: boolean; } export interface ExportConfigModalSettings extends ExportConfig { diff --git a/src/ui/modal/sections/BehaviorSection.ts b/src/ui/modal/sections/BehaviorSection.ts index 298dc9f..59a146c 100644 --- a/src/ui/modal/sections/BehaviorSection.ts +++ b/src/ui/modal/sections/BehaviorSection.ts @@ -42,6 +42,30 @@ export class BehaviorSection implements ModalSection { state.updateSettings({ preserveFolderStructure: value }); }); }); + + // Embed PDF files toggle + new Setting(this.container) + .setName('Embed PDF files') + .setDesc('Include PDF files as attachments in the exported PDF (in addition to preview images)') + .addToggle(toggle => { + toggle + .setValue(state.settings.embedPdfFiles !== false) + .onChange(value => { + state.updateSettings({ embedPdfFiles: value }); + }); + }); + + // Print frontmatter toggle + new Setting(this.container) + .setName('Print frontmatter') + .setDesc('Display frontmatter as formatted text at the beginning of the document') + .addToggle(toggle => { + toggle + .setValue(state.settings.printFrontmatter || false) + .onChange(value => { + state.updateSettings({ printFrontmatter: value }); + }); + }); } validate(): ValidationResult { diff --git a/src/ui/modal/state/ModalState.ts b/src/ui/modal/state/ModalState.ts index b9b5d16..ea015c8 100644 --- a/src/ui/modal/state/ModalState.ts +++ b/src/ui/modal/state/ModalState.ts @@ -84,7 +84,9 @@ export class ModalState implements IModalState { outputFolder: this.settings.outputFolder, templateVariables: this.templateVariables, openAfterExport: this.settings.openAfterExport, - preserveFolderStructure: this.settings.preserveFolderStructure + preserveFolderStructure: this.settings.preserveFolderStructure, + embedPdfFiles: this.settings.embedPdfFiles, + printFrontmatter: this.settings.printFrontmatter }; return config;