Skip to content

armgit / Filee

Public Imported from GitHub
0

Free, open-source file converter. Convert 263 formats offline by drag & drop — images, PDF, Word, Excel, PowerPoint, HWP/HWPX, video, audio, e-books and archives. No upload, no Office needed.

PDF → Markdown: pictures next to the file, text-only option, fewer running heads

KnifeLemon14d6878bcb16
diff --git a/docs/ENGINES.md b/docs/ENGINES.md
index 3ff7b465..415a65b3 100644
--- a/docs/ENGINES.md
+++ b/docs/ENGINES.md
@@ -10,14 +10,14 @@ Filee chooses engines automatically. Settings → *Engines* shows their status,
| ICNS | built in | images → ICNS (16–1024 px), ICNS → images |
| PDFsharp | built in (library) | images → PDF, merge, split, page ranges, **compression** (smaller PDFs, see below) |
| PDFium | built in (library) | PDF → images (multi-page TIFF/GIF supported) |
-| Unhwp | built in (library) | HWP/HWPX → TXT, Markdown, HTML |
+| Unhwp | built in (library) | HWP/HWPX → TXT, Markdown, HTML (pictures in a `<name>_files` folder next to the Markdown, embedded in the HTML) |
| Markdown (Markdig) | built in (library) | **Markdown → HTML, TXT** (and → PDF / DOCX through the HWPX writer, rhwp or LibreOffice) |
| Spreadsheets (ExcelDataReader for XLS) | built in (library) | **XLSX, XLS, ODS, CSV, TSV → XLSX, ODS, CSV, TSV** (one CSV / TSV per sheet) |
| Office Open XML | built in | **DOCM / DOTX / DOTM ↔ DOCX, XLSM / XLTX ↔ XLSX, PPTM / POTX / PPSX ↔ PPTX** (macros removed for macro-free types) |
| Fonts | built in | **TTF, OTF, WOFF, WOFF2, EOT ↔ each other**; CFF (PostScript) outlines become TrueType for TTF and EOT |
| **HWPX writer** | built in | **DOCX (+ DOCM/DOTX/DOTM), XLSX (+ XLSM/XLTX), XLS, ODS, CSV, TSV, PPTX (+ PPTM/POTX/PPSX), PDF, HTML, EPUB, MOBI/AZW3, FB2, HWPX, TXT, Markdown → HWPX** (and with rhwp → PDF and images); ODT, RTF, reStructuredText, LaTeX → HWPX with Pandoc |
| **DOCX writer** | built in | **HWPX (and HWP through rhwp), PDF, HTML, EPUB, MOBI/AZW3, FB2, Markdown, TXT, XLSX, XLS, ODS, CSV, PPTX (+ variants) → DOCX** |
-| PDF text | built in (PdfPig) | **PDF → TXT** (reading order, also two columns; no OCR) |
+| PDF text | built in (PdfPig) | **PDF → TXT, Markdown** (reading order, also two columns; Markdown keeps headings, emphasis, links and the pictures; no OCR) |
| PDF slides | built in (PDFium, PdfPig) | **PDF → PPTX**: a picture of each page on its own slide (looks like the PDF, not editable), the page's text in the speaker notes |
| E-mail | built in (MimeKit, MsgReader) | **EML, Outlook MSG → HTML** (headers + body, inline pictures), **TXT**, **ZIP** (the attachments); **MSG → EML** |
| Data | built in (System.Text.Json, YamlDotNet, Tomlyn, System.Xml) | **JSON, JSON Lines, YAML, TOML, XML, CSV ↔ each other** (CSV for tables); **vCard ↔ CSV**; spreadsheets and contacts reach JSON / YAML / TOML / XML through CSV |
@@ -370,7 +370,7 @@ it. DOCX → DOCX is no edge; the Word variants are the Office Open XML engine's
## PDF reader
`Pdf/PdfDocumentReader*.cs` reads PDFs with PdfPig (Apache-2.0) into the document model, for PDF → DOCX, HWPX and
-(with `PdfTextConverter`) TXT:
+(with `PdfTextConverter`) TXT and Markdown:
- words with their positions, fonts, sizes and colours → lines → paragraphs: a line continues the paragraph above
when it follows at about one line pitch, unless it starts with a bullet or number, is indented as a first line,
@@ -387,8 +387,11 @@ it. DOCX → DOCX is no edge; the Word variants are the Office Open XML engine's
and italic from the fonts, colours, links from link annotations, alignment, indents, spacing and line pitch;
- pictures: JPEG streams are kept as they are, others are decoded to PNG, and what PdfPig cannot decode is cut out
of the rendered page; a picture covering the page behind text (the scan under an OCR layer) is skipped;
-- page size per page and margins shared by the document; running headers and footers that repeat on most pages
- (and bare page numbers) are left out;
+- page size per page and margins shared by the document; what sits at the top or bottom edge only because it is a
+ page is left out: running headers and footers that repeat on most pages (digits ignored, so "Page 3" matches
+ "Page 4"), running heads that change with the chapter (the same text at the same height on three pages or more,
+ no larger than the body text, so a heading that starts several pages stays), bare page numbers ("12", "- 12 -",
+ "Page 3 of 10", "第 3 页", roman "iv") and the same picture (a logo) at the same place on most pages;
- a page without text (a scan, a page of drawings, a turned page) becomes the rendered page (PDFium, 150 dpi JPEG)
as a picture behind the text of an empty page, so nothing is lost; there is no OCR. PDF → TXT includes the
invisible OCR text layer of scanned PDFs that have one.
@@ -396,6 +399,18 @@ it. DOCX → DOCX is no edge; the Word variants are the Office Open XML engine's
Password-protected PDFs fail with a clear message. Not converted: tables (their cells come out as paragraphs in
reading order), vector drawings on text pages, form fields and annotations other than links.
+**PDF → Markdown** is one step (`PdfTextConverter`, a `DirectOnly` edge, so PDF → HTML, EPUB, ... never start going
+through a Markdown file): the document is written by `MarkdownWriter` as for e-books, with headings (`#`, not bold
+inside), bold / italic and links. Indents are the PDF's layout, not block quotes, and the PDF's information title
+(often a file name) gives no front matter. A Markdown file can't hold pictures, so `Text/MarkdownPictures.cs` writes
+them into a folder next to it, reserved through the output allocator like any output (`report.md` →
+`report_files/img0001.jpg`, `report_files (2)` when that folder is taken), and links them relatively, so editors
+show them and the pair can be moved together; JPEGs are the PDF's own, a scanned page is the picture of the page.
+The preset option *Leave out pictures* (`DocumentOptions.LeaveOutPictures`, Documents card, shown for Markdown)
+writes the text only, read like PDF → TXT (the invisible OCR layer of scans included) and without a folder. The same
+option applies to every Markdown writer: e-books (`EbookConverter`), HWP / HWPX (`UnhwpConverter`) and Pandoc (a
+Lua filter drops the pictures, figures keep their captions).
+
## PDF → PPTX
`Pdf/PdfSlidesConverter.cs` turns a PDF into a PowerPoint deck of pictures: every page is rendered (PDFium, as for
@@ -824,7 +839,8 @@ DocBook (`.dbk`, `.docbook`; written as DocBook 5), Jupyter notebooks (`.ipynb`)
- Extensions that mean other things are not claimed: man pages only as `.man` (`.1` … `.9` are also rotated logs,
`app.log.1`), DocBook as `.dbk` / `.docbook`, never every `.xml`.
- DocBook, man pages, OPML, Typst, HTML and LaTeX are written with `--standalone` (a root element, a `.TH` header,
- a preamble), the text formats extract pictures into `<name>_files` next to the result.
+ a preamble), the text formats extract pictures into `<name>_files` next to the result (Markdown with *Leave out
+ pictures* gets none: a Lua filter drops them).
## Subtitles
diff --git a/src/Filee.App/Assets/i18n/en.json b/src/Filee.App/Assets/i18n/en.json
index 7a0f9ab5..81b656b6 100644
--- a/src/Filee.App/Assets/i18n/en.json
+++ b/src/Filee.App/Assets/i18n/en.json
@@ -423,6 +423,8 @@
"presets.split_tall_image_hint": "Off: a long image is scaled down to the format's limit (JPG 65,500 px, WebP 16,383 px).\nOn: it keeps its size and is split between pages into several files (name_1, name_2, …).",
"presets.group.document": "Documents",
"presets.pdfa": "PDF/A (archival)",
+ "presets.leave_out_pictures": "Leave out pictures (text only)",
+ "presets.leave_out_pictures_hint": "Off: the pictures are saved in a \"name_files\" folder next to the Markdown file and linked from it.\nOn: only the text, no folder.",
"presets.target_folder": "Folder (extract archives)",
"presets.group.media": "Video & audio",
"presets.media_quality": "Quality",
diff --git a/src/Filee.App/Assets/i18n/ko.json b/src/Filee.App/Assets/i18n/ko.json
index 923542c3..9325caa2 100644
--- a/src/Filee.App/Assets/i18n/ko.json
+++ b/src/Filee.App/Assets/i18n/ko.json
@@ -423,6 +423,8 @@
"presets.split_tall_image_hint": "끄면 긴 이미지를 형식의 최대 높이(JPG 65,500px, WebP 16,383px)에 맞게 줄여요.\n켜면 원래 크기 그대로 페이지 사이에서 나눠 여러 파일(이름_1, 이름_2, …)로 저장해요.",
"presets.group.document": "문서",
"presets.pdfa": "PDF/A (장기 보존용)",
+ "presets.leave_out_pictures": "그림 빼기 (텍스트만)",
+ "presets.leave_out_pictures_hint": "끄면: 그림을 마크다운 파일 옆 \"이름_files\" 폴더에 저장하고 파일에서 연결해요.\n켜면: 폴더 없이 텍스트만 남겨요.",
"presets.target_folder": "폴더 (압축 풀기)",
"presets.group.media": "동영상·오디오",
"presets.media_quality": "품질",
diff --git a/src/Filee.App/Assets/i18n/pl.json b/src/Filee.App/Assets/i18n/pl.json
index ec2d5a7e..83c4309e 100644
--- a/src/Filee.App/Assets/i18n/pl.json
+++ b/src/Filee.App/Assets/i18n/pl.json
@@ -423,6 +423,8 @@
"presets.split_tall_image_hint": "Wyłączone: długi obraz jest zmniejszany do limitu formatu (JPG 65 500 px, WebP 16 383 px).\nWłączone: zachowuje rozmiar i jest dzielony między stronami na kilka plików (nazwa_1, nazwa_2, …).",
"presets.group.document": "Dokumenty",
"presets.pdfa": "PDF/A (archiwalny)",
+ "presets.leave_out_pictures": "Pomiń obrazy (tylko tekst)",
+ "presets.leave_out_pictures_hint": "Wyłączone: obrazy trafiają do folderu „nazwa_files” obok pliku Markdown, który do nich linkuje.\nWłączone: tylko tekst, bez folderu.",
"presets.target_folder": "Folder (rozpakuj archiwa)",
"presets.group.media": "Wideo i audio",
"presets.media_quality": "Jakość",
diff --git a/src/Filee.App/Assets/i18n/zh-CN.json b/src/Filee.App/Assets/i18n/zh-CN.json
index 5f1f8504..d800805c 100644
--- a/src/Filee.App/Assets/i18n/zh-CN.json
+++ b/src/Filee.App/Assets/i18n/zh-CN.json
@@ -423,6 +423,8 @@
"presets.split_tall_image_hint": "关闭时,长图会缩小到该格式的最大高度(JPG 65,500 像素,WebP 16,383 像素)。\n打开时保持原尺寸,在页面之间分开,保存成多个文件(名称_1、名称_2……)。",
"presets.group.document": "文档",
"presets.pdfa": "PDF/A(长期存档)",
+ "presets.leave_out_pictures": "不保留图片(仅文本)",
+ "presets.leave_out_pictures_hint": "关闭时,图片保存在 Markdown 文件旁的“名称_files”文件夹中,并从文件中链接。\n开启时,只保留文字,不生成文件夹。",
"presets.target_folder": "文件夹(解压缩)",
"presets.group.media": "视频和音频",
"presets.media_quality": "质量",
diff --git a/src/Filee.App/ViewModels/PresetEditorViewModel.cs b/src/Filee.App/ViewModels/PresetEditorViewModel.cs
index cbba2856..11c47f9a 100644
--- a/src/Filee.App/ViewModels/PresetEditorViewModel.cs
+++ b/src/Filee.App/ViewModels/PresetEditorViewModel.cs
@@ -147,6 +147,7 @@ public sealed partial class PresetEditorViewModel : ObservableObject
_trimPageMargins = _edit.Pdf.TrimPageMargins;
_splitTallImage = _edit.Pdf.SplitTallImage;
_pdfA = _edit.Document.PdfA;
+ _leaveOutPictures = _edit.Document.LeaveOutPictures;
_subfolderName = _edit.Output.SubfolderName;
_customFolder = _edit.Output.CustomFolder;
_pattern = _edit.Output.FileNamePattern;
@@ -182,7 +183,7 @@ public sealed partial class PresetEditorViewModel : ObservableObject
[ObservableProperty]
[NotifyPropertyChangedFor(nameof(ShowImage), nameof(ShowTurnForPdf), nameof(ShowQuality), nameof(ShowTiff), nameof(ShowMultiPageTiff), nameof(ShowWebp), nameof(ShowIco),
- nameof(ShowPdf), nameof(ShowPdfBuild), nameof(ShowDocument), nameof(ShowPdfSplit), nameof(ShowPdfCombine),
+ nameof(ShowPdf), nameof(ShowPdfBuild), nameof(ShowDocument), nameof(ShowLeaveOutPictures), nameof(ShowPdfSplit), nameof(ShowPdfCombine),
nameof(ShowPdfCompression), nameof(ShowPdfCompressionOptions),
nameof(ShowMedia), nameof(ShowMediaQuality), nameof(ShowMaxHeight), nameof(ShowAudioBitrate), nameof(ShowRemoveAudio),
nameof(ShowAudioChannels), nameof(ShowWav), nameof(VideoCodecs), nameof(VideoCodecChoice), nameof(ShowVideoCodec), nameof(ShowHardwareEncoding),
@@ -315,6 +316,9 @@ public sealed partial class PresetEditorViewModel : ObservableObject
[ObservableProperty] private bool _trimPageMargins;
[ObservableProperty] private bool _splitTallImage;
[ObservableProperty] private bool _pdfA;
+
+ /// <summary>Markdown: the text only, no picture folder next to it (DocumentOptions.LeaveOutPictures).</summary>
+ [ObservableProperty] private bool _leaveOutPictures;
[ObservableProperty] private string _subfolderName;
[ObservableProperty] private string _customFolder;
[ObservableProperty] private string _pattern;
@@ -399,6 +403,8 @@ public sealed partial class PresetEditorViewModel : ObservableObject
public bool ShowPdfCombine => TargetCategory == FormatCategory.Image
&& TargetId is not ("tiff" or "gif" or "apng" or "mng" or "ico" or "cur" or "icns" or "svg" or "pdf");
public bool ShowDocument => TargetId == "pdf";
+ /// <summary>Markdown can't hold pictures: they go into a folder next to it, or are left out.</summary>
+ public bool ShowLeaveOutPictures => TargetId == "md";
public bool ShowMedia => ShowMediaQuality || ShowMaxHeight || ShowRemoveAudio || ShowAudioChannels || ShowVideoCodec || ShowAudioCodec;
/// <summary>Mono / stereo for every audio target but AMR, which is mono by definition.</summary>
public bool ShowAudioChannels => TargetIsAudio && TargetId != "amr";
@@ -489,6 +495,8 @@ public sealed partial class PresetEditorViewModel : ObservableObject
pdf.Compression = CompressionLevel.Value;
pdf.CompressWithGhostscript = CompressWithGhostscript;
_original.Document.PdfA = PdfA;
+ // Only where the option is shown, as with SaveEveryFrame below.
+ _original.Document.LeaveOutPictures = ShowLeaveOutPictures && LeaveOutPictures;
var media = _original.Media;
media.Quality = MediaQuality.Value;
diff --git a/src/Filee.App/Views/PresetEditorView.axaml b/src/Filee.App/Views/PresetEditorView.axaml
index cebecfbd..0cfff9b0 100644
--- a/src/Filee.App/Views/PresetEditorView.axaml
+++ b/src/Filee.App/Views/PresetEditorView.axaml
@@ -225,6 +225,17 @@
</StackPanel>
</Border>
+ <!-- Documents → Markdown: pictures in a folder next to the file, or text only -->
+ <Border x:Name="DocumentCard" Classes="card" Padding="14" IsVisible="{Binding ShowLeaveOutPictures}">
+ <StackPanel Spacing="10">
+ <TextBlock Classes="h2" Text="{DynamicResource presets.group.document}" />
+ <StackPanel Spacing="2">
+ <CheckBox Content="{DynamicResource presets.leave_out_pictures}" IsChecked="{Binding LeaveOutPictures}" />
+ <TextBlock Classes="caption" TextWrapping="Wrap" Margin="28,0,0,0" Text="{DynamicResource presets.leave_out_pictures_hint}" />
+ </StackPanel>
+ </StackPanel>
+ </Border>
+
<!-- PDF options (render settings also apply when a PDF is converted to images) -->
<Border Classes="card" Padding="14" IsVisible="{Binding ShowPdf}">
<StackPanel Spacing="10">
diff --git a/src/Filee.Core/Presets/Preset.cs b/src/Filee.Core/Presets/Preset.cs
index 305d9b27..c1c014a7 100644
--- a/src/Filee.Core/Presets/Preset.cs
+++ b/src/Filee.Core/Presets/Preset.cs
@@ -360,6 +360,11 @@ public sealed class DocumentOptions
/// <summary>Export PDF/A (archival) when producing PDF from documents.</summary>
public bool PdfA { get; set; }
+ /// <summary>
+ /// Markdown output: the text only, without the document's pictures (no "&lt;name&gt;_files" folder next to it).
+ /// </summary>
+ public bool LeaveOutPictures { get; set; }
+
public DocumentOptions Clone() => (DocumentOptions)MemberwiseClone();
}
diff --git a/src/Filee.Engines/Ebooks/EbookConverter.cs b/src/Filee.Engines/Ebooks/EbookConverter.cs
index c32e11a9..fe51f2e2 100644
--- a/src/Filee.Engines/Ebooks/EbookConverter.cs
+++ b/src/Filee.Engines/Ebooks/EbookConverter.cs
@@ -10,6 +10,7 @@ using Filee.Core.Conversion;
using Filee.Engines.Hwp.Hwpx;
using Filee.Engines.Hwp.Hwpx.Docx;
using Filee.Engines.Infrastructure;
+using Filee.Engines.Text;
namespace Filee.Engines.Ebooks;
@@ -159,8 +160,11 @@ public sealed class EbookConverter : IConverter
break;
}
case "md":
- File.WriteAllText(output, MarkdownWriter.Write(book.Document, MarkdownImages(output, work)), new UTF8Encoding(false));
- break;
+ {
+ Func<string, string?> pictures = step.Preset.Document.LeaveOutPictures ? _ => null : new MarkdownPictures(output, step.Output, work).Add;
+ File.WriteAllText(output, MarkdownWriter.Write(book.Document, pictures), new UTF8Encoding(false));
+ break;
+ }
case "fb2":
Fb2Writer.Write(book, output, step.InputPath, work);
break;
@@ -206,24 +210,4 @@ public sealed class EbookConverter : IConverter
EbookFiles.CommonImage(path, convertFolder, gifAndSvg: true) is ({ } file, { } mediaType)
? $"data:{mediaType};base64,{System.Convert.ToBase64String(File.ReadAllBytes(file))}"
: null;
-
- /// <summary>Pictures of a Markdown export go to "&lt;name&gt;_files" next to it, referenced relatively.</summary>
- private static Func<string, string?> MarkdownImages(string output, string work)
- {
- var folderName = Path.GetFileNameWithoutExtension(output) + "_files";
- var folder = Path.Combine(Path.GetDirectoryName(output)!, folderName);
- var convert = EbookFiles.NewFolder(work, "md-images");
- var names = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
- return path =>
- {
- if (names.TryGetValue(path, out var known))
- return known;
- if (EbookFiles.CommonImage(path, convert, gifAndSvg: true) is not ({ } file, _))
- return null;
- Directory.CreateDirectory(folder);
- var name = $"img{names.Count + 1:0000}{Path.GetExtension(file).ToLowerInvariant()}";
- File.Copy(file, Path.Combine(folder, name), overwrite: true);
- return names[path] = $"{Uri.EscapeDataString(folderName)}/{name}";
- };
- }
}
diff --git a/src/Filee.Engines/Hwp/UnhwpConverter.cs b/src/Filee.Engines/Hwp/UnhwpConverter.cs
index 84fd928b..86fcd067 100644
--- a/src/Filee.Engines/Hwp/UnhwpConverter.cs
+++ b/src/Filee.Engines/Hwp/UnhwpConverter.cs
@@ -1,7 +1,15 @@
// HWP / HWPX → plain text, Markdown or HTML with Unhwp (MIT, native library shipped in the NuGet package).
+//
+// Unhwp's Markdown links pictures as "assets/<id>" without writing them: Filee takes each picture from the document
+// (GetResourceData) and puts it into a "<name>_files" folder next to the Markdown file (MarkdownPictures), or embeds
+// it in the HTML page as a data: URI, so the page stays one file. Pictures it can't provide are left out instead of
+// becoming broken links; "Leave out pictures" (DocumentOptions.LeaveOutPictures) leaves out all of them.
+using System.Text.RegularExpressions;
using Filee.Core.Conversion;
+using Filee.Engines.Ebooks;
using Filee.Engines.Infrastructure;
+using Filee.Engines.Text;
using Markdig;
using Unhwp;
@@ -12,6 +20,9 @@ public sealed class UnhwpConverter : IConverter
{
private static readonly MarkdownPipeline Pipeline = new MarkdownPipelineBuilder().UseAdvancedExtensions().Build();
+ /// <summary>A picture in Unhwp's Markdown: <c>![alt](assets/image1.jpg)</c>, the id being the resource's.</summary>
+ private static readonly Regex AssetPicture = new(@"!\[([^\]\n]*)\]\(assets/([^)\s]+)\)", RegexOptions.Compiled | RegexOptions.CultureInvariant);
+
public string Id => "unhwp";
public string DisplayName => "Unhwp";
public int MaxParallelism => 0;
@@ -41,22 +52,67 @@ public sealed class UnhwpConverter : IConverter
cancellationToken.ThrowIfCancellationRequested();
progress?.Report(0.5);
+ var path = step.Output.Allocate(step.To);
+ if (path is null)
+ return [];
var content = step.To switch
{
"txt" => document.ToText(),
- "md" => document.ToMarkdown(new MarkdownOptions { IncludeFrontmatter = false }),
- "html" => ToHtml(document.ToMarkdown(new MarkdownOptions()), document.Title ?? Path.GetFileNameWithoutExtension(step.InputPath)),
+ "md" => WriteMarkdown(document, step, path),
+ "html" => ToHtml(Pictures(document.ToMarkdown(new MarkdownOptions()), document, step.WorkDirectory, DataUri),
+ document.Title ?? Path.GetFileNameWithoutExtension(step.InputPath)),
_ => throw new NotSupportedException(step.To),
};
-
- var path = step.Output.Allocate(step.To);
- if (path is null)
- return [];
File.WriteAllText(path, content, new System.Text.UTF8Encoding(encoderShouldEmitUTF8Identifier: step.To == "txt"));
progress?.Report(1);
return [path];
}, cancellationToken);
+ private static string WriteMarkdown(UnhwpDocument document, ConversionStep step, string output)
+ {
+ var markdown = document.ToMarkdown(new MarkdownOptions { IncludeFrontmatter = false });
+ Func<string, string?> link = step.Preset.Document.LeaveOutPictures
+ ? _ => null
+ : new MarkdownPictures(output, step.Output, step.WorkDirectory).Add;
+ return Pictures(markdown, document, step.WorkDirectory, link);
+ }
+
+ /// <summary>
+ /// Points the "assets/…" pictures of Unhwp's Markdown at <paramref name="link"/>(file of the picture); a picture
+ /// without a link is left out, with the empty paragraph it stood in.
+ /// </summary>
+ internal static string Pictures(string markdown, UnhwpDocument document, string workDirectory, Func<string, string?> link)
+ {
+ if (!AssetPicture.IsMatch(markdown))
+ return markdown;
+ var ids = document.GetResourceIds().ToHashSet(StringComparer.Ordinal);
+ var folder = EbookFiles.NewFolder(workDirectory, "unhwp-pictures");
+ var files = new Dictionary<string, string?>(StringComparer.Ordinal);
+ var result = AssetPicture.Replace(markdown, match =>
+ {
+ var id = match.Groups[2].Value;
+ if (!files.TryGetValue(id, out var target))
+ {
+ target = null;
+ if (ids.Contains(id) && document.GetResourceData(id) is { Length: > 0 } data)
+ {
+ var file = Path.Combine(folder, $"{files.Count + 1}-{Path.GetFileName(id)}");
+ File.WriteAllBytes(file, data);
+ target = link(file);
+ }
+ files[id] = target;
+ }
+ return target is null ? "" : $"![{match.Groups[1].Value}](<{target}>)";
+ });
+ // Paragraphs that held only a picture left behind: at most one empty line between blocks.
+ return Regex.Replace(result, @"\n{3,}", "\n\n").Trim() + "\n";
+ }
+
+ private static string? DataUri(string file) =>
+ EbookFiles.CommonImage(file, Path.GetDirectoryName(file)!, gifAndSvg: true) is ({ } common, { } mediaType)
+ ? $"data:{mediaType};base64,{Convert.ToBase64String(File.ReadAllBytes(common))}"
+ : null;
+
private static string ToHtml(string markdown, string title) =>
- Text.MarkdownConverter.HtmlPage(title, Markdown.ToHtml(markdown, Pipeline));
+ MarkdownConverter.HtmlPage(title, Markdown.ToHtml(markdown, Pipeline));
}
diff --git a/src/Filee.Engines/Office/PandocConverter.cs b/src/Filee.Engines/Office/PandocConverter.cs
index 8dac1fee..fe7f2a83 100644
--- a/src/Filee.Engines/Office/PandocConverter.cs
+++ b/src/Filee.Engines/Office/PandocConverter.cs
@@ -2,7 +2,8 @@
// Adds Markdown ↔ DOCX / ODT / RTF, HTML ↔ DOCX / ODT, the markup languages (reStructuredText, LaTeX, Org, AsciiDoc,
// Typst, MediaWiki, DocBook, Jupyter notebooks, Textile, man pages, OPML) ↔ Markdown / HTML / DOCX / ODT and each
// other (and → RTF, EPUB, TXT), and Markdown and the lightweight markups → PPTX slides. Markdown → HTML / TXT / HWPX /
-// DOCX is built in (MarkdownConverter, the HWPX and DOCX writers).
+// DOCX is built in (MarkdownConverter, the HWPX and DOCX writers). Pictures of a text result are extracted into a
+// "<name>_files" folder next to it; Markdown with "Leave out pictures" gets none (a Lua filter drops them).
using Filee.Core.Conversion;
using Filee.Core.Formats;
@@ -121,7 +122,9 @@ public sealed class PandocConverter : IConverter
List<string> args = [step.InputPath, "-f", Readers[step.From], "-t", Writers[step.To], "-o", output];
if (Standalone.Contains(step.To))
args.Add("--standalone");
- if (ExtractsMedia.Contains(step.To))
+ if (step.To == "md" && step.Preset.Document.LeaveOutPictures)
+ args.Add("--lua-filter=" + WithoutPictures(step.WorkDirectory));
+ else if (ExtractsMedia.Contains(step.To))
args.Add("--extract-media=" + Path.Combine(Path.GetDirectoryName(output)!, Path.GetFileNameWithoutExtension(output) + "_files"));
ProcessResult result;
@@ -134,6 +137,21 @@ public sealed class PandocConverter : IConverter
return [output];
}
+ /// <summary>
+ /// A Lua filter that drops every picture ("Leave out pictures", DocumentOptions.LeaveOutPictures); a figure keeps
+ /// its caption as text.
+ /// </summary>
+ private static string WithoutPictures(string workDirectory)
+ {
+ Directory.CreateDirectory(workDirectory);
+ var path = Path.Combine(workDirectory, $"no-pictures-{Guid.NewGuid():N}.lua");
+ File.WriteAllText(path, """
+ function Image(image) return {} end
+ function Figure(figure) return figure.caption.long end
+ """);
+ return path;
+ }
+
/// <summary>Uses the selected copy, a bundled copy, then the system installation.</summary>
internal static string? Locate() =>
EngineEnvironment.OwnProgram("pandoc", "pandoc.exe") ?? LocateBundled() ?? EngineEnvironment.SystemProgram("pandoc", "pandoc.exe");
diff --git a/src/Filee.Engines/Pdf/PdfDocumentReader.cs b/src/Filee.Engines/Pdf/PdfDocumentReader.cs
index f25d868c..33dbb978 100644
--- a/src/Filee.Engines/Pdf/PdfDocumentReader.cs
+++ b/src/Filee.Engines/Pdf/PdfDocumentReader.cs
@@ -2,9 +2,10 @@
//
// Every page's words (with their positions, fonts, sizes and colours) become lines, lines become paragraphs, and the
// paragraphs and pictures are put in reading order, also on two-column pages (PdfDocumentReader.Layout). Headings
-// come from font sizes, bold / italic from the fonts, page size and margins from the page. Headers and footers that
-// repeat on the pages (and bare page numbers) are left out. A page without text (a scan) becomes the rendered page as
-// a picture (PDFium via PDFtoImage), so the result is complete; there is no OCR.
+// come from font sizes, bold / italic from the fonts, page size and margins from the page. Running headers and
+// footers (also those that change with the chapter), page numbers and a logo repeated at the top or bottom of the
+// pages are left out. A page without text (a scan) becomes the rendered page as a picture (PDFium via PDFtoImage), so
+// the result is complete; there is no OCR.
//
// Rows laid out with tab stops (a number, a label and a date far to the right) stay one line with tabs at the PDF's
// positions, and a line that ends early although the next line's first word would have fitted (an address) keeps its
@@ -456,9 +457,21 @@ internal sealed partial class PdfDocumentReader
"^[\\s\\-–—(\\[]*(page|p\\.|페이지|第)?\\s*\\d+\\s*(/|of|페이지|쪽|页)?\\s*\\d*[\\s\\-–—)\\]]*$",
RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.Compiled);
+ /// <summary>Page numbers in roman numerals ("iv", "- XII -"), as front matter is often numbered.</summary>
+ private static readonly Regex RomanPageNumber = new(
+ "^[\\s\\-–—(\\[]*(?=[ivxlcdm])m{0,3}(cm|cd|d?c{0,3})(xc|xl|l?x{0,3})(ix|iv|v?i{0,3})[\\s\\-–—)\\]]*$",
+ RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.Compiled);
+
/// <summary>
- /// Leaves out paragraphs at the top or bottom edge that repeat on most pages (running heads, footers; digits are
- /// ignored so "Page 3" matches "Page 4") and bare page numbers there.
+ /// Leaves out what sits at the top or bottom edge of the pages only because it is a page (running heads, footers,
+ /// page numbers), so text exports read on without it:
+ /// <list type="bullet">
+ /// <item>paragraphs that repeat on most pages (digits are ignored, so "Page 3" matches "Page 4");</item>
+ /// <item>running heads that change with the chapter: the same text at the same height on three pages or more,
+ /// no larger than the body text (a heading that starts several pages is larger, and stays);</item>
+ /// <item>bare page numbers ("12", "- 12 -", "Page 3 of 10", "iv");</item>
+ /// <item>the same picture (a logo) at the same place on most pages.</item>
+ /// </list>
/// </summary>
private static void RemoveRepeatedHeadersAndFooters(List<PageContent> pages)
{
@@ -467,19 +480,47 @@ internal sealed partial class PdfDocumentReader
return;
bool AtEdge(Item item, PageContent page) => item.Top > page.Height * 0.9 || item.Bottom < page.Height * 0.1;
static string Key(Item item) => Regex.Replace(item.Text, "\\d+", "#").Trim();
+ static (string Key, long Top) Place(Item item) => (Key(item), (long)Math.Round(item.Top / 2));
- var counts = textPages
- .SelectMany(p => p.Items.Where(i => !i.IsPicture && AtEdge(i, p)).Select(i => (Page: p.Index, Key: Key(i))).Distinct())
+ var edgeText = textPages.SelectMany(p => p.Items.Where(i => !i.IsPicture && AtEdge(i, p)).Select(i => (Page: p.Index, Item: i))).ToList();
+ var counts = edgeText.Select(x => (x.Page, Key: Key(x.Item))).Distinct()
.GroupBy(x => x.Key)
.ToDictionary(g => g.Key, g => g.Count());
+ var placeCounts = edgeText.Select(x => (x.Page, Place: Place(x.Item))).Distinct()
+ .GroupBy(x => x.Place)
+ .ToDictionary(g => g.Key, g => g.Count());
+ var bodySize = BodySize([.. textPages.SelectMany(p => p.Items.Where(i => !i.IsPicture))]);
var needed = Math.Max(2, (int)Math.Ceiling(textPages.Count * 0.5));
+
+ bool RunningText(Item item) =>
+ item.Lines.Count <= 2
+ && (counts.GetValueOrDefault(Key(item)) >= needed
+ || (placeCounts.GetValueOrDefault(Place(item)) >= 3 && item.Size <= bodySize + 0.5)
+ || PageNumber.IsMatch(item.Text) || RomanPageNumber.IsMatch(item.Text));
+
+ var pictureKeys = textPages.SelectMany(p => p.Items.Where(i => i.IsPicture && AtEdge(i, p))).ToDictionary(i => i, PictureKey);
+ var pictureCounts = textPages
+ .SelectMany(p => p.Items.Where(pictureKeys.ContainsKey).Select(i => (Page: p.Index, Key: pictureKeys[i])).Distinct())
+ .GroupBy(x => x.Key)
+ .ToDictionary(g => g.Key, g => g.Count());
+
foreach (var page in textPages)
{
- page.Items.RemoveAll(i => !i.IsPicture && AtEdge(i, page) && i.Lines.Count <= 2
- && (counts.GetValueOrDefault(Key(i)) >= needed || PageNumber.IsMatch(i.Text)));
+ page.Items.RemoveAll(i => AtEdge(i, page) && (i.IsPicture
+ ? pictureCounts.GetValueOrDefault(pictureKeys[i]) >= needed
+ : RunningText(i)));
}
}
+ /// <summary>A picture's place (to 2 points) and content: the same logo on every page has the same key.</summary>
+ private static string PictureKey(Item item)
+ {
+ var bounds = item.PictureBounds!.Value;
+ var bytes = File.ReadAllBytes(item.PicturePath!);
+ return FormattableString.Invariant($"{Math.Round(bounds.Left / 2)},{Math.Round(bounds.Top / 2)},{Math.Round(bounds.Width / 2)},{Math.Round(bounds.Height / 2)}:")
+ + Convert.ToHexString(System.Security.Cryptography.SHA256.HashData(bytes));
+ }
+
// ───────────────────────── Building the document ─────────────────────────
private HDocument Build(List<PageContent> pages, string? title)
diff --git a/src/Filee.Engines/Pdf/PdfTextConverter.cs b/src/Filee.Engines/Pdf/PdfTextConverter.cs
index a91d8353..86859ffb 100644
--- a/src/Filee.Engines/Pdf/PdfTextConverter.cs
+++ b/src/Filee.Engines/Pdf/PdfTextConverter.cs
@@ -1,39 +1,102 @@
-// PDF → TXT with PdfPig (Apache-2.0): the text in reading order (also on two-column pages), one paragraph per line and
-// an empty line between paragraphs. The invisible text layer of OCR-processed scans is included; scans without one
-// have no text to extract (Filee does no OCR).
+// PDF → TXT and Markdown with PdfPig (Apache-2.0), read by PdfDocumentReader: the text in reading order (also on
+// two-column pages), without running headers, footers and page numbers.
+//
+// TXT has one paragraph per line and an empty line between paragraphs. The invisible text layer of OCR-processed
+// scans is included; scans without one have no text to extract (Filee does no OCR).
+//
+// Markdown keeps headings, bold / italic and links (MarkdownWriter, as for e-books). The pictures go into a
+// "<name>_files" folder next to the Markdown file and are linked relatively (MarkdownPictures); a page without text
+// (a scan) becomes the picture of the page. With "Leave out pictures" (DocumentOptions.LeaveOutPictures) the
+// Markdown is read like TXT: text only, OCR layers included.
using System.Text;
using Filee.Core.Conversion;
+using Filee.Engines.Hwp.Hwpx;
using Filee.Engines.Infrastructure;
+using Filee.Engines.Text;
namespace Filee.Engines.Pdf;
-/// <summary>Extracts the text of PDF files.</summary>
+/// <summary>Extracts the text of PDF files, as plain text or Markdown.</summary>
public sealed class PdfTextConverter : IConverter
{
public string Id => "pdf-text";
public string DisplayName => "PDF text (built-in)";
public int MaxParallelism => 0;
- public IReadOnlyList<ConversionEdge> Edges { get; } = [new("pdf", "txt")];
+ public IReadOnlyList<ConversionEdge> Edges { get; } =
+ [
+ new("pdf", "txt"),
+ // Read once, written once: cheaper than through DOCX and Pandoc or HWPX and Unhwp. Direct only, so no other
+ // route (PDF → HTML, EPUB, ...) starts going through a Markdown file and its picture folder.
+ new("pdf", "md", 10 + DocumentReaders.PdfPenalty, DirectOnly: true),
+ ];
- public EngineStatus GetStatus() => EngineStatus.Available("PDF → TXT", $"{EngineVersions.BuiltIn} · {EngineVersions.Library("PdfPig", typeof(UglyToad.PdfPig.PdfDocument))}");
+ public EngineStatus GetStatus() => EngineStatus.Available("PDF → TXT, Markdown", $"{EngineVersions.BuiltIn} · {EngineVersions.Library("PdfPig", typeof(UglyToad.PdfPig.PdfDocument))}");
public Task<IReadOnlyList<string>> ConvertAsync(ConversionStep step, IProgress<double>? progress, CancellationToken cancellationToken) =>
- Task.Run<IReadOnlyList<string>>(() =>
+ Task.Run(() => step.To == "md" ? Markdown(step, progress, cancellationToken) : Text(step, progress, cancellationToken), cancellationToken);
+
+ private static IReadOnlyList<string> Text(ConversionStep step, IProgress<double>? progress, CancellationToken cancellationToken)
+ {
+ progress?.Report(0.1);
+ var text = PdfDocumentReader.PlainText(PdfDocumentReader.ReadText(step.InputPath));
+ cancellationToken.ThrowIfCancellationRequested();
+ if (text.Length == 0)
+ throw NoText();
+
+ var output = step.Output.Allocate("txt");
+ if (output is null)
+ return [];
+ // UTF-8 with BOM, so Notepad and Excel-era tools pick the right encoding for Korean and Chinese text.
+ File.WriteAllText(output, text, new UTF8Encoding(encoderShouldEmitUTF8Identifier: true));
+ progress?.Report(1);
+ return [output];
+ }
+
+ private static IReadOnlyList<string> Markdown(ConversionStep step, IProgress<double>? progress, CancellationToken cancellationToken)
+ {
+ progress?.Report(0.1);
+ var textOnly = step.Preset.Document.LeaveOutPictures;
+ var document = textOnly
+ ? PdfDocumentReader.ReadText(step.InputPath)
+ : PdfDocumentReader.Read(step.InputPath, Path.Combine(step.WorkDirectory, $"media-{Guid.NewGuid():N}"));
+ cancellationToken.ThrowIfCancellationRequested();
+ if (textOnly && PdfDocumentReader.PlainText(document).Length == 0)
+ throw NoText();
+ progress?.Report(0.6);
+
+ // The PDF's information title is often a file name ("Microsoft Word - report.docx"): no front matter. Indents
+ // are the PDF's layout, not quotes (MarkdownWriter reads large left indents as block quote levels), and
+ // headings are bold by nature (no "# **Title**").
+ document.Title = null;
+ foreach (var paragraph in document.Sections.SelectMany(s => s.Blocks).OfType<HParagraph>())
{
- progress?.Report(0.1);
- var text = PdfDocumentReader.PlainText(PdfDocumentReader.ReadText(step.InputPath));
- cancellationToken.ThrowIfCancellationRequested();
- if (text.Length == 0)
- throw new InvalidOperationException("The PDF contains no text (it may be scanned; Filee does not recognise text in images).");
-
- var output = step.Output.Allocate("txt");
- if (output is null)
- return [];
- // UTF-8 with BOM, so Notepad and Excel-era tools pick the right encoding for Korean and Chinese text.
- File.WriteAllText(output, text, new UTF8Encoding(encoderShouldEmitUTF8Identifier: true));
- progress?.Report(1);
- return [output];
- }, cancellationToken);
+ paragraph.Format = paragraph.Format with { Left = null };
+ if (paragraph.HeadingLevel > 0)
+ NotBold(paragraph.Inlines);
+ }
+
+ var output = step.Output.Allocate("md");
+ if (output is null)
+ return [];
+ Func<string, string?> pictures = textOnly ? _ => null : new MarkdownPictures(output, step.Output, step.WorkDirectory).Add;
+ File.WriteAllText(output, MarkdownWriter.Write(document, pictures), new UTF8Encoding(encoderShouldEmitUTF8Identifier: false));
+ progress?.Report(1);
+ return [output];
+ }
+
+ private static void NotBold(List<HInline> inlines)
+ {
+ for (var i = 0; i < inlines.Count; i++)
+ {
+ if (inlines[i] is HText text)
+ inlines[i] = new HText(text.Text, text.Format with { Bold = null });
+ else if (inlines[i] is HLink link)
+ NotBold(link.Content);
+ }
+ }
+
+ private static InvalidOperationException NoText() =>
+ new("The PDF contains no text (it may be scanned; Filee does not recognise text in images).");
}
diff --git a/src/Filee.Engines/Text/MarkdownPictures.cs b/src/Filee.Engines/Text/MarkdownPictures.cs
new file mode 100644
index 00000000..0520cb97
--- /dev/null
+++ b/src/Filee.Engines/Text/MarkdownPictures.cs
@@ -0,0 +1,70 @@
+// The pictures of a Markdown file Filee writes (e-books, PDF, HWP → Markdown): a Markdown file can't hold pictures,
+// so they go into a folder next to it ("report.md" → "report_files/img0001.jpg") and are linked relatively, which
+// every Markdown editor shows and which keeps working when both are moved together.
+
+using Filee.Core.Conversion;
+using Filee.Engines.Ebooks;
+
+namespace Filee.Engines.Text;
+
+/// <summary>Writes the pictures of one Markdown output into its "_files" folder and hands out their links.</summary>
+internal sealed class MarkdownPictures
+{
+ /// <summary>Name suffix of the picture folder: "report.md" → "report_files".</summary>
+ public const string FolderSuffix = "_files";
+
+ private readonly string _markdown;
+ private readonly IOutputAllocator _output;
+ private readonly string _convertFolder;
+ private readonly Dictionary<string, string> _links = new(StringComparer.OrdinalIgnoreCase);
+ private string? _folder;
+ private bool _skipped;
+
+ /// <param name="markdown">The Markdown file being written (already allocated).</param>
+ /// <param name="output">The allocator that handed it out: the folder is reserved through it, like any output.</param>
+ /// <param name="workDirectory">Scratch space for pictures converted to a common format.</param>
+ public MarkdownPictures(string markdown, IOutputAllocator output, string workDirectory)
+ {
+ _markdown = markdown;
+ _output = output;
+ _convertFolder = Path.Combine(workDirectory, "md-pictures-" + Guid.NewGuid().ToString("N")[..8]);
+ }
+
+ /// <summary>
+ /// Copies the picture at <paramref name="path"/> into the folder (formats editors don't show, such as BMP or
+ /// WebP, as PNG or JPEG) and returns its relative link, or null when it can't be read or the folder is skipped.
+ /// The same picture used twice is written once.
+ /// </summary>
+ public string? Add(string path)
+ {
+ if (_links.TryGetValue(path, out var known))
+ return known;
+ if (EbookFiles.CommonImage(path, _convertFolder, gifAndSvg: true) is not ({ } file, _) || Folder() is not { } folder)
+ return null;
+ var name = $"img{_links.Count + 1:0000}{Path.GetExtension(file).ToLowerInvariant()}";
+ File.Copy(file, Path.Combine(folder, name), overwrite: true);
+ return _links[path] = $"{Uri.EscapeDataString(Path.GetFileName(folder))}/{name}";
+ }
+
+ /// <summary>
+ /// The folder, created on the first picture: reserved through the allocator ("report_files", "report_files (2)"
+ /// or skipped, as the preset's conflict rule says). An intermediate Markdown file (a step of a longer route) keeps
+ /// it right beside itself, so the next step finds the pictures.
+ /// </summary>
+ private string? Folder()
+ {
+ if (_folder is not null || _skipped)
+ return _folder;
+ var beside = Path.GetDirectoryName(Path.GetFullPath(_markdown))!;
+ var folder = _output.Allocate("", FolderSuffix);
+ if (folder is not null && !string.Equals(Path.GetDirectoryName(Path.GetFullPath(folder)), beside, StringComparison.OrdinalIgnoreCase))
+ folder = Path.Combine(beside, Path.GetFileNameWithoutExtension(_markdown) + FolderSuffix);
+ if (folder is null)
+ {
+ _skipped = true;
+ return null;
+ }
+ Directory.CreateDirectory(folder);
+ return _folder = folder;
+ }
+}
diff --git a/tests/Filee.App.Tests/RenderTests.cs b/tests/Filee.App.Tests/RenderTests.cs
index d284a6f3..24e8505d 100644
--- a/tests/Filee.App.Tests/RenderTests.cs
+++ b/tests/Filee.App.Tests/RenderTests.cs
@@ -1033,6 +1033,37 @@ public class RenderTests
Assert.Equal((Filee.Core.Presets.TracingMode.BlackAndWhite, 64, 80), (preset.Trace.Mode, preset.Trace.Colors, preset.Trace.Detail));
}
+ [AvaloniaTheory]
+ [InlineData("en")]
+ [InlineData("ko")]
+ [InlineData("zh-CN")]
+ public void Preset_editor_offers_markdown_without_pictures(string language)
+ {
+ TestServices.EnsureInitialized(language);
+ var store = AppHost.Get<UserDataStore>();
+ var preset = store.FindPreset("to-md")!.Clone();
+ var vm = new PresetEditorViewModel(preset, AppHost.Get<ILocalizer>());
+ Assert.True(vm.ShowLeaveOutPictures);
+ Assert.False(vm.LeaveOutPictures);
+
+ var window = new PresetEditorWindow { DataContext = vm, Height = 760 };
+ window.Show();
+ Pump();
+ Assert.True(window.GetVisualDescendants().OfType<Border>().Single(b => b.Name == "DocumentCard").IsVisible);
+ Save(window, $"preset-markdown-{language}.png");
+ window.Close();
+
+ vm.LeaveOutPictures = true;
+ Assert.True(vm.Apply());
+ Assert.True(preset.Document.LeaveOutPictures);
+
+ // Other targets don't show it, and don't keep it.
+ vm.Target = vm.Targets.Single(t => t.Value == "docx");
+ Assert.False(vm.ShowLeaveOutPictures);
+ Assert.True(vm.Apply());
+ Assert.False(preset.Document.LeaveOutPictures);
+ }
+
[AvaloniaFact]
public void Preset_editor_saves_media_and_archive_options()
{
diff --git a/tests/Filee.Engines.Tests/DocumentEngineTests.cs b/tests/Filee.Engines.Tests/DocumentEngineTests.cs
index f741567b..68989bf0 100644
--- a/tests/Filee.Engines.Tests/DocumentEngineTests.cs
+++ b/tests/Filee.Engines.Tests/DocumentEngineTests.cs
@@ -74,6 +74,39 @@ public class DocumentEngineTests(EngineFixture fx) : IClassFixture<EngineFixture
Assert.Contains("두 번째 문단입니다", await File.ReadAllTextAsync(job.Outputs.Single(), TestContext.Current.CancellationToken));
}
+ [Fact]
+ public async Task Hwpx_to_markdown_and_html_keeps_the_pictures()
+ {
+ SkipUnlessAvailable("unhwp");
+ var dir = fx.NewFolder();
+ EngineFixture.MakeImage(dir, "chart.png", ImageMagick.MagickFormat.Png);
+ var source = Path.Combine(dir, "memo.md");
+ await File.WriteAllTextAsync(source, "# 회의 메모\n\n그림 앞 문단.\n\n![](chart.png)\n\n그림 뒤 문단.\n", TestContext.Current.CancellationToken);
+ var hwpx = (await fx.ConvertAsync([source], new Preset { TargetFormat = "hwpx" })).Outputs.Single();
+ Assert.Equal("unhwp", Assert.Single(fx.Catalog.CreatePlanner().Plan("hwpx", "md")!.Steps).Converter.Id);
+
+ // Unhwp links "assets/image1.png" without writing it: the picture goes into "memo_files" next to the result.
+ var md = (await fx.ConvertAsync([hwpx], new Preset { TargetFormat = "md" })).Outputs.Single();
+ var markdown = await File.ReadAllTextAsync(md, TestContext.Current.CancellationToken);
+ Assert.DoesNotContain("assets/", markdown);
+ var link = System.Text.RegularExpressions.Regex.Match(markdown, @"!\[[^\]]*\]\(<([^>]+)>\)").Groups[1].Value;
+ Assert.StartsWith("memo_files/", link, StringComparison.Ordinal);
+ Assert.True(File.Exists(Path.Combine(dir, Uri.UnescapeDataString(link))));
+ Assert.Contains("그림 뒤 문단", markdown);
+
+ // HTML is one page: the picture is embedded.
+ var html = await File.ReadAllTextAsync((await fx.ConvertAsync([hwpx], new Preset { TargetFormat = "html" })).Outputs.Single(), TestContext.Current.CancellationToken);
+ Assert.Contains("src=\"data:image/png;base64,", html);
+ Assert.DoesNotContain("assets/", html);
+
+ // Text only: no picture, no folder.
+ var folders = Directory.GetDirectories(dir).Length;
+ var textOnly = await File.ReadAllTextAsync((await fx.ConvertAsync([hwpx], new Preset { TargetFormat = "md", Document = { LeaveOutPictures = true } })).Outputs.Single(), TestContext.Current.CancellationToken);
+ Assert.DoesNotContain("![", textOnly);
+ Assert.Contains("그림 앞 문단.\n\n그림 뒤 문단", textOnly.ReplaceLineEndings("\n"));
+ Assert.Equal(folders, Directory.GetDirectories(dir).Length);
+ }
+
[Fact]
public async Task Rhwp_converts_between_hwpx_and_hwp()
{
diff --git a/tests/Filee.Engines.Tests/EbookTests.cs b/tests/Filee.Engines.Tests/EbookTests.cs
index f8339011..48bcbd0a 100644
--- a/tests/Filee.Engines.Tests/EbookTests.cs
+++ b/tests/Filee.Engines.Tests/EbookTests.cs
@@ -170,6 +170,11 @@ public class EbookTests(EngineFixture fx) : IClassFixture<EngineFixture>
Assert.Contains("| 이름 | 값 |", markdown);
var picture = System.Text.RegularExpressions.Regex.Match(markdown, @"!\[\]\(<([^>]+)>\)").Groups[1].Value;
Assert.True(File.Exists(Path.Combine(Path.GetDirectoryName(md)!, Uri.UnescapeDataString(picture))));
+
+ var textOnly = await fx.ConvertAsync([epub], new Preset { TargetFormat = "md", Document = { LeaveOutPictures = true } });
+ var withoutPictures = await File.ReadAllTextAsync(textOnly.Outputs.Single(), TestContext.Current.CancellationToken);
+ Assert.Contains("# 첫 번째 장", withoutPictures);
+ Assert.DoesNotContain("![", withoutPictures);
}
[Fact]
diff --git a/tests/Filee.Engines.Tests/PandocMarkupTests.cs b/tests/Filee.Engines.Tests/PandocMarkupTests.cs
index 3f4da2ee..482ae154 100644
--- a/tests/Filee.Engines.Tests/PandocMarkupTests.cs
+++ b/tests/Filee.Engines.Tests/PandocMarkupTests.cs
@@ -182,6 +182,28 @@ public class PandocMarkupTests(EngineFixture fx) : IClassFixture<EngineFixture>
Assert.Contains("first item", HwpxAssert.Xml(hwpx).Value);
}
+ [Fact]
+ public async Task Docx_to_markdown_extracts_the_pictures_or_leaves_them_out()
+ {
+ SkipUnlessInstalled();
+ var source = await WriteAsync("memo.md", "# Memo\n\nBefore the chart.\n\n![](chart.png)\n\nAfter the chart.\n");
+ EngineFixture.MakeImage(Path.GetDirectoryName(source)!, "chart.png", ImageMagick.MagickFormat.Png);
+ var docx = await ConvertAsync(source, "docx");
+ File.Delete(source);
+ Assert.Equal("pandoc", Assert.Single(fx.Catalog.CreatePlanner().Plan("docx", "md")!.Steps).Converter.Id);
+
+ var withPictures = await File.ReadAllTextAsync(await ConvertAsync(docx, "md"), TestContext.Current.CancellationToken);
+ Assert.Contains("memo_files", withPictures);
+
+ var job = await fx.ConvertAsync([docx], new Preset { TargetFormat = "md", Document = { LeaveOutPictures = true } });
+ Assert.True(job.State == JobState.Completed, string.Join("; ", job.Files.Select(f => $"{f.ErrorKey} {f.ErrorDetail}")));
+ var textOnly = await File.ReadAllTextAsync(job.Outputs.Single(), TestContext.Current.CancellationToken);
+ Assert.DoesNotContain("![", textOnly);
+ Assert.DoesNotContain("<img", textOnly);
+ Assert.Contains("Before the chart.", textOnly);
+ Assert.Contains("After the chart.", textOnly);
+ }
+
[Fact]
public async Task Latex_to_markdown_epub_and_back()
{
diff --git a/tests/Filee.Engines.Tests/PdfReaderTests.cs b/tests/Filee.Engines.Tests/PdfReaderTests.cs
index 8a48714e..125ba028 100644
--- a/tests/Filee.Engines.Tests/PdfReaderTests.cs
+++ b/tests/Filee.Engines.Tests/PdfReaderTests.cs
@@ -1,9 +1,11 @@
-// PDF → DOCX / HWPX / TXT with the built-in PDF reader (PdfPig): paragraphs in reading order (two-column pages
-// too), headings from font sizes, bold / italic / colour, links, pictures (JPEG kept as it is), repeated headers and
-// footers left out, scanned pages as page pictures, and a clear error for password-protected files.
+// PDF → DOCX / HWPX / TXT / Markdown with the built-in PDF reader (PdfPig): paragraphs in reading order (two-column
+// pages too), headings from font sizes, bold / italic / colour, links, pictures (JPEG kept as it is; next to a
+// Markdown file in "<name>_files"), repeated headers, footers, page numbers and logos left out, scanned pages as page
+// pictures, and a clear error for password-protected files.
// The test PDFs use the standard 14 fonts, so no installed font is needed (only the Korean test embeds one, if any).
using System.IO.Compression;
+using System.Text.RegularExpressions;
using Filee.Core.Conversion;
using Filee.Core.Presets;
using Filee.Engines.Hwp.Hwpx;
@@ -225,6 +227,108 @@ public class PdfReaderTests(EngineFixture fx) : IClassFixture<EngineFixture>
HwpxAssert.RenderWithRhwp(fx, hwpx, "pdf-report");
}
+ /// <summary>Picture links of a Markdown file, as written by MarkdownWriter: <c>![](&lt;report_files/img0001.jpg&gt;)</c>.</summary>
+ private static List<string> PictureLinks(string markdown) =>
+ [.. Regex.Matches(markdown, @"!\[\]\(<([^>]+)>\)").Select(m => m.Groups[1].Value)];
+
+ [Fact]
+ public async Task Pdf_to_markdown_saves_the_pictures_next_to_it()
+ {
+ Assert.Equal("pdf-text", Assert.Single(fx.Catalog.CreatePlanner().Plan("pdf", "md")!.Steps).Converter.Id);
+ var dir = fx.NewFolder();
+ var path = Report(dir);
+
+ var md = await ConvertAsync(path, "md");
+
+ Assert.Equal(Path.Combine(dir, "report.md"), md);
+ var markdown = await File.ReadAllTextAsync(md, TestContext.Current.CancellationToken);
+ Assert.StartsWith("# Annual Report 2026\n\n## 1. Introduction\n\n" + First + "\n\n", markdown, StringComparison.Ordinal);
+ Assert.Contains("## 2. Details\n\n" + Second, markdown);
+ Assert.Contains("**Warning**", markdown);
+ Assert.Contains("(<https://example.com/>)", markdown);
+ // No running header, footer or page number; no quote marks from the PDF's indents.
+ Assert.DoesNotContain("Quarterly", markdown);
+ Assert.DoesNotContain("Page", markdown);
+ Assert.DoesNotContain("> ", markdown);
+
+ // The pictures are files in "report_files", linked relatively; the JPEG is the PDF's own.
+ var links = PictureLinks(markdown);
+ Assert.Equal(["report_files/img0001.jpg", "report_files/img0002.png"], links);
+ Assert.Equal(await File.ReadAllBytesAsync(Path.Combine(dir, "photo.jpg"), TestContext.Current.CancellationToken),
+ await File.ReadAllBytesAsync(Path.Combine(dir, "report_files", "img0001.jpg"), TestContext.Current.CancellationToken));
+ Assert.True(File.Exists(Path.Combine(dir, "report_files", "img0002.png")));
+
+ // Converted again: a new Markdown file gets a new folder instead of writing into the first one.
+ var again = await ConvertAsync(path, "md");
+ Assert.Equal(Path.Combine(dir, "report (2).md"), again);
+ var second = PictureLinks(await File.ReadAllTextAsync(again, TestContext.Current.CancellationToken));
+ Assert.Equal(["report_files%20%282%29/img0001.jpg", "report_files%20%282%29/img0002.png"], second);
+ Assert.All(second, link => Assert.True(File.Exists(Path.Combine(dir, Uri.UnescapeDataString(link)))));
+ }
+
+ [Fact]
+ public async Task Pdf_to_markdown_can_leave_out_the_pictures()
+ {
+ var dir = fx.NewFolder();
+ var path = Report(dir);
+
+ var job = await fx.ConvertAsync([path], new Preset { TargetFormat = "md", Document = { LeaveOutPictures = true } });
+
+ Assert.Equal(JobState.Completed, job.State);
+ var markdown = await File.ReadAllTextAsync(job.Outputs.Single(), TestContext.Current.CancellationToken);
+ Assert.Contains("# Annual Report 2026", markdown);
+ Assert.Contains(Second, markdown);
+ Assert.DoesNotContain("![", markdown);
+ Assert.Empty(Directory.GetDirectories(dir));
+ }
+
+ /// <summary>
+ /// Eight pages of a book: a running head per chapter (three and five pages), roman page numbers, a logo in the
+ /// corner of every page, a larger heading at the top of three pages and a photo on page 2.
+ /// </summary>
+ private static string Book(string folder)
+ {
+ var pdf = new PdfBuilder();
+ var logo = PdfBuilder.Photo(folder, "logo.png", MagickFormat.Png, 60, 30);
+ string[] roman = ["i", "ii", "iii", "iv", "v", "vi", "vii", "viii"];
+ for (var page = 1; page <= 8; page++)
+ {
+ pdf.NewPage();
+ var regular = pdf.Font();
+ pdf.Line(page <= 3 ? "Chapter One: Beginnings" : "Chapter Two: Results", 9, regular, 50, 30);
+ pdf.Picture(logo, 485, 15, 60, 30);
+ pdf.Line(roman[page - 1], 9, regular, 295, 815);
+ if (page <= 3)
+ pdf.Line("Overview", 16, pdf.Font(bold: true), 50, 75);
+ pdf.Paragraph($"Body text of page {page} goes on long enough to be a real paragraph of the book.", 11, regular, 50, 120, 495, 14);
+ if (page == 2)
+ pdf.Picture(PdfBuilder.Photo(folder, "photo.jpg", MagickFormat.Jpeg), 50, 200, 200, 120);
+ }
+ return pdf.Save(Path.Combine(folder, "book.pdf"));
+ }
+
+ [Fact]
+ public async Task Running_heads_per_chapter_roman_page_numbers_and_logos_are_left_out()
+ {
+ var dir = fx.NewFolder();
+
+ var markdown = await File.ReadAllTextAsync(await ConvertAsync(Book(dir), "md"), TestContext.Current.CancellationToken);
+
+ Assert.DoesNotContain("Chapter", markdown);
+ Assert.DoesNotMatch(new Regex("^(i|ii|iii|iv|v|vi|vii|viii)$", RegexOptions.Multiline), markdown);
+ // The heading at the top of three pages is larger than the body text: content, not a running head.
+ Assert.Equal(3, Regex.Matches(markdown, "^# Overview$", RegexOptions.Multiline).Count);
+ for (var page = 1; page <= 8; page++)
+ Assert.Contains($"Body text of page {page} ", markdown);
+ // Only the photo: the logo repeats in the corner of every page.
+ Assert.Equal(["book_files/img0001.jpg"], PictureLinks(markdown));
+
+ // The same for plain text (no pictures there anyway).
+ var text = await File.ReadAllTextAsync(await ConvertAsync(Path.Combine(dir, "book.pdf"), "txt"), TestContext.Current.CancellationToken);
+ Assert.DoesNotContain("Chapter", text);
+ Assert.StartsWith("Overview\r\n\r\nBody text of page 1 ", text.TrimStart(''), StringComparison.Ordinal);
+ }
+
/// <summary>Hangul needs an embedded font; the test uses Malgun Gothic when the system has it.</summary>
[Fact]
public async Task Korean_lines_join_into_one_paragraph()