feat: add PDF embedding and frontmatter display controls
- 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 <noreply@anthropic.com>
This commit is contained in:
7 files changed
+342
-112
No files matched your search
@@ -27,6 +27,7 @@ import { ModalSettingsHelper } from './src/core/ModalSettingsHelper';
|
|||||||
import { ExportErrorHandler } from './src/core/ExportErrorHandler';
|
import { ExportErrorHandler } from './src/core/ExportErrorHandler';
|
||||||
import { TempDirectoryManager } from './src/core/TempDirectoryManager';
|
import { TempDirectoryManager } from './src/core/TempDirectoryManager';
|
||||||
import { PandocTypstConverter } from './src/converters/PandocTypstConverter';
|
import { PandocTypstConverter } from './src/converters/PandocTypstConverter';
|
||||||
|
import { MarkdownPreprocessor } from './src/converters/MarkdownPreprocessor';
|
||||||
import { ExportConfigModal } from './src/ui/modal/ExportConfigModal';
|
import { ExportConfigModal } from './src/ui/modal/ExportConfigModal';
|
||||||
import { ExportConfig, ExportConfigModalSettings } from './src/ui/modal/modalTypes';
|
import { ExportConfig, ExportConfigModalSettings } from './src/ui/modal/modalTypes';
|
||||||
import { TemplateManager } from './src/templates/TemplateManager';
|
import { TemplateManager } from './src/templates/TemplateManager';
|
||||||
@@ -451,32 +452,37 @@ export class obsidianTypstPDFExport extends Plugin {
|
|||||||
* Export a file with specific configuration
|
* Export a file with specific configuration
|
||||||
*/
|
*/
|
||||||
private async exportFileWithConfig(file: TFile, config: ExportConfig): Promise<void> {
|
private async exportFileWithConfig(file: TFile, config: ExportConfig): Promise<void> {
|
||||||
// Get plugin directory and vault base path
|
const pluginDir = this.manifest.dir!;
|
||||||
const vaultPath = (this.app.vault.adapter as any).basePath;
|
const vaultPath = (this.app.vault.adapter as any).basePath;
|
||||||
|
|
||||||
|
// Create controller for this export (allows cancellation)
|
||||||
|
this.currentExportController = new AbortController();
|
||||||
|
|
||||||
try {
|
try {
|
||||||
// Create abort controller for cancellation
|
// Create temp directory for conversion
|
||||||
this.currentExportController = new AbortController();
|
const tempManager = new TempDirectoryManager({ vaultPath: vaultPath });
|
||||||
|
const tempDir = tempManager.ensureTempDir('pandoc');
|
||||||
|
|
||||||
// Show progress notice
|
// Load file content
|
||||||
const progressNotice = ExportErrorHandler.showProgressNotice('Exporting to PDF...');
|
|
||||||
|
|
||||||
// Read file content
|
|
||||||
const content = await this.app.vault.read(file);
|
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
|
// Create progress notice with cancel button
|
||||||
const tempManager = TempDirectoryManager.create(vaultPath);
|
const progressNotice = new Notice('', 0);
|
||||||
const tempDir = tempManager.ensureTempDir('images');
|
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
|
// Preprocess markdown
|
||||||
const { MarkdownPreprocessor } = await import('./src/converters/MarkdownPreprocessor');
|
|
||||||
const preprocessor = new MarkdownPreprocessor({
|
const preprocessor = new MarkdownPreprocessor({
|
||||||
vaultPath: vaultPath,
|
vaultPath: vaultPath,
|
||||||
options: {
|
options: {
|
||||||
includeMetadata: true,
|
includeMetadata: true,
|
||||||
preserveFrontmatter: false,
|
preserveFrontmatter: config.printFrontmatter ?? this.settings.behavior.printFrontmatter,
|
||||||
baseUrl: undefined
|
baseUrl: undefined,
|
||||||
|
printFrontmatter: config.printFrontmatter ?? this.settings.behavior.printFrontmatter
|
||||||
},
|
},
|
||||||
wikilinkConfig: {
|
wikilinkConfig: {
|
||||||
format: 'md',
|
format: 'md',
|
||||||
@@ -497,7 +503,8 @@ export class obsidianTypstPDFExport extends Plugin {
|
|||||||
// Process PDF embeds if any were found
|
// Process PDF embeds if any were found
|
||||||
if (processedResult.metadata.pdfEmbeds && processedResult.metadata.pdfEmbeds.length > 0) {
|
if (processedResult.metadata.pdfEmbeds && processedResult.metadata.pdfEmbeds.length > 0) {
|
||||||
console.log(`Export: Processing ${processedResult.metadata.pdfEmbeds.length} PDF embeds`);
|
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
|
// Process image embeds if any were found
|
||||||
@@ -749,52 +756,65 @@ ${dependencyResult.allAvailable
|
|||||||
* @returns Object with relative paths for image and PDF
|
* @returns Object with relative paths for image and PDF
|
||||||
*/
|
*/
|
||||||
private async copyImageToVaultTemp(
|
private async copyImageToVaultTemp(
|
||||||
imagePath: string,
|
imagePath: string,
|
||||||
pdfPath: string,
|
pdfPath: string,
|
||||||
baseName: string,
|
baseName: string,
|
||||||
vaultBasePath: string
|
vaultBasePath: string
|
||||||
): Promise<{ relativeImagePath: string; relativePdfPath: string }> {
|
): Promise<{ relativeImagePath: string; relativePdfPath: string }> {
|
||||||
const pathModule = require('path');
|
const pathModule = require('path');
|
||||||
const fs = require('fs');
|
const fs = require('fs');
|
||||||
|
|
||||||
// Copy image to vault temp directory for access
|
// Copy image to vault temp directory for access
|
||||||
const vaultTempImagesDir = pathModule.join(vaultBasePath, '.obsidian', 'plugins', 'obsidian-typst-pdf-export', 'temp-images');
|
const vaultTempImagesDir = pathModule.join(vaultBasePath, '.obsidian', 'plugins', 'obsidian-typst-pdf-export', 'temp-images');
|
||||||
await fs.promises.mkdir(vaultTempImagesDir, { recursive: true });
|
await fs.promises.mkdir(vaultTempImagesDir, { recursive: true });
|
||||||
|
|
||||||
const imageFileName = `${baseName}_preview.png`;
|
// Sanitize the basename for use in filename - replace problematic characters
|
||||||
const vaultImagePath = pathModule.join(vaultTempImagesDir, imageFileName);
|
const sanitizedBaseName = baseName
|
||||||
await fs.promises.copyFile(imagePath, vaultImagePath);
|
.replace(/[^a-zA-Z0-9\-_]/g, '_') // Replace non-alphanumeric chars with underscore
|
||||||
|
.replace(/_{2,}/g, '_') // Collapse multiple underscores
|
||||||
// Get relative paths from vault base
|
.replace(/^_+|_+$/g, ''); // Remove leading/trailing underscores
|
||||||
const relativeImagePath = pathModule.relative(vaultBasePath, vaultImagePath);
|
|
||||||
const relativePdfPath = pathModule.relative(vaultBasePath, pdfPath);
|
const imageFileName = `${sanitizedBaseName}_preview.png`;
|
||||||
|
const vaultImagePath = pathModule.join(vaultTempImagesDir, imageFileName);
|
||||||
return { relativeImagePath, relativePdfPath };
|
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(
|
private generatePdfEmbedContent(
|
||||||
relativePdfPath: string,
|
relativePdfPath: string,
|
||||||
baseName: string,
|
baseName: string,
|
||||||
relativeImagePath?: string,
|
relativeImagePath?: string,
|
||||||
errorSuffix?: string
|
errorSuffix?: string,
|
||||||
|
embedPdfFiles: boolean = true
|
||||||
): string {
|
): string {
|
||||||
const description = `${baseName}${errorSuffix ? ` ${errorSuffix}` : ''}`;
|
const description = `${baseName}${errorSuffix ? ` ${errorSuffix}` : ''}`;
|
||||||
const attachmentNote = `*PDF attached: ${description} - check your PDF reader's attachment panel*`;
|
|
||||||
|
|
||||||
const content = [
|
const content = [];
|
||||||
relativeImagePath ? `` : null,
|
|
||||||
relativeImagePath ? '' : null,
|
|
||||||
'```{=typst}',
|
|
||||||
`#pdf.embed("${relativePdfPath}", description: "${description}", mime-type: "application/pdf")`,
|
|
||||||
'```',
|
|
||||||
'',
|
|
||||||
attachmentNote
|
|
||||||
].filter(line => line !== null).join('\n');
|
|
||||||
|
|
||||||
return content;
|
// Always include image preview if available
|
||||||
|
if (relativeImagePath) {
|
||||||
|
content.push(``);
|
||||||
|
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<void> {
|
private async processPdfEmbeds(processedResult: any, vaultBasePath: string, tempDir: string, currentFile?: TFile, embedPdfFiles: boolean = true): Promise<void> {
|
||||||
const { PdfToImageConverter } = await import('./src/converters/PdfToImageConverter');
|
const { PdfToImageConverter } = await import('./src/converters/PdfToImageConverter');
|
||||||
const converter = PdfToImageConverter.getInstance(this);
|
const converter = PdfToImageConverter.getInstance(this);
|
||||||
const pathModule = require('path');
|
const pathModule = require('path');
|
||||||
@@ -840,22 +860,30 @@ ${dependencyResult.allAvailable
|
|||||||
vaultBasePath
|
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(
|
const combinedOutput = this.generatePdfEmbedContent(
|
||||||
relativePdfPath,
|
relativePdfPath,
|
||||||
pdfEmbed.baseName,
|
pdfEmbed.baseName,
|
||||||
relativeImagePath
|
relativeImagePath,
|
||||||
|
undefined,
|
||||||
|
embedPdfFiles
|
||||||
);
|
);
|
||||||
|
|
||||||
// Replace the placeholder with the combined output
|
// Replace the placeholder with the combined output
|
||||||
updatedContent = updatedContent.replace(pdfEmbed.marker, combinedOutput);
|
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 {
|
} else {
|
||||||
console.warn(`Export: Failed to convert PDF to image: ${result.error}`);
|
console.warn(`Export: Failed to convert PDF to image: ${result.error}`);
|
||||||
const relativePdfPath = pathModule.relative(vaultBasePath, fullPdfPath);
|
const relativePdfPath = pathModule.relative(vaultBasePath, fullPdfPath);
|
||||||
// Even without preview image, still embed the PDF
|
// Even without preview image, still embed the PDF if requested
|
||||||
const fallbackOutput = this.generatePdfEmbedContent(relativePdfPath, pdfEmbed.baseName);
|
const fallbackOutput = this.generatePdfEmbedContent(
|
||||||
|
relativePdfPath,
|
||||||
|
pdfEmbed.baseName,
|
||||||
|
undefined,
|
||||||
|
'(preview not available)',
|
||||||
|
embedPdfFiles
|
||||||
|
);
|
||||||
updatedContent = updatedContent.replace(pdfEmbed.marker, fallbackOutput);
|
updatedContent = updatedContent.replace(pdfEmbed.marker, fallbackOutput);
|
||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
@@ -866,7 +894,8 @@ ${dependencyResult.allAvailable
|
|||||||
relativePdfPath,
|
relativePdfPath,
|
||||||
pdfEmbed.baseName,
|
pdfEmbed.baseName,
|
||||||
undefined,
|
undefined,
|
||||||
'(error occurred)'
|
'(error occurred)',
|
||||||
|
embedPdfFiles
|
||||||
);
|
);
|
||||||
updatedContent = updatedContent.replace(pdfEmbed.marker, fallbackOutput);
|
updatedContent = updatedContent.replace(pdfEmbed.marker, fallbackOutput);
|
||||||
}
|
}
|
||||||
@@ -1418,38 +1447,58 @@ class ObsidianTypstPDFExportSettingTab extends PluginSettingTab {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private createBehaviorSection(containerEl: HTMLElement): void {
|
private createBehaviorSection(containerEl: HTMLElement): void {
|
||||||
containerEl.createEl('h3', { text: 'Behavior' });
|
containerEl.createEl('h3', { text: 'Behavior' });
|
||||||
|
|
||||||
new Setting(containerEl)
|
new Setting(containerEl)
|
||||||
.setName('Open after export')
|
.setName('Open after export')
|
||||||
.setDesc('Automatically open PDF after successful export')
|
.setDesc('Automatically open PDF after successful export')
|
||||||
.addToggle(toggle => toggle
|
.addToggle(toggle => toggle
|
||||||
.setValue(this.plugin.settings.behavior.openAfterExport)
|
.setValue(this.plugin.settings.behavior.openAfterExport)
|
||||||
.onChange(async (value) => {
|
.onChange(async (value) => {
|
||||||
this.plugin.settings.behavior.openAfterExport = value;
|
this.plugin.settings.behavior.openAfterExport = value;
|
||||||
await this.plugin.saveSettings();
|
await this.plugin.saveSettings();
|
||||||
}));
|
}));
|
||||||
|
|
||||||
new Setting(containerEl)
|
new Setting(containerEl)
|
||||||
.setName('Preserve folder structure')
|
.setName('Preserve folder structure')
|
||||||
.setDesc('Maintain vault folder structure in output directory')
|
.setDesc('Maintain vault folder structure in output directory')
|
||||||
.addToggle(toggle => toggle
|
.addToggle(toggle => toggle
|
||||||
.setValue(this.plugin.settings.behavior.preserveFolderStructure)
|
.setValue(this.plugin.settings.behavior.preserveFolderStructure)
|
||||||
.onChange(async (value) => {
|
.onChange(async (value) => {
|
||||||
this.plugin.settings.behavior.preserveFolderStructure = value;
|
this.plugin.settings.behavior.preserveFolderStructure = value;
|
||||||
await this.plugin.saveSettings();
|
await this.plugin.saveSettings();
|
||||||
}));
|
}));
|
||||||
|
|
||||||
new Setting(containerEl)
|
new Setting(containerEl)
|
||||||
.setName('Debug mode')
|
.setName('Embed PDF files')
|
||||||
.setDesc('Enable verbose logging for troubleshooting')
|
.setDesc('Include PDF files as attachments in the exported PDF (in addition to preview images)')
|
||||||
.addToggle(toggle => toggle
|
.addToggle(toggle => toggle
|
||||||
.setValue(this.plugin.settings.behavior.debugMode)
|
.setValue(this.plugin.settings.behavior.embedPdfFiles)
|
||||||
.onChange(async (value) => {
|
.onChange(async (value) => {
|
||||||
this.plugin.settings.behavior.debugMode = value;
|
this.plugin.settings.behavior.embedPdfFiles = value;
|
||||||
await this.plugin.saveSettings();
|
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
|
// Helper methods for fonts
|
||||||
private async getAvailableFonts(): Promise<string[]> {
|
private async getAvailableFonts(): Promise<string[]> {
|
||||||
|
|||||||
@@ -10,6 +10,8 @@ export interface PreprocessorOptions {
|
|||||||
preserveFrontmatter: boolean;
|
preserveFrontmatter: boolean;
|
||||||
/** Base URL for relative link resolution */
|
/** Base URL for relative link resolution */
|
||||||
baseUrl?: string;
|
baseUrl?: string;
|
||||||
|
/** Display frontmatter as formatted text at the beginning of the document */
|
||||||
|
printFrontmatter?: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface WikilinkConfig {
|
export interface WikilinkConfig {
|
||||||
@@ -199,27 +201,51 @@ export class MarkdownPreprocessor {
|
|||||||
result.metadata.title = parsed.data.title.trim();
|
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) {
|
if (this.options.preserveFrontmatter) {
|
||||||
// Keep the frontmatter in the content, but reconstruct it with the modified title
|
// Keep the frontmatter in the content, but reconstruct it with the modified title
|
||||||
if (this.noteTitle) {
|
const yaml = require('js-yaml');
|
||||||
const yaml = require('js-yaml');
|
const newFrontmatter = yaml.dump(finalFrontmatter);
|
||||||
const frontmatterCopy = { ...parsed.data };
|
let processedContent = `---\n${newFrontmatter}---\n${parsed.content}`;
|
||||||
frontmatterCopy.title = this.noteTitle;
|
|
||||||
const newFrontmatter = yaml.dump(frontmatterCopy);
|
// Add printed frontmatter if requested
|
||||||
return `---\n${newFrontmatter}---\n${parsed.content}`;
|
if (this.options.printFrontmatter) {
|
||||||
} else {
|
const frontmatterDisplay = this.formatFrontmatterForDisplay(finalFrontmatter);
|
||||||
return content;
|
processedContent = `---\n${newFrontmatter}---\n\n${frontmatterDisplay}\n\n${parsed.content}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
return processedContent;
|
||||||
} else {
|
} else {
|
||||||
// Return content without frontmatter, but add title as frontmatter for Pandoc
|
// Return content without frontmatter, but add title as frontmatter for Pandoc
|
||||||
|
let processedContent: string;
|
||||||
if (this.noteTitle) {
|
if (this.noteTitle) {
|
||||||
const yaml = require('js-yaml');
|
const yaml = require('js-yaml');
|
||||||
const titleFrontmatter = yaml.dump({ title: this.noteTitle });
|
const titleFrontmatter = yaml.dump({ title: this.noteTitle });
|
||||||
console.log('Replacing frontmatter with title:', titleFrontmatter);
|
console.log('Replacing frontmatter with title:', titleFrontmatter);
|
||||||
return `---\n${titleFrontmatter}---\n${parsed.content}`;
|
processedContent = `---\n${titleFrontmatter}---\n${parsed.content}`;
|
||||||
} else {
|
} 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 {
|
} else {
|
||||||
// No frontmatter found - add title frontmatter if we have a noteTitle
|
// No frontmatter found - add title frontmatter if we have a noteTitle
|
||||||
@@ -266,7 +292,18 @@ export class MarkdownPreprocessor {
|
|||||||
if (this.noteTitle) {
|
if (this.noteTitle) {
|
||||||
const yaml = require('js-yaml');
|
const yaml = require('js-yaml');
|
||||||
const newFrontmatter = yaml.dump(frontmatter);
|
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 {
|
} else {
|
||||||
return content;
|
return content;
|
||||||
}
|
}
|
||||||
@@ -275,7 +312,18 @@ export class MarkdownPreprocessor {
|
|||||||
if (this.noteTitle) {
|
if (this.noteTitle) {
|
||||||
const yaml = require('js-yaml');
|
const yaml = require('js-yaml');
|
||||||
const titleFrontmatter = yaml.dump({ title: this.noteTitle });
|
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 {
|
} else {
|
||||||
return content.replace(this.FRONTMATTER_PATTERN, '');
|
return content.replace(this.FRONTMATTER_PATTERN, '');
|
||||||
}
|
}
|
||||||
@@ -288,6 +336,94 @@ export class MarkdownPreprocessor {
|
|||||||
return content;
|
return content;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Format frontmatter as a readable display block
|
||||||
|
*/
|
||||||
|
private formatFrontmatterForDisplay(frontmatter: Record<string, any>): 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
|
* Extract tags from content
|
||||||
|
|||||||
@@ -99,6 +99,8 @@ export class PandocTypstConverter {
|
|||||||
// Create temporary markdown file
|
// Create temporary markdown file
|
||||||
await this.ensureTempDirectory();
|
await this.ensureTempDirectory();
|
||||||
const tempInputPath = path.join(this.tempDir!, `temp-${Date.now()}.md`);
|
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');
|
await fsPromises.writeFile(tempInputPath, content, 'utf-8');
|
||||||
|
|
||||||
// Merge options
|
// Merge options
|
||||||
@@ -141,7 +143,7 @@ export class PandocTypstConverter {
|
|||||||
/**
|
/**
|
||||||
* Process PDF embeds by converting them to images and creating combined output
|
* Process PDF embeds by converting them to images and creating combined output
|
||||||
*/
|
*/
|
||||||
async processPdfEmbeds(processedResult: any, vaultBasePath: string, tempDir: string): Promise<void> {
|
async processPdfEmbeds(processedResult: any, vaultBasePath: string, tempDir: string, embedPdfFiles: boolean = true): Promise<void> {
|
||||||
const { PdfToImageConverter } = require('./PdfToImageConverter');
|
const { PdfToImageConverter } = require('./PdfToImageConverter');
|
||||||
const converter = PdfToImageConverter.getInstance(this.plugin);
|
const converter = PdfToImageConverter.getInstance(this.plugin);
|
||||||
|
|
||||||
@@ -164,7 +166,7 @@ export class PandocTypstConverter {
|
|||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Convert PDF to image
|
// Convert PDF to image (always happens regardless of embedPdfFiles setting)
|
||||||
const conversionResult = await converter.convertFirstPageToImage(
|
const conversionResult = await converter.convertFirstPageToImage(
|
||||||
fullPdfPath,
|
fullPdfPath,
|
||||||
tempDir,
|
tempDir,
|
||||||
@@ -180,13 +182,20 @@ export class PandocTypstConverter {
|
|||||||
// Get relative path for the generated image
|
// Get relative path for the generated image
|
||||||
const relativeImagePath = path.relative(vaultBasePath, conversionResult.imagePath);
|
const relativeImagePath = path.relative(vaultBasePath, conversionResult.imagePath);
|
||||||
|
|
||||||
// Create combined output: image preview + PDF attachment link
|
// Create output based on embedPdfFiles setting
|
||||||
const combinedOutput = [
|
let combinedOutput: string;
|
||||||
``,
|
if (embedPdfFiles) {
|
||||||
`[📎 **Download PDF:** ${pdfEmbed.fileName}](${pdfEmbed.sanitizedPath})`
|
// Include both image preview and PDF attachment note
|
||||||
].join('\n\n');
|
combinedOutput = [
|
||||||
|
``,
|
||||||
|
`[📎 **Download PDF:** ${pdfEmbed.fileName}](${pdfEmbed.sanitizedPath})`
|
||||||
|
].join('\n\n');
|
||||||
|
} else {
|
||||||
|
// Only show image preview
|
||||||
|
combinedOutput = ``;
|
||||||
|
}
|
||||||
|
|
||||||
// Replace marker with combined output
|
// Replace marker with output
|
||||||
processedResult.content = processedResult.content.replace(pdfEmbed.marker, combinedOutput);
|
processedResult.content = processedResult.content.replace(pdfEmbed.marker, combinedOutput);
|
||||||
|
|
||||||
console.log(`Export: Successfully converted PDF: ${pdfEmbed.fileName} -> ${path.basename(conversionResult.imagePath)}`);
|
console.log(`Export: Successfully converted PDF: ${pdfEmbed.fileName} -> ${path.basename(conversionResult.imagePath)}`);
|
||||||
|
|||||||
@@ -89,6 +89,10 @@ export interface obsidianTypstPDFExportSettings {
|
|||||||
exportConcurrency: number;
|
exportConcurrency: number;
|
||||||
/** Enable debug mode for verbose logging */
|
/** Enable debug mode for verbose logging */
|
||||||
debugMode: boolean;
|
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,
|
openAfterExport: true,
|
||||||
preserveFolderStructure: true,
|
preserveFolderStructure: true,
|
||||||
exportConcurrency: 3,
|
exportConcurrency: 3,
|
||||||
debugMode: false
|
debugMode: false,
|
||||||
|
embedPdfFiles: true,
|
||||||
|
printFrontmatter: false
|
||||||
}
|
}
|
||||||
};;
|
};;;;
|
||||||
@@ -18,6 +18,10 @@ export interface ExportConfig {
|
|||||||
openAfterExport?: boolean;
|
openAfterExport?: boolean;
|
||||||
/** Preserve folder structure when exporting */
|
/** Preserve folder structure when exporting */
|
||||||
preserveFolderStructure?: boolean;
|
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 {
|
export interface ExportConfigModalSettings extends ExportConfig {
|
||||||
|
|||||||
@@ -42,6 +42,30 @@ export class BehaviorSection implements ModalSection {
|
|||||||
state.updateSettings({ preserveFolderStructure: value });
|
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 {
|
validate(): ValidationResult {
|
||||||
|
|||||||
@@ -84,7 +84,9 @@ export class ModalState implements IModalState {
|
|||||||
outputFolder: this.settings.outputFolder,
|
outputFolder: this.settings.outputFolder,
|
||||||
templateVariables: this.templateVariables,
|
templateVariables: this.templateVariables,
|
||||||
openAfterExport: this.settings.openAfterExport,
|
openAfterExport: this.settings.openAfterExport,
|
||||||
preserveFolderStructure: this.settings.preserveFolderStructure
|
preserveFolderStructure: this.settings.preserveFolderStructure,
|
||||||
|
embedPdfFiles: this.settings.embedPdfFiles,
|
||||||
|
printFrontmatter: this.settings.printFrontmatter
|
||||||
};
|
};
|
||||||
|
|
||||||
return config;
|
return config;
|
||||||
|
|||||||
Reference in new issue
Block a user