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.
C# audio-converteravaloniabatch-conversionconvertercsharpdocument-converterdocx-to-pdfdotnetdrag-and-dropfile-conversionfile-converterheic-converterhwphwpximage-converterlinuxmacospdf-convertervideo-converterwindows
PDF to DOCX keeps tabbed rows and line breaks (#38)
KnifeLemonb5686779a009
diff --git a/src/Filee.Engines/Pdf/PdfDocumentReader.Layout.cs b/src/Filee.Engines/Pdf/PdfDocumentReader.Layout.csindex 84bbc727..5262ab51 100644--- a/src/Filee.Engines/Pdf/PdfDocumentReader.Layout.cs+++ b/src/Filee.Engines/Pdf/PdfDocumentReader.Layout.cs@@ -52,8 +52,9 @@ internal sealed partial class PdfDocumentReadervar space = gaps.Count > 0 ? Math.Max(0.5, Median(gaps.Where(g => g > 0))) : 3;var lines = new List<TextLine>();- foreach (var row in rows)+ for (var r = 0; r < rows.Count; r++){+ var row = rows[r];var current = new List<TextWord> { row[0] };for (var i = 1; i < row.Count; i++){@@ -61,16 +62,81 @@ internal sealed partial class PdfDocumentReadervar size = Math.Min(row[i].Size, row[i - 1].Size);if (gap > Math.Max(5 * space, 1.5 * size)){- lines.Add(new TextLine(current));+ lines.Add(new TextLine(current, r));current = [];}current.Add(row[i]);}- lines.Add(new TextLine(current));+ lines.Add(new TextLine(current, r));}return lines;}+ /// <summary>+ /// Joins the parts of a split row again, with a tab between them, where no column gutter lies between the parts+ /// and the gap is a tab: after a list number ("1."), wider than a column gutter with a ragged line end (6 em), or+ /// at the same place as a tab in a row right above or below (the value column of a form, whatever the label's+ /// length). "1. RFP Published 08/14/2026" stays one row instead of three paragraphs. Null when no row changes.+ /// </summary>+ private static List<TextLine>? JoinTabbedRows(List<TextLine> lines, List<Item> items)+ {+ var rows = lines.GroupBy(l => l.Row).Select(g => g.ToList()).ToList();+ if (items.Count == 0 || rows.All(r => r.Count == 1))+ return null;+ var gutters = Gutters(items, items.Min(i => i.Left), items.Max(i => i.Right));++ // Gaps that may be tabs: (row, index of the part after the gap, where that part starts).+ var candidates = new List<(int Row, int Part, double X)>();+ var tabs = new HashSet<(int Row, int Part)>();+ foreach (var row in rows)+ {+ for (var p = 1; p < row.Count; p++)+ {+ var (before, after) = (row[p - 1], row[p]);+ if (gutters.Any(g => g.Start >= before.Right - 2 && g.End <= after.Left + 2))+ continue;+ candidates.Add((before.Row, p, after.Left));+ var number = before.Words.Count == 1 && ListStart.IsMatch(before.Words[0].Text);+ if (number || after.Left - before.Right > 6 * Math.Max(before.Size, after.Size))+ tabs.Add((before.Row, p));+ }+ }+ if (tabs.Count == 0)+ return null;+ for (var grown = true; grown;)+ {+ grown = false;+ foreach (var (row, part, x) in candidates)+ {+ if (!tabs.Contains((row, part)) && candidates.Any(c => tabs.Contains((c.Row, c.Part)) && Math.Abs(c.Row - row) <= 2 && Math.Abs(c.X - x) <= 1.5))+ grown |= tabs.Add((row, part));+ }+ }++ var result = new List<TextLine>();+ foreach (var row in rows)+ {+ var current = row[0];+ for (var p = 1; p < row.Count; p++)+ {+ if (tabs.Contains((current.Row, p)))+ {+ var joined = new TextLine([.. current.Words, .. row[p].Words], current.Row);+ joined.Tabs.AddRange(current.Tabs);+ joined.Tabs.Add(current.Words.Count);+ current = joined;+ }+ else+ {+ result.Add(current);+ current = row[p];+ }+ }+ result.Add(current);+ }+ return result;+ }+// ───────────────────────── Paragraphs ─────────────────────────/// <summary>@@ -87,7 +153,13 @@ internal sealed partial class PdfDocumentReadervar bestDistance = double.MaxValue;foreach (var item in items){+ if (line.Tabs.Count > 0)+ break; // a tabbed row starts its own paragraphvar last = item.Lines[^1];+ // A tabbed row continues only with text under its last part (the wrapped text of "1. Text …").+ var head = item.Lines[0];+ if (head.Tabs.Count > 0 && Math.Abs(line.Left - head.Words[head.Tabs[^1]].Left) > 0.5 * line.Size)+ continue;var distance = last.Baseline - line.Baseline;var size = Math.Max(last.Size, line.Size);if (distance <= 0 || distance > 1.9 * size || Math.Abs(last.Size - line.Size) > 0.2 * size)@@ -124,7 +196,7 @@ internal sealed partial class PdfDocumentReader// First-line indent: this line starts further right than the paragraph's other lines.var bodyLeft = item.Lines.Count > 1 ? item.Lines.Skip(1).Min(l => l.Left) : last.Left;- var listItem = ListStart.IsMatch(item.Lines[0].Words[0].Text);+ var listItem = ListStart.IsMatch(item.Lines[0].Words[0].Text) || item.Lines[0].Tabs.Count > 0;if (line.Left > bodyLeft + 0.8 * em && !listItem && (item.Lines.Count > 1 || line.Left > last.Left + 0.8 * em))return true;diff --git a/src/Filee.Engines/Pdf/PdfDocumentReader.cs b/src/Filee.Engines/Pdf/PdfDocumentReader.csindex 39d4a1fa..4703e760 100644--- a/src/Filee.Engines/Pdf/PdfDocumentReader.cs+++ b/src/Filee.Engines/Pdf/PdfDocumentReader.cs@@ -6,6 +6,10 @@// 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.//+// 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+// line break.+//// Not converted: tables (their cells come out as paragraphs in reading order), vector drawings on text pages,// annotations other than links, form fields.@@ -90,9 +94,16 @@ internal sealed partial class PdfDocumentReaderprivate sealed record TextWord(string Text, double Left, double Right, double Top, double Bottom, double Baseline, double Size, HCharFormat Format, string? Link);/// <summary>A text line (or the part of it in one column).</summary>- private sealed class TextLine(List<TextWord> words)+ private sealed class TextLine(List<TextWord> words, int row = 0){public List<TextWord> Words { get; } = words;++ /// <summary>The row of the page the line is on: the parts of a line split at wide gaps share it.</summary>+ public int Row { get; } = row;++ /// <summary>Indexes of the words a tab leads to (the start of each part after the first of a tabbed row).</summary>+ public List<int> Tabs { get; } = [];+public double Left => Words[0].Left;public double Right => Words[^1].Right;public double Top => Words.Max(w => w.Top);@@ -215,7 +226,11 @@ internal sealed partial class PdfDocumentReaderreturn content;}- content.Items = Paragraphs(Lines(words));+ var lines = Lines(words);+ var items = Paragraphs(lines);+ if (JoinTabbedRows(lines, items) is { } joined)+ items = Paragraphs(joined);+ content.Items = items;if (!_textOnly)content.Items.AddRange(Pictures(page, content, crop));return content;@@ -599,11 +614,16 @@ internal sealed partial class PdfDocumentReaderfirstLine = Hwp(first);}+ // A tabbed row: a left tab stop where each part starts in the PDF.+ var tabs = item.Lines.SelectMany(l => l.Tabs.Select(t => Hwp(l.Words[t].Left - item.ContainerLeft))).Distinct().Order()+ .Select(position => new HTabStop(position, HTabKind.Left, "NONE")).ToList();+var pitch = item.Lines.Count >= 2 ? Pitch(item) : size * lineRatio;paragraph.Format = new HParaFormat(Align: align,Left: left,FirstLine: firstLine,+ Tabs: tabs.Count > 0 ? tabs : null,Before: SpaceBefore(item, previous, lineRatio),After: 0,// "At least" the PDF's line distance: close to the original and never cuts off a larger font.@@ -629,7 +649,10 @@ internal sealed partial class PdfDocumentReaderreturn extra > 1 ? Hwp(Math.Min(extra, 72)) : 0;}- /// <summary>Words joined into runs of equal formatting; line ends become spaces (not inside CJK text or after a hyphen).</summary>+ /// <summary>+ /// Words joined into runs of equal formatting; line ends become spaces (not inside CJK text or after a hyphen), or+ /// line breaks where the line ended early on purpose. Tabs of a tabbed row stay tabs.+ /// </summary>private static void Runs(Item item, List<HInline> output){var pieces = new List<(string Text, HCharFormat Format, string? Link)>();@@ -643,7 +666,11 @@ internal sealed partial class PdfDocumentReaderif (pieces.Count > 0){var (previousText, previousFormat, previousLink) = pieces[^1];- if (w > 0)+ if (w > 0 && line.Tabs.Contains(w))+ {+ pieces.Add(("\t", word.Format, null));+ }+ else if (w > 0){pieces[^1] = (previousText + " ", previousFormat, previousLink);}@@ -651,6 +678,10 @@ internal sealed partial class PdfDocumentReader{pieces[^1] = (previousText[..^1], previousFormat, previousLink); // hyphenated at the line end}+ else if (EndedEarly(item, l))+ {+ pieces.Add(("\n", word.Format, null));+ }else if (!(IsCjk(previousText[^1]) || IsCjk(text[0]))){pieces[^1] = (previousText + " ", previousFormat, previousLink);@@ -663,6 +694,12 @@ internal sealed partial class PdfDocumentReaderHLink? link = null;foreach (var group in Merge(pieces)){+ if (group.Text is "\t" or "\n")+ {+ link = null;+ output.Add(group.Text == "\t" ? new HTab(group.Format) : new HLineBreak(group.Format));+ continue;+ }var text = new HText(group.Text, group.Format);if (group.Link is null){@@ -681,6 +718,26 @@ internal sealed partial class PdfDocumentReader}}+ /// <summary>+ /// Whether line <paramref name="l"/> - 1 of the item ended although the first word of line <paramref name="l"/>+ /// would have fitted after it: a line break the author made (an address, a poem). Wrapped text never ends like+ /// that within its own width; past it only when the paragraph is clearly narrower than its column (an indented+ /// block of short lines), not a quote with a right indent.+ /// </summary>+ private static bool EndedEarly(Item item, int l)+ {+ var previous = item.Lines[l - 1];+ var line = item.Lines[l];+ if (previous.Words[^1].Text.EndsWith('-'))+ return false;+ var em = line.Size;+ var end = previous.Right + 0.3 * em + (line.Words[0].Right - line.Words[0].Left);+ if (end < item.Right - 0.5 * em)+ return true;+ var column = item.ContainerRight - item.ContainerLeft;+ return end < item.ContainerRight - 0.5 * em && item.ContainerRight - item.Right > 0.25 * column;+ }+private static IEnumerable<(string Text, HCharFormat Format, string? Link)> Merge(List<(string Text, HCharFormat Format, string? Link)> pieces){var sb = new StringBuilder();@@ -689,7 +746,7 @@ internal sealed partial class PdfDocumentReadervar open = false;foreach (var piece in pieces){- if (open && (piece.Format != format || piece.Link != link))+ if (open && (piece.Format != format || piece.Link != link || piece.Text is "\t" or "\n" || sb.ToString() is "\t" or "\n")){yield return (sb.ToString(), format, link);sb.Clear();@@ -698,7 +755,7 @@ internal sealed partial class PdfDocumentReader(format, link, open) = (piece.Format, piece.Link, true);}if (open)- yield return (sb.ToString().TrimEnd(), format, link);+ yield return (sb.ToString() is "\t" or "\n" ? sb.ToString() : sb.ToString().TrimEnd(), format, link);}/// <summary>Chinese and Japanese text has no spaces between words (Korean does).</summary>@@ -720,7 +777,13 @@ internal sealed partial class PdfDocumentReadervar sb = new StringBuilder();foreach (var paragraph in document.Sections.SelectMany(s => s.Blocks).OfType<HParagraph>()){- var text = string.Concat(paragraph.Inlines.SelectMany(i => i is HLink link ? link.Content : [i]).OfType<HText>().Select(t => t.Text)).Trim();+ var text = string.Concat(paragraph.Inlines.SelectMany(i => i is HLink link ? link.Content : [i]).Select(i => i switch+ {+ HText t => t.Text,+ HTab => "\t",+ HLineBreak => "\r\n",+ _ => "",+ })).Trim();if (text.Length == 0)continue;if (sb.Length > 0)diff --git a/tests/Filee.Engines.Tests/PdfReaderTests.cs b/tests/Filee.Engines.Tests/PdfReaderTests.csindex 5dc94195..8a48714e 100644--- a/tests/Filee.Engines.Tests/PdfReaderTests.cs+++ b/tests/Filee.Engines.Tests/PdfReaderTests.cs@@ -128,6 +128,67 @@ public class PdfReaderTests(EngineFixture fx) : IClassFixture<EngineFixture>Assert.Contains(Text("Left first") + "\r\n\r\n" + Text("Left second"), text);}+ /// <summary>+ /// Page 5 of the RFP in #38: a schedule laid out with tab stops, an address block of short lines, and a form whose+ /// labels are short and long.+ /// </summary>+ private static string Schedule(string folder)+ {+ var pdf = new PdfBuilder().NewPage(612, 792);+ var body = pdf.Font();+ pdf.Paragraph("E. PROPOSED SCHEDULE OF ACTIVITIES: the dates below may change. This paragraph is long enough to wrap, so the page has a full text width.",+ 12, body, 54, 60, 500, 15);+ string[][] rows = [["1.", "RFP Published", "08/14/2026"], ["2.", "Proposal Submission", "10/16/2026"], ["3.", "Proposal Selection", "10/19/2026"]];+ for (var r = 0; r < rows.Length; r++)+ {+ pdf.Line(rows[r][0], 12, body, 76.5, 110 + r * 14.6);+ pdf.Line(rows[r][1], 12, body, 108, 110 + r * 14.6);+ pdf.Line(rows[r][2], 12, body, 432, 110 + r * 14.6);+ }+ pdf.Paragraph("F. INQUIRIES: Send all inquiries (transmittal by E-Mail preferred) to the address below, which is the only one.", 12, body, 54, 170, 500, 15);+ string[] address = ["WESTAR", "1880 Willamette Falls Drive, Ste. 200E", "West Linn, Oregon 97068", "Attn: Jeffrey P. Gabler"];+ for (var l = 0; l < address.Length; l++)+ pdf.Line(address[l], 12, body, 144, 215 + l * 14.6);+ string[][] form = [["Name:", "JEFFREY P. GABLER"], ["Organization:", "WESTAR COUNCIL"], ["Phone:", "503-657-4838"]];+ for (var r = 0; r < form.Length; r++)+ {+ pdf.Line(form[r][0], 11, body, 72, 300 + r * 14);+ pdf.Line(form[r][1], 11, body, 176, 300 + r * 14);+ }+ return pdf.Save(Path.Combine(folder, "schedule.pdf"));+ }++ /// <summary>Text with tabs as \t and line breaks as \n.</summary>+ private static string Shown(HParagraph paragraph) => string.Concat(paragraph.Inlines.SelectMany(i => i is HLink link ? link.Content : [i])+ .Select(i => i switch { HText t => t.Text, HTab => "\t", HLineBreak => "\n", _ => "" }));++ [Fact]+ public async Task Tabbed_rows_and_line_breaks_are_kept()+ {+ var path = Schedule(fx.NewFolder());++ var docx = await ConvertAsync(path, "docx");++ ValidPackage(docx);+ var paragraphs = Paragraphs(ReadBack(docx).Sections.SelectMany(s => s.Blocks)).Where(p => TextOf(p).Length > 0).ToList();+ Assert.Equal([+ "1.\tRFP Published\t08/14/2026", "2.\tProposal Submission\t10/16/2026", "3.\tProposal Selection\t10/19/2026",+ "1880 Willamette Falls Drive, Ste. 200E\nWest Linn, Oregon 97068",+ "Name:\tJEFFREY P. GABLER", "Organization:\tWESTAR COUNCIL", "Phone:\t503-657-4838",+ ], paragraphs.Select(Shown).Where(t => t.Contains('\t') || t.Contains('\n')));+ // The tab stops sit where the parts start in the PDF, from the text's left edge (54 pt): 108 - 54 and 432 - 54.+ var row = paragraphs.Single(p => Shown(p).StartsWith("1.\t", StringComparison.Ordinal));+ Assert.Equal([5400, 37800], row.Format.Tabs!.Select(t => t.Position));+ Assert.All(row.Format.Tabs!, t => Assert.Equal(HTabKind.Left, t.Kind));+ // The street and the town stay apart; the short lines around them are paragraphs of their own.+ Assert.Contains(paragraphs, p => Shown(p) == "WESTAR");+ Assert.Contains(paragraphs, p => Shown(p) == "Attn: Jeffrey P. Gabler");++ var text = await File.ReadAllTextAsync(await ConvertAsync(path, "txt"), TestContext.Current.CancellationToken);+ Assert.Contains("1.\tRFP Published\t08/14/2026\r\n\r\n2.\tProposal Submission", text);+ Assert.Contains("Ste. 200E\r\nWest Linn", text);+ }+[Fact]public async Task Scanned_pages_become_page_pictures(){