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.

OFD: real e-invoices fit their page, show their seals and keep list rows level

KnifeLemon63cfdbf1a67c
diff --git a/docs/ENGINES.md b/docs/ENGINES.md
index b351bcd6..9f630959 100644
--- a/docs/ENGINES.md
+++ b/docs/ENGINES.md
@@ -547,25 +547,45 @@ sits on the office donut (settings schema 27 teaches existing donuts `.ofd`).
drawing objects, page blocks nested 32 deep. DeltaX / DeltaY "g n d" repeats never yield more values than the
text has characters.
- **Encryption**: a package with an `Encryptions.xml` (GM/T 0099) or encryption entries in OFD.xml is refused with a
- clear message; nothing is decrypted. Parts that are not XML (encrypted or damaged) fail the same way. Signatures
- (`Signs/`) are ignored, so the seal images stored inside signed data do not appear.
+ clear message; nothing is decrypted. Parts that are not XML (encrypted or damaged) fail the same way.
- **Text**: TextObjects with their Boundary, CTM (scale, also of the font size), Size in millimetres, TextCode X / Y
- (missing ones continue where the previous code ended) and DeltaX advances; DeltaY runs are vertical text. Fonts
- from the resource files, with common Chinese names written in English (宋体 → SimSun, 黑体 → SimHei, 楷体 → KaiTi,
- 仿宋 → FangSong, 微软雅黑 → Microsoft YaHei, …) so Word and LibreOffice find them on any system; bold from
- `Weight` ≥ 600 or the font, italic, colour from the object (FillColor element or attribute; RGB, grey, CMYK,
+ (missing ones continue where the previous code ended) and DeltaX advances; DeltaY alone moving the characters is
+ vertical text. A DeltaX list shorter than the text goes on with its last value while the characters are as wide
+ (a title with one advance for all its characters); a step back with DeltaX or down with DeltaY inside one TextCode
+ starts a new line, kept with a line break (the four lines of a VAT invoice's 密码区 cipher text are one TextCode).
+ Fonts from the resource files, with common Chinese names written in English (宋体 → SimSun, 黑体 → SimHei,
+ 楷体 → KaiTi, 仿宋 → FangSong, 微软雅黑 → Microsoft YaHei, …) so Word and LibreOffice find them on any system; bold
+ from `Weight` ≥ 600 or the font, italic, colour from the object (FillColor element or attribute; RGB, grey, CMYK,
decimal or #hex channels), its DrawParam or the layer's DrawParam (tax invoices colour the template that way),
following `Relative` chains. Invisible objects (`Visible="false"`) are left out.
- **Templates**: the template pages a page names are read first, so an invoice's labels (发票号码:, 名称:) and its
values come out together. In template content, single characters stacked in one column (购买方信息, 备注) or a
- pair spread over a line (合 计) become one word.
+ pair spread over a line (合 计) become one word, once the page's own text is there: a pair with a value between
+ (共 4 页 of a sales list) stays apart.
+- **Annotations** (Annots): the text and pictures of each annotation's appearance, placed from its boundary (a stamp
+ drawn as a picture, a note). Hidden annotations and their paths (highlights, underlines) are left out.
+- **Seals** (`OfdReader.Seals.cs`): an e-invoice's or a contract's seal is stored in its signature
+ (`Signs/Sign_n/SignedValue.dat`, GM/T 0031 SES_Signature). The seal picture in it is shown where the signature's
+ StampAnnot puts it, floating in front of the text. PNG, JPEG, GIF and BMP are kept; a seal that is a small OFD
+ package of its own (the red oval of 全国统一发票监制章 with its characters set round the edge) is drawn with
+ SkiaSharp at 12 pixels per mm on a transparent PNG: text per character with its CTM rotation, stroked and filled
+ paths (lines, Béziers, arcs) and pictures. The DER is walked with every length checked against what is left,
+ nesting and the element count capped; a SignedValue is read up to 4 MB, a seal package unpacks to 16 MB, at most
+ 64 signatures with 16 stamps each. The signature is not verified: what shows is the picture the file carries.
- **Layout** (`OfdReader.Layout.cs`): fragments on one baseline form a line, in reading order top to bottom and
left to right; a line that ran to the right edge from at least half the measure continues in the next one
(justified, first-line indent kept, no space between Chinese lines). Wide gaps (1.5 em) become tabs with left
tab stops where each part starts, so an invoice's item rows keep their columns; a line under such a row whose
parts start in its columns and hold no amounts is the wrapped end of its cells and follows after a line break in
the same paragraph. Centred and right-aligned lines, left indents and vertical distances (space before) follow
- the page; page size per page (a new section when it changes), margins from what is drawn.
+ the page; page size per page (a new section when it changes), margins from what is drawn. Line distances are
+ exact where the largest text fits ("at least" grows each line to the font's own height in Word and LibreOffice,
+ ~1.4 em for KaiTi, and a full 210 × 140 mm invoice ran onto a second page); a one-line paragraph closer to the one
+ above than 1.2 sizes gets the distance between them. A block that starts above the end of the one before (the
+ invoice number beside the title) is pushed down, and the next gaps take that back, so the frame stays at its
+ place. A table gets its distance from the block above through a 1 pt paragraph, and is `Tight` in HWPX: no 5 mm
+ under it and no empty line in the paragraph that holds it. The first block's distance from the top margin is an
+ empty line of that height (rhwp draws no space before at the top of a page).
- **Ruled tables** (`OfdReader.Tables.cs`): the approach of the PDF reader in millimetres. PathObjects
(AbbreviatedData M/S/L/Q/B/A/C, with Boundary, CTM, line width and stroke colour from the object or its
DrawParams) give stroked straight rules and thin filled rectangles; joined rules that meet form grids, and a grid
@@ -573,16 +593,25 @@ sits on the office donut (settings schema 27 teaches existing donuts `.ofd`).
column widths and row heights, borders in the drawn colour and shading. Text goes into the cell of its first
character (widths without DeltaX are estimated) and is laid out like the page, with exact line spacing so the
rows keep their heights. The frame of an e-invoice becomes one table: buyer and seller blocks, the item list
- (one cell with tabbed rows: the invoice draws no rules between item columns), totals and remarks.
+ (one cell with tabbed rows: the invoice draws no rules between item columns), totals and remarks. A cell with one
+ paragraph about as far from its top as from its bottom is centred; any other keeps its text's distance from the
+ top as the cell's top padding (space before a cell's first paragraph is not drawn by every renderer), and only
+ lines at about single spacing (1.6 sizes) are one paragraph. So the columns of a sales list (销货清单: rules only
+ between the columns, each column one cell with all its rows) keep their rows level, the 小计 at the bottom of 序号
+ beside its amount.
- **Pictures**: ImageObjects (MultiMedia of type Image) with the box from their CTM. PNG, JPEG, GIF and BMP are
kept as they are (the format comes from the bytes, not the name), TIFF and JPEG 2000 are converted to PNG
(ImageMagick, at most 100 megapixels), anything else (JBIG2) is left out. A picture alone in its band of the page
becomes a paragraph; one beside or over text (a QR code next to the title, a seal on a table) floats at its place
on the paper, in front of the text.
-Not converted: annotations (Annots), signatures and their seals, embedded fonts (the font name is kept), composite
-objects and other vector drawings, attachments, more than the first document of a package, tables without rules
-(their text stays in tabbed rows), clipping. Two text blocks side by side without rules share their lines.
+Not converted: signature checks (a seal shows whether or not its signature is valid), seal pictures in SVG,
+embedded fonts (the font name is kept), composite objects and other vector drawings (the ⊗ before an invoice's
+amount in words), attachments, more than the first document of a package, tables without rules (their text stays
+in tabbed rows), clipping. Two text blocks side by side without rules share their lines. Renderers place text
+differently inside an exact line (Word and LibreOffice at its foot, 한글 and rhwp at its head), so in the rhwp PDF
+text sits up to 0.2 sizes higher than on the page. LibreOffice adds cell borders to row heights: the DOCX of a
+full 140 mm invoice opened there puts its last line on a second page (rhwp's PDF keeps it on one).
## PDF → PPTX
diff --git a/src/Filee.Engines/Hwp/Hwpx/Docx/DocxWriter.Body.cs b/src/Filee.Engines/Hwp/Hwpx/Docx/DocxWriter.Body.cs
index 3e706a88..02b272b6 100644
--- a/src/Filee.Engines/Hwp/Hwpx/Docx/DocxWriter.Body.cs
+++ b/src/Filee.Engines/Hwp/Hwpx/Docx/DocxWriter.Body.cs
@@ -600,6 +600,8 @@ internal sealed partial class DocxWriter
}
if (Hex(cell.Fill) is { } fill)
sb.Append($"<w:shd w:val=\"clear\" w:color=\"auto\" w:fill=\"{fill}\"/>");
+ if (cell.CellMargin is { } m)
+ sb.Append($"<w:tcMar><w:top w:w=\"{Number(Twips(m.Top))}\" w:type=\"dxa\"/><w:left w:w=\"{Number(Twips(m.Left))}\" w:type=\"dxa\"/><w:bottom w:w=\"{Number(Twips(m.Bottom))}\" w:type=\"dxa\"/><w:right w:w=\"{Number(Twips(m.Right))}\" w:type=\"dxa\"/></w:tcMar>");
if (cell.VerticalAlign != HVerticalAlign.Top)
sb.Append($"<w:vAlign w:val=\"{(cell.VerticalAlign == HVerticalAlign.Center ? "center" : "bottom")}\"/>");
sb.Append("</w:tcPr>").Append(content);
diff --git a/src/Filee.Engines/Hwp/Hwpx/HwpxModel.cs b/src/Filee.Engines/Hwp/Hwpx/HwpxModel.cs
index 1c06db10..440de58a 100644
--- a/src/Filee.Engines/Hwp/Hwpx/HwpxModel.cs
+++ b/src/Filee.Engines/Hwp/Hwpx/HwpxModel.cs
@@ -130,6 +130,13 @@ internal sealed class HTable : HBlock
/// <summary>The table starts a new page (a page break set in Excel).</summary>
public bool PageBreakBefore { get; set; }
+ /// <summary>
+ /// The table takes no more height than its rows (fixed layouts: OFD, whose next paragraph has its own distance).
+ /// In HWPX it gets no 5 mm space under it and the paragraph holding it no empty line of its own, so a full page
+ /// does not run over.
+ /// </summary>
+ public bool Tight { get; set; }
+
public List<HBlock> Caption { get; } = [];
}
diff --git a/src/Filee.Engines/Hwp/Hwpx/HwpxWriter.Body.cs b/src/Filee.Engines/Hwp/Hwpx/HwpxWriter.Body.cs
index d1abceb8..c30413c3 100644
--- a/src/Filee.Engines/Hwp/Hwpx/HwpxWriter.Body.cs
+++ b/src/Filee.Engines/Hwp/Hwpx/HwpxWriter.Body.cs
@@ -300,7 +300,7 @@ internal sealed partial class HwpxWriter
_ => "LEFT",
};
sb.Append($"<hp:pos treatAsChar=\"0\" affectLSpacing=\"0\" flowWithText=\"1\" allowOverlap=\"0\" holdAnchorAndSO=\"0\" vertRelTo=\"PARA\" horzRelTo=\"COLUMN\" vertAlign=\"TOP\" horzAlign=\"{horizontalAlign}\" vertOffset=\"0\" horzOffset=\"{(table.Align == HAlign.Left ? table.Indent : 0)}\"/>");
- sb.Append("<hp:outMargin left=\"0\" right=\"0\" top=\"0\" bottom=\"1417\"/>");
+ sb.Append($"<hp:outMargin left=\"0\" right=\"0\" top=\"0\" bottom=\"{(table.Tight ? 0 : 1417)}\"/>");
sb.Append($"<hp:inMargin left=\"{margin.Left}\" right=\"{margin.Right}\" top=\"{margin.Top}\" bottom=\"{margin.Bottom}\"/>");
var outerWidth = _width;
@@ -338,9 +338,14 @@ internal sealed partial class HwpxWriter
_width = outerWidth;
sb.Append("</hp:tbl>");
+ // The paragraph holding the table has a text line under it; a tight table's is 1 pt with no spacing.
+ var (paraPrId, charPrId) = table.Tight
+ ? (ParaPr(_base.ParaPrId, new HParaFormat(Before: 0, After: 0, LineSpacing: new HLineSpacing(HLineSpacingKind.Percent, 100)), null),
+ CharPr(_base.CharPrId, new HCharFormat(Size: 100)))
+ : (_base.ParaPrId, _base.CharPrId);
var runs = new RunBuilder();
- runs.Control(_base.CharPrId, sb.ToString(), isObject: true);
- var paragraph = $"<hp:p id=\"0\" paraPrIDRef=\"{_base.ParaPrId}\" styleIDRef=\"{_base.StyleId}\" pageBreak=\"{(table.PageBreakBefore ? 1 : 0)}\" columnBreak=\"0\" merged=\"0\">{leadingRun}{runs.Finish(_base.CharPrId, leadingRun is not null)}</hp:p>";
+ runs.Control(charPrId, sb.ToString(), isObject: true);
+ var paragraph = $"<hp:p id=\"0\" paraPrIDRef=\"{paraPrId}\" styleIDRef=\"{_base.StyleId}\" pageBreak=\"{(table.PageBreakBefore ? 1 : 0)}\" columnBreak=\"0\" merged=\"0\">{leadingRun}{runs.Finish(charPrId, leadingRun is not null)}</hp:p>";
return paragraph + string.Concat(table.Caption.Select(b => Block(b)));
}
diff --git a/src/Filee.Engines/Ofd/OfdPackage.cs b/src/Filee.Engines/Ofd/OfdPackage.cs
index fcd4b951..2e74863b 100644
--- a/src/Filee.Engines/Ofd/OfdPackage.cs
+++ b/src/Filee.Engines/Ofd/OfdPackage.cs
@@ -35,13 +35,24 @@ internal sealed class OfdPackage : IDisposable
private readonly ZipArchive _zip;
private readonly Dictionary<string, ZipArchiveEntry> _entries = new(StringComparer.OrdinalIgnoreCase);
+ private readonly long _maxTotal;
private long _read;
- public OfdPackage(string path)
+ public OfdPackage(string path) : this(() => ZipFile.OpenRead(path), MaxTotalBytes)
{
+ }
+
+ /// <summary>A package held in memory (the seal picture inside a signature), with its own limit on what it unpacks to.</summary>
+ public OfdPackage(byte[] bytes, long maxTotal) : this(() => new ZipArchive(new MemoryStream(bytes, writable: false), ZipArchiveMode.Read), maxTotal)
+ {
+ }
+
+ private OfdPackage(Func<ZipArchive> open, long maxTotal)
+ {
+ _maxTotal = Math.Min(maxTotal, MaxTotalBytes);
try
{
- _zip = ZipFile.OpenRead(path);
+ _zip = open();
}
catch (InvalidDataException ex)
{
@@ -138,8 +149,8 @@ internal sealed class OfdPackage : IDisposable
if (copy.Length + count > max)
return null;
_read += count;
- if (_read > MaxTotalBytes)
- throw new InvalidDataException($"The OFD package unpacks to more than {MaxTotalBytes / (1024 * 1024 * 1024)} GB; Filee does not read it.");
+ if (_read > _maxTotal)
+ throw new InvalidDataException($"The OFD package unpacks to more than {_maxTotal / (1024 * 1024)} MB; Filee does not read it.");
copy.Write(buffer, 0, count);
}
return copy.ToArray();
diff --git a/src/Filee.Engines/Ofd/OfdReader.Layout.cs b/src/Filee.Engines/Ofd/OfdReader.Layout.cs
index 2024522b..63f796e7 100644
--- a/src/Filee.Engines/Ofd/OfdReader.Layout.cs
+++ b/src/Filee.Engines/Ofd/OfdReader.Layout.cs
@@ -35,6 +35,9 @@ internal sealed partial class OfdReader
public double Right => Fragments.Max(f => f.Right);
public double LastBaseline => Fragments.Concat(Wrapped.Select(w => w.Fragment)).Max(f => f.Baseline + f.Run);
public bool Vertical => Fragments[0].Vertical;
+
+ /// <summary>Line distance of a paragraph of this one line when the line above leaves less than 1.2 sizes.</summary>
+ public double? Cap { get; set; }
}
/// <summary>A paragraph, a table or a picture at its place on the page (mm from the top).</summary>
@@ -60,7 +63,7 @@ internal sealed partial class OfdReader
var blocks = PageBlocks(page, left, page.Width - right, top);
// A table cannot start a page in every format: a tiny empty paragraph before it carries the page break.
if (blocks.Count == 0 || blocks[0] is HTable)
- blocks.Insert(0, new HParagraph { MarkFormat = new HCharFormat(Size: 100) });
+ blocks.Insert(0, Spacer());
if (!newSection && blocks[0] is HParagraph first)
first.PageBreakBefore = true;
section!.Blocks.AddRange(blocks);
@@ -105,13 +108,13 @@ internal sealed partial class OfdReader
var items = new List<Placed>();
foreach (var table in RuledTables(page, fragments))
items.Add(new Placed(table.Top, table.Bottom, Table: table));
- foreach (var paragraph in Paragraphs(Lines(fragments), containerLeft, containerRight))
+ foreach (var paragraph in FitLineHeights(Paragraphs(Lines(fragments), containerLeft, containerRight)))
items.Add(new Placed(TextTop(paragraph), TextBottom(paragraph), Lines: paragraph));
var floating = new List<HImage>();
foreach (var picture in page.Pictures.OrderBy(p => p.Top))
{
- if (Extract(picture.Part) is not { } file)
+ if ((picture.File ?? (picture.Part is { } part ? Extract(part) : null)) is not { } file)
continue;
var image = new HImage(file) { Width = Hwp(picture.Width), Height = Hwp(picture.Height) };
if (items.Any(i => i.Top < picture.Bottom - 0.5 && i.Bottom > picture.Top + 0.5))
@@ -125,13 +128,23 @@ internal sealed partial class OfdReader
}
}
+ // The blocks follow each other down the page; where one starts above the end of the one before (a title with
+ // the invoice number beside it) it is pushed down, and the next gaps take that back, so the rest of the page
+ // stays at its place.
var blocks = new List<HBlock>();
- var above = marginTop;
+ var flow = marginTop;
foreach (var item in items.OrderBy(i => i.Top))
{
- var before = Math.Clamp(item.Top - above, 0, 100);
+ var before = Math.Clamp(item.Top - flow, 0, 100);
if (item.Table is { } table)
{
+ // A table has no space before: a 1 pt paragraph carries the distance.
+ if (before > 0.5)
+ {
+ var spacer = Spacer();
+ spacer.Format = spacer.Format with { Before = Hwp(before - 0.35) };
+ blocks.Add(spacer);
+ }
blocks.Add(TableBlock(table, containerLeft));
}
else if (item.Image is { } image)
@@ -146,20 +159,41 @@ internal sealed partial class OfdReader
}
else
{
- blocks.Add(TextParagraph(item.Lines!, containerLeft, containerRight, Hwp(before)));
+ // Exact line distance where the largest text fits in it: "at least" grows each line to the font's own
+ // height in Word and LibreOffice (KaiTi: ~1.4 em), and a full invoice page ran over.
+ var lines = item.Lines!;
+ var exact = lines.Max(l => l.Size) <= LineHeight(lines) + 0.01;
+ blocks.Add(TextParagraph(lines, containerLeft, containerRight, Hwp(before), exact));
}
- above = Math.Max(above, item.Bottom);
+ flow += before + (item.Bottom - item.Top);
+ }
+
+ // The first block's distance from the top margin becomes the height of an empty line: space before the first
+ // paragraph of a page is not drawn by every renderer (rhwp leaves it out, and the page came out 3 mm high).
+ if (blocks.Count > 0 && blocks[0] is HParagraph first && first.Format.Before is > 0 and var top && top > Hwp(0.5))
+ {
+ var spacer = Spacer();
+ spacer.Format = spacer.Format with { LineSpacing = new HLineSpacing(HLineSpacingKind.Fixed, top) };
+ first.Format = first.Format with { Before = 0 };
+ blocks.Insert(0, spacer);
}
if (floating.Count > 0)
{
if (blocks.Count == 0 || blocks[0] is not HParagraph)
- blocks.Insert(0, new HParagraph { MarkFormat = new HCharFormat(Size: 100) });
+ blocks.Insert(0, Spacer());
((HParagraph)blocks[0]).Inlines.InsertRange(0, floating);
}
return blocks;
}
+ /// <summary>An empty 1 pt paragraph with no spacing: carries a page break before a table, or the floating pictures.</summary>
+ private static HParagraph Spacer() => new()
+ {
+ Format = new HParaFormat(Before: 0, After: 0, LineSpacing: new HLineSpacing(HLineSpacingKind.Percent, 100)),
+ MarkFormat = new HCharFormat(Size: 100),
+ };
+
/// <summary>The same text drawn twice at one place (fake bold, a label in both the template and the page) once.</summary>
private static List<Fragment> Deduplicated(List<Fragment> fragments)
{
@@ -230,15 +264,16 @@ internal sealed partial class OfdReader
/// <summary>
/// Lines into paragraphs: a line continues the paragraph above when that one filled the measure (ran to the
/// right edge from at least half-way), the size and line distance match and it starts no further right than the
- /// paragraph's body (the first line may be indented).
+ /// paragraph's body (the first line may be indented). Lines further apart than <paramref name="maxPitch"/> font
+ /// sizes stay paragraphs of their own.
/// </summary>
- private static List<List<Line>> Paragraphs(List<Line> lines, double containerLeft, double containerRight)
+ private static List<List<Line>> Paragraphs(List<Line> lines, double containerLeft, double containerRight, double maxPitch = 2.5)
{
var paragraphs = new List<List<Line>>();
foreach (var line in lines)
{
var current = paragraphs.LastOrDefault();
- if (current is not null && Continues(current, line, containerLeft, containerRight))
+ if (current is not null && Continues(current, line, containerLeft, containerRight, maxPitch))
current.Add(line);
else
paragraphs.Add([line]);
@@ -246,14 +281,19 @@ internal sealed partial class OfdReader
return paragraphs;
}
- private static bool Continues(List<Line> paragraph, Line line, double containerLeft, double containerRight)
+ private static bool Continues(List<Line> paragraph, Line line, double containerLeft, double containerRight, double maxPitch)
{
var last = paragraph[^1];
var size = last.Size;
if (last.Tabs.Count > 0 || line.Tabs.Count > 0 || last.Vertical || line.Vertical || Math.Abs(line.Size - size) > 0.15 * size)
return false;
var pitch = line.Baseline - last.Baseline;
- if (pitch < 0.9 * size || pitch > 2.5 * size || paragraph.Count > 1 && Math.Abs(pitch - (last.Baseline - paragraph[^2].Baseline)) > 0.25 * size)
+ if (pitch < 0.9 * size || pitch > maxPitch * size || paragraph.Count > 1 && Math.Abs(pitch - (last.Baseline - paragraph[^2].Baseline)) > 0.25 * size)
+ return false;
+ // A line its writer broke inside one TextCode (a block of cipher text) follows after a line break.
+ if (line.Fragments[0].Continued)
+ return line.Fragments.Count == 1 && Math.Abs(line.Left - last.Left) < 0.6 * size;
+ if (paragraph.Skip(1).Any(l => l.Fragments[0].Continued))
return false;
var body = paragraph.Count > 1 ? paragraph.Skip(1).Min(l => l.Left) : paragraph[0].Left;
if (last.Right < containerRight - 2.5 * size || last.Right - Math.Min(body, last.Left) < 0.5 * (containerRight - containerLeft))
@@ -268,10 +308,28 @@ internal sealed partial class OfdReader
var wrapped = lines[0].Wrapped.Select(w => w.Fragment.Baseline).Distinct().Count();
var pitch = lines.Count > 1 ? (lines[^1].Baseline - lines[0].Baseline) / (lines.Count - 1)
: wrapped > 0 ? (lines[0].LastBaseline - lines[0].Baseline) / wrapped
- : size * 1.2;
+ : lines[0].Cap ?? size * 1.2;
return Math.Clamp(pitch, size, size * 3);
}
+ /// <summary>
+ /// A one-line paragraph closer to the line above than 1.2 times its size (an invoice's label rows, 4.7 mm apart
+ /// with 4.2 mm numbers) gets a line distance that fits in between, else every such line pushes the rest down.
+ /// </summary>
+ private static List<List<Line>> FitLineHeights(List<List<Line>> paragraphs)
+ {
+ for (var i = 1; i < paragraphs.Count; i++)
+ {
+ var (above, line) = (paragraphs[i - 1][^1], paragraphs[i][0]);
+ if (paragraphs[i].Count > 1 || line.Wrapped.Count > 0 || line.Vertical || above.Vertical)
+ continue;
+ var room = line.Baseline - above.LastBaseline + 0.25 * (line.Size - above.Size);
+ if (room > 0 && room < 1.2 * line.Size)
+ line.Cap = room;
+ }
+ return paragraphs;
+ }
+
/// <summary>Top of a paragraph's first line box (Word puts the extra line distance above the text).</summary>
private static double TextTop(List<Line> lines) =>
lines[0].Vertical ? lines[0].Fragments[0].Top : lines[0].Baseline - (LineHeight(lines) - 0.25 * lines[0].Size);
@@ -292,8 +350,8 @@ internal sealed partial class OfdReader
align = HAlign.Center;
else if (lines.Count == 1 && !tabbed && rightGap < 1.5 && leftGap > width * 0.2)
align = HAlign.Right;
- else if (lines.Count > 1)
- align = HAlign.Justify;
+ else if (lines.Count > 1 && !lines.Skip(1).Any(l => l.Fragments[0].Continued))
+ align = HAlign.Justify; // not lines that end in a line break: Word would spread them
else
align = HAlign.Left;
@@ -358,6 +416,10 @@ internal sealed partial class OfdReader
if (gap > 0.5 * fragment.Size || gap > 0.2 * fragment.Size && !IsWide(previous.Text[^1]) && !IsWide(fragment.Text[0]))
Space();
}
+ else if (l > 0 && fragment.Continued)
+ {
+ pieces.Add(("\n", fragment.Format));
+ }
else if (l > 0 && pieces.Count > 0 && !IsWide(pieces[^1].Text[^1]) && !IsWide(fragment.Text[0]))
{
Space();
diff --git a/src/Filee.Engines/Ofd/OfdReader.Seals.cs b/src/Filee.Engines/Ofd/OfdReader.Seals.cs
new file mode 100644
index 00000000..a7b8f0ec
--- /dev/null
+++ b/src/Filee.Engines/Ofd/OfdReader.Seals.cs
@@ -0,0 +1,359 @@
+// Seals for OfdReader: an e-invoice's or a contract's seal is not drawn on the page but stored in its signature
+// (Signs/Sign_n/SignedValue.dat, GM/T 0031 SES_Signature, DER). The seal picture inside it — PNG, JPEG, GIF, BMP or a
+// small OFD package of its own (the red oval of 全国统一发票监制章 drawn with paths and rotated characters) — is shown
+// where the signature's StampAnnot puts it, floating over the text like the stamp on paper. The signature itself is
+// not checked: what is shown is the picture the file carries, not a verified seal.
+//
+// The DER is walked with bounds and a budget (lengths are checked against what is left, nesting and the number of
+// elements are capped); a seal OFD is opened from memory with its own small limit and drawn with SkiaSharp: text with
+// each character at its place and rotation (CTM), paths (lines, curves, arcs) stroked and filled, pictures.
+
+using System.Xml.Linq;
+using Filee.Engines.Cad;
+using SkiaSharp;
+
+namespace Filee.Engines.Ofd;
+
+internal sealed partial class OfdReader
+{
+ /// <summary>Signatures read per document; stamps per signature.</summary>
+ private const int MaxSignatures = 64, MaxStamps = 16;
+
+ /// <summary>Largest SignedValue read (a signature with its certificates is a few KB).</summary>
+ private const long MaxSignedValueBytes = 4L * 1024 * 1024;
+
+ /// <summary>What a seal OFD may unpack to.</summary>
+ private const long MaxSealPackageBytes = 16L * 1024 * 1024;
+
+ /// <summary>Seal drawing resolution (pixels per millimetre, about 300 dpi) and largest seal side (mm).</summary>
+ private const float SealScale = 12, MaxSealSize = 200;
+
+ /// <summary>Drawing objects drawn per seal.</summary>
+ private const int MaxSealObjects = 20_000;
+
+ /// <summary>
+ /// Adds the seal of each signature (OFD.xml → Signatures.xml → Signature.xml) as a picture at its StampAnnot's
+ /// boundary on the page it names. A damaged signature part leaves its seal out; the document still converts.
+ /// </summary>
+ private void AddSeals(XElement ofd, List<PageContent> pages)
+ {
+ var listPath = OfdPackage.Resolve("", Child(Child(ofd, "DocBody"), "Signatures")?.Value);
+ if (Optional(listPath) is not { } list)
+ return;
+ var byId = pages.Where(p => p.Id is not null).GroupBy(p => p.Id!).ToDictionary(g => g.Key, g => g.First());
+ foreach (var signature in Children(list, "Signature").Take(MaxSignatures))
+ {
+ var path = OfdPackage.Resolve(OfdPackage.DirName(listPath!), Attr(signature, "BaseLoc"));
+ if (Optional(path) is not { } root)
+ continue;
+ var info = Child(root, "SignedInfo");
+ var stamps = Children(info, "StampAnnot").Take(MaxStamps)
+ .Select(s => (Page: Attr(s, "PageRef") is { } id ? byId.GetValueOrDefault(id) : null, Box: Box(Attr(s, "Boundary"))))
+ .Where(s => s.Page is not null && s.Box is { Width: >= 1 and <= MaxSealSize, Height: >= 1 and <= MaxSealSize })
+ .ToList();
+ if (stamps.Count == 0)
+ continue;
+ var valuePath = OfdPackage.Resolve(OfdPackage.DirName(path!), Child(root, "SignedValue")?.Value);
+ if (valuePath is null || _package.Read(valuePath, MaxSignedValueBytes) is not { } signed || SealFile(signed) is not { } file)
+ continue;
+ foreach (var (page, box) in stamps)
+ {
+ var (x, y, width, height) = box!.Value;
+ if (x < page!.Width && y < page.Height && x + width > 0 && y + height > 0)
+ page.Pictures.Add(new Picture(null, file, x, y, width, height));
+ }
+ }
+ }
+
+ /// <summary>An XML part that may be missing or damaged (null then) without failing the conversion.</summary>
+ private XElement? Optional(string? name)
+ {
+ try
+ {
+ return _package.LoadXml(name)?.Root;
+ }
+ catch (InvalidDataException)
+ {
+ return null;
+ }
+ }
+
+ /// <summary>The seal picture of a signature as a file in the media folder; null when there is none Filee can show.</summary>
+ private string? SealFile(byte[] signed)
+ {
+ if (SealPicture(signed) is not { } data)
+ return null;
+ try
+ {
+ return data is [0x50, 0x4B, ..] ? DrawSeal(data) : Save(data);
+ }
+ catch (Exception ex) when (ex is InvalidDataException or IOException or System.Xml.XmlException)
+ {
+ return null; // a damaged seal is left out; the page still converts
+ }
+ }
+
+ // ───────────────────────── DER ─────────────────────────
+
+ /// <summary>
+ /// The picture data of a seal (SES_ESPictrueInfo: SEQUENCE { type IA5String, data OCTET STRING, width, height }),
+ /// the first such sequence in the signature whose type is a picture format; null when there is none.
+ /// </summary>
+ private static byte[]? SealPicture(byte[] der)
+ {
+ var budget = 20_000;
+ return Find(0, der.Length, 0);
+
+ byte[]? Find(int start, int end, int depth)
+ {
+ for (var pos = start; pos < end && budget-- > 0;)
+ {
+ if (!Header(pos, end, out var tag, out var body, out var length))
+ return null;
+ if (tag is 0x30 or 0xA0 or 0xA1 or 0xA2 or 0xA3)
+ {
+ if (tag == 0x30 && PictureInfo(body, body + length) is { } found)
+ return found;
+ if (depth < 12 && Find(body, body + length, depth + 1) is { } inner)
+ return inner;
+ }
+ pos = body + length;
+ }
+ return null;
+ }
+
+ byte[]? PictureInfo(int start, int end)
+ {
+ if (!Header(start, end, out var typeTag, out var typeBody, out var typeLength) || typeTag is not (0x16 or 0x0C or 0x13) || typeLength is < 2 or > 8)
+ return null;
+ var type = System.Text.Encoding.ASCII.GetString(der, typeBody, typeLength).Trim().ToLowerInvariant();
+ if (type is not ("ofd" or "png" or "jpg" or "jpeg" or "gif" or "bmp" or "tif" or "tiff")
+ || !Header(typeBody + typeLength, end, out var dataTag, out var dataBody, out var dataLength) || dataTag != 0x04 || dataLength == 0)
+ return null;
+ return der[dataBody..(dataBody + dataLength)];
+ }
+
+ // Tag, start and length of the element at pos; false when it is not well formed or runs past end.
+ bool Header(int pos, int end, out int tag, out int body, out int length)
+ {
+ (tag, body, length) = (0, 0, 0);
+ if (pos + 2 > end)
+ return false;
+ tag = der[pos];
+ if ((tag & 0x1F) == 0x1F)
+ return false; // multi-byte tags do not occur in a signature
+ int first = der[pos + 1];
+ body = pos + 2;
+ if (first < 0x80)
+ {
+ length = first;
+ }
+ else
+ {
+ var count = first & 0x7F;
+ if (count is 0 or > 4 || body + count > end)
+ return false;
+ long value = 0;
+ for (var i = 0; i < count; i++)
+ value = value << 8 | der[body + i];
+ body += count;
+ if (value > int.MaxValue)
+ return false;
+ length = (int)value;
+ }
+ return length <= end - body;
+ }
+ }
+
+ // ───────────────────────── Drawing a seal OFD ─────────────────────────
+
+ /// <summary>The first page of a seal OFD drawn on a transparent PNG at its own size; null when it has none.</summary>
+ private string? DrawSeal(byte[] zip)
+ {
+ using var package = new OfdPackage(zip, MaxSealPackageBytes);
+ var reader = new OfdReader(package, _mediaFolder);
+ var ofd = package.LoadXml("OFD.xml")?.Root;
+ var docPath = OfdPackage.Resolve("", Child(Child(ofd, "DocBody"), "DocRoot")?.Value);
+ if (ofd is null || package.LoadXml(docPath)?.Root is not { } document)
+ return null;
+ var docDir = OfdPackage.DirName(docPath!);
+ var common = Child(document, "CommonData");
+ var res = new Resources(null);
+ foreach (var name in Children(common, "PublicRes").Concat(Children(common, "DocumentRes")))
+ reader.LoadRes(res, OfdPackage.Resolve(docDir, name.Value), docDir);
+ var pagePath = PagePath(docDir, Attr(Child(Child(document, "Pages"), "Page"), "BaseLoc"));
+ if (package.LoadXml(pagePath)?.Root is not { } page)
+ return null;
+ var pageRes = reader.PageResources(page, pagePath!, docDir, res);
+ var (width, height) = PageArea(Child(page, "Area")) ?? PageArea(Child(common, "PageArea")) ?? (0, 0);
+ if (width is < 1 or > MaxSealSize || height is < 1 or > MaxSealSize)
+ return null;
+
+ using var surface = SKSurface.Create(new SKImageInfo((int)Math.Ceiling(width * SealScale), (int)Math.Ceiling(height * SealScale), SKColorType.Rgba8888, SKAlphaType.Premul));
+ if (surface is null)
+ return null;
+ var canvas = surface.Canvas;
+ canvas.Clear(SKColors.Transparent);
+ canvas.Scale(SealScale);
+ var objects = 0;
+ reader.DrawContent(canvas, Child(page, "Content"), pageRes, null, 0, ref objects);
+
+ using var image = surface.Snapshot();
+ using var png = image.Encode(SKEncodedImageFormat.Png, 100);
+ Directory.CreateDirectory(_mediaFolder);
+ var file = Path.Combine(_mediaFolder, $"ofd-{Guid.NewGuid():N}.png");
+ using (var stream = File.Create(file))
+ png.SaveTo(stream);
+ return file;
+ }
+
+ private void DrawContent(SKCanvas canvas, XElement? container, Resources res, string? layerDraw, int depth, ref int objects)
+ {
+ if (container is null || depth > MaxDepth)
+ return;
+ foreach (var element in container.Elements())
+ {
+ if (Attr(element, "Visible") == "false" || ++objects > MaxSealObjects)
+ continue;
+ switch (element.Name.LocalName)
+ {
+ case "Layer":
+ DrawContent(canvas, element, res, Attr(element, "DrawParam") ?? layerDraw, depth + 1, ref objects);
+ break;
+ case "PageBlock":
+ DrawContent(canvas, element, res, layerDraw, depth + 1, ref objects);
+ break;
+ case "TextObject":
+ DrawText(canvas, element, res, layerDraw);
+ break;
+ case "PathObject":
+ DrawPath(canvas, element, res, layerDraw);
+ break;
+ case "ImageObject":
+ DrawImage(canvas, element, res);
+ break;
+ }
+ }
+ }
+
+ /// <summary>Moves the canvas into an object's space: its boundary's corner, then its CTM.</summary>
+ private static void Enter(SKCanvas canvas, XElement element)
+ {
+ var box = Box(Attr(element, "Boundary")) ?? default;
+ var ctm = Matrix.Parse(Attr(element, "CTM"));
+ canvas.Save();
+ canvas.Translate((float)box.X, (float)box.Y);
+ var matrix = new SKMatrix((float)ctm.A, (float)ctm.C, (float)ctm.E, (float)ctm.B, (float)ctm.D, (float)ctm.F, 0, 0, 1);
+ canvas.Concat(in matrix);
+ }
+
+ private static SKColor? SkColor(string? hex) => hex is null ? null : SKColor.TryParse(hex, out var color) ? color : null;
+
+ private static void DrawText(SKCanvas canvas, XElement element, Resources res, string? layerDraw)
+ {
+ var size = Number(Attr(element, "Size")) is { } s and > 0 and < 1000 ? s : DefaultSize;
+ var info = Attr(element, "Font") is { } fontId ? res.Font(fontId) : null;
+ var own = res.Draw(Attr(element, "DrawParam"));
+ var layer = res.Draw(layerDraw);
+ var color = SkColor(Color(Attr(element, "FillColor")) ?? ColorOf(Child(element, "FillColor")) ?? own.Fill ?? layer.Fill) ?? SKColors.Black;
+ var primary = CadFonts.Resolve(FontFamily(info?.Name), Number(Attr(element, "Weight")) >= 600 || info?.Bold == true, info?.Italic == true);
+ using var paint = new SKPaint { Color = color, IsAntialias = true };
+
+ Enter(canvas, element);
+ double penX = 0, penY = 0;
+ foreach (var code in Children(element, "TextCode"))
+ {
+ if (Glyphs(code, size, ref penX, ref penY) is not { } glyphs)
+ continue;
+ var (text, xs, ys, _) = glyphs;
+ for (var i = 0; i < text.Length; i++)
+ {
+ if (char.IsWhiteSpace(text[i]) || char.IsSurrogate(text[i]))
+ continue;
+ var typeface = CadFonts.Layout(text[i].ToString(), primary) is [var run, ..] ? run.Typeface : primary;
+ using var font = CadFonts.CreateFont(typeface, (float)size);
+ canvas.DrawText(text[i].ToString(), (float)xs[i], (float)ys[i], font, paint);
+ }
+ }
+ canvas.Restore();
+ }
+
+ private static void DrawPath(SKCanvas canvas, XElement element, Resources res, string? layerDraw)
+ {
+ if (Child(element, "AbbreviatedData")?.Value is not { Length: > 0 and < 1_000_000 } data)
+ return;
+ var own = res.Draw(Attr(element, "DrawParam"));
+ var layer = res.Draw(layerDraw);
+ var stroke = Attr(element, "Stroke") != "false" ? SkColor(ColorOf(Child(element, "StrokeColor")) ?? own.Stroke ?? layer.Stroke) ?? SKColors.Black : (SKColor?)null;
+ var fill = Attr(element, "Fill") == "true" ? SkColor(ColorOf(Child(element, "FillColor")) ?? own.Fill ?? layer.Fill) ?? SKColors.Black : (SKColor?)null;
+ var lineWidth = Number(Attr(element, "LineWidth")) ?? own.LineWidth ?? layer.LineWidth ?? 0.353;
+
+ using var path = new SKPath();
+ var tokens = data.Split([' ', '\t', '\r', '\n', ','], StringSplitOptions.RemoveEmptyEntries);
+ float At(int i) => i < tokens.Length ? (float)(Number(tokens[i]) ?? 0) : 0;
+ for (var i = 0; i < tokens.Length;)
+ {
+ switch (tokens[i])
+ {
+ case "S" or "M":
+ path.MoveTo(At(i + 1), At(i + 2));
+ i += 3;
+ break;
+ case "L":
+ path.LineTo(At(i + 1), At(i + 2));
+ i += 3;
+ break;
+ case "Q":
+ path.QuadTo(At(i + 1), At(i + 2), At(i + 3), At(i + 4));
+ i += 5;
+ break;
+ case "B":
+ path.CubicTo(At(i + 1), At(i + 2), At(i + 3), At(i + 4), At(i + 5), At(i + 6));
+ i += 7;
+ break;
+ case "A":
+ path.ArcTo(At(i + 1), At(i + 2), At(i + 3), At(i + 4) != 0 ? SKPathArcSize.Large : SKPathArcSize.Small,
+ At(i + 5) != 0 ? SKPathDirection.Clockwise : SKPathDirection.CounterClockwise, At(i + 6), At(i + 7));
+ i += 8;
+ break;
+ case "C":
+ path.Close();
+ i++;
+ break;
+ default:
+ i++;
+ break;
+ }
+ }
+
+ Enter(canvas, element);
+ if (fill is { } fillColor)
+ {
+ using var paint = new SKPaint { Color = fillColor, IsAntialias = true, Style = SKPaintStyle.Fill };
+ canvas.DrawPath(path, paint);
+ }
+ if (stroke is { } strokeColor)
+ {
+ using var paint = new SKPaint { Color = strokeColor, IsAntialias = true, Style = SKPaintStyle.Stroke, StrokeWidth = (float)Math.Clamp(lineWidth, 0.05, 20) };
+ canvas.DrawPath(path, paint);
+ }
+ canvas.Restore();
+ }
+
+ /// <summary>A picture of the seal (PNG, JPEG, GIF, BMP), filling its unit square in the object's space.</summary>
+ private void DrawImage(SKCanvas canvas, XElement element, Resources res)
+ {
+ if (Attr(element, "ResourceID") is not { } id || res.Media(id) is not { } part
+ || _package.Read(part, OfdPackage.MaxPictureBytes) is not { } bytes)
+ return;
+ using var codec = SKCodec.Create(new MemoryStream(bytes));
+ if (codec is null || (long)codec.Info.Width * codec.Info.Height > MaxPicturePixels)
+ return;
+ using var bitmap = SKBitmap.Decode(codec);
+ if (bitmap is null)
+ return;
+ Enter(canvas, element);
+ canvas.DrawBitmap(bitmap, new SKRect(0, 0, 1, 1));
+ canvas.Restore();
+ }
+}
diff --git a/src/Filee.Engines/Ofd/OfdReader.Tables.cs b/src/Filee.Engines/Ofd/OfdReader.Tables.cs
index 35d0b04f..ba81b591 100644
--- a/src/Filee.Engines/Ofd/OfdReader.Tables.cs
+++ b/src/Filee.Engines/Ofd/OfdReader.Tables.cs
@@ -453,6 +453,7 @@ internal sealed partial class OfdReader
ColumnWidths = [.. grid.Columns.Zip(grid.Columns.Skip(1), (a, b) => Hwp(b - a))],
Borders = HBorders.Empty,
CellMargin = new HInsets(Hwp(Padding), Hwp(Padding), 0, 0),
+ Tight = true, // the next block's space before is the distance on the page
};
if (grid.Left - containerLeft > 0.5)
table.Indent = Hwp(grid.Left - containerLeft);
@@ -472,19 +473,27 @@ internal sealed partial class OfdReader
if (cell.Fragments.Count > 0)
{
var (left, right) = (cell.Left + Padding, cell.Right - Padding);
- var paragraphs = Paragraphs(Lines(cell.Fragments), left, right);
- var above = TextTop(paragraphs[0]);
+ // Only lines at about single spacing are one paragraph: widely spaced lines in a cell are rows (小计,
+ // 折扣, 总计 under each other) that must stay level with the rows of the cells beside them, and renderers
+ // place text differently inside a tall exact line (Word at its foot, 한글 and rhwp at its head).
+ var paragraphs = FitLineHeights(Paragraphs(Lines(cell.Fragments), left, right, maxPitch: 1.6));
+
+ // One paragraph about as far from the top as from the bottom is centred. Anything else keeps its distance
+ // from the top (as the cell's top padding: space before a cell's first paragraph is not drawn
+ // everywhere): the cells of a column-ruled list (序号, 项目名称, 金额 side by side, each with all rows)
+ // hold their rows at the same heights, so they line up across the columns as on the page.
+ var space = (Top: TextTop(paragraphs[0]) - cell.Top, Bottom: cell.Bottom - TextBottom(paragraphs[^1]));
+ var centred = paragraphs.Count == 1 && space.Top > 1 && Math.Abs(space.Top - space.Bottom) <= Math.Max(1, 0.25 * (space.Top + space.Bottom));
+ hcell.VerticalAlign = centred ? HVerticalAlign.Center : HVerticalAlign.Top;
+ if (!centred && space.Top > 0.2)
+ hcell.CellMargin = new HInsets(Hwp(Padding), Hwp(Padding), Hwp(Math.Min(space.Top, 100)), 0);
+ var flow = TextTop(paragraphs[0]);
foreach (var paragraph in paragraphs)
{
- var before = hcell.Blocks.Count == 0 ? 0 : Math.Clamp(TextTop(paragraph) - above, 0, 50);
+ var before = Math.Clamp(TextTop(paragraph) - flow, 0, 100);
hcell.Blocks.Add(TextParagraph(paragraph, left, right, Hwp(before), exact: true));
- above = TextBottom(paragraph);
+ flow += before + TextBottom(paragraph) - TextTop(paragraph);
}
- // Text about as far from the top as from the bottom is centred; text at the bottom stays there.
- var space = (Top: TextTop(paragraphs[0]) - cell.Top, Bottom: cell.Bottom - TextBottom(paragraphs[^1]));
- hcell.VerticalAlign = space.Top > 1 && Math.Abs(space.Top - space.Bottom) <= Math.Max(1, 0.25 * (space.Top + space.Bottom)) ? HVerticalAlign.Center
- : space.Bottom < 0.4 * space.Top && space.Top > 2 ? HVerticalAlign.Bottom
- : HVerticalAlign.Top;
}
table.Rows[cell.Row].Cells.Add(hcell);
}
diff --git a/src/Filee.Engines/Ofd/OfdReader.cs b/src/Filee.Engines/Ofd/OfdReader.cs
index 4414399b..56ec9395 100644
--- a/src/Filee.Engines/Ofd/OfdReader.cs
+++ b/src/Filee.Engines/Ofd/OfdReader.cs
@@ -11,11 +11,13 @@
//
// Three writer variants seen in the wild are handled: the standard's own structure, WPS (page size only in
// Document.xml, a Res.xml next to the pages, bold as Weight=700) and tax invoices (template pages with the labels,
-// DocumentRes, the colour in a layer's DrawParam, item names wrapped onto a second line).
+// DocumentRes, the colour in a layer's DrawParam, item names wrapped onto a second line, the cipher text as one
+// TextCode of four lines, a sales list with rules only between its columns). Annotations add the text and pictures
+// of their appearance; seals stored in signatures (Signs/) float where their stamp is (OfdReader.Seals).
//
-// Not converted: signatures (seals stored in Signs/ as signed data), annotations, embedded fonts (the font name is
-// kept), composite objects, JBIG2 pictures. Encrypted documents (GM/T 0099 Encryptions.xml) are refused; nothing
-// is decrypted. The package is read defensively (OfdPackage).
+// Not converted: signature checks, embedded fonts (the font name is kept), composite objects, JBIG2 pictures.
+// Encrypted documents (GM/T 0099 Encryptions.xml) are refused; nothing is decrypted. The package is read
+// defensively (OfdPackage).
using System.Globalization;
using System.Xml.Linq;
@@ -94,18 +96,44 @@ internal sealed partial class OfdReader
templates.TryAdd(id, path);
}
+ var annotations = AnnotationFiles(document, docDir);
var pages = new List<PageContent>();
foreach (var page in Children(Child(document, "Pages"), "Page"))
{
if (pages.Count == MaxPages)
throw new InvalidDataException($"The OFD document has more than {MaxPages:N0} pages; Filee does not read it.");
var path = PagePath(docDir, Attr(page, "BaseLoc"));
- if (_package.LoadXml(path)?.Root is { } content)
- pages.Add(ReadPage(content, path!, docDir, docRes, templates, defaultArea));
+ if (_package.LoadXml(path)?.Root is not { } content)
+ continue;
+ var id = Attr(page, "ID");
+ var read = ReadPage(content, path!, docDir, docRes, templates, defaultArea,
+ id is not null && annotations.TryGetValue(id, out var files) ? files : []);
+ read.Id = id;
+ pages.Add(read);
}
+ AddSeals(ofd, pages);
return Build(pages);
}
+ /// <summary>The annotation files of each page (by page ID) that the document's Annotations.xml lists.</summary>
+ private Dictionary<string, List<string>> AnnotationFiles(XElement document, string docDir)
+ {
+ var result = new Dictionary<string, List<string>>();
+ var listPath = OfdPackage.Resolve(docDir, Child(document, "Annotations")?.Value);
+ if (_package.LoadXml(listPath)?.Root is not { } list)
+ return result;
+ foreach (var page in Children(list, "Page").Take(MaxPages))
+ {
+ if (Attr(page, "PageID") is not { } id || OfdPackage.Resolve(OfdPackage.DirName(listPath!), Child(page, "FileLoc")?.Value) is not { } file)
+ continue;
+ if (!result.TryGetValue(id, out var files))
+ result[id] = files = [];
+ if (files.Count < 8)
+ files.Add(file);
+ }
+ return result;
+ }
+
/// <summary>
/// Encrypted OFD (GM/T 0099: an Encryptions.xml entry file, encrypted parts) is refused, never decrypted.
/// </summary>
@@ -130,6 +158,9 @@ internal sealed partial class OfdReader
/// <summary>What a page draws, in millimetres from its top-left corner.</summary>
private sealed class PageContent
{
+ /// <summary>The page's ID in Document.xml (signatures and annotations name pages by it).</summary>
+ public string? Id { get; set; }
+
public double Width { get; set; }
public double Height { get; set; }
public List<Fragment> Fragments { get; } = [];
@@ -153,6 +184,9 @@ internal sealed partial class OfdReader
/// <summary>Drawn by a template page (labels of a form), not by the page itself.</summary>
public bool Template { get; } = template;
+ /// <summary>A further line of one TextCode (a block the writer broke itself): it starts a line of its own.</summary>
+ public bool Continued { get; init; }
+
public double X { get; set; }
public double Baseline { get; set; }
public double Width { get; set; }
@@ -167,15 +201,15 @@ internal sealed partial class OfdReader
public double Bottom => Baseline + Run + 0.12 * Size;
}
- /// <summary>A picture: the package part and its box.</summary>
- private sealed record Picture(string Part, double Left, double Top, double Width, double Height)
+ /// <summary>A picture and its box: a part of the package, or a file already made (a seal drawn from its signature).</summary>
+ private sealed record Picture(string? Part, string? File, double Left, double Top, double Width, double Height)
{
public double Right => Left + Width;
public double Bottom => Top + Height;
}
private PageContent ReadPage(XElement content, string path, string docDir, Resources docRes,
- Dictionary<string, string> templates, (double W, double H) defaultArea)
+ Dictionary<string, string> templates, (double W, double H) defaultArea, List<string> annotationFiles)
{
var page = new PageContent();
var area = PageArea(Child(content, "Area"));
@@ -186,13 +220,31 @@ internal sealed partial class OfdReader
if (!templates.TryGetValue(id, out var templatePath) || Template(templatePath, docDir, docRes) is not { } template)
continue;
area ??= PageArea(Child(template.Root, "Area"));
- var first = page.Fragments.Count;
Collect(Child(template.Root, "Content"), template.Res, page, null, true, 0);
- if (page.Fragments.Count - first <= 5000)
- MergeTemplateLabels(page.Fragments, first);
}
- Collect(Child(content, "Content"), PageResources(content, path, docDir, docRes), page, null, false, 0);
+ var res = PageResources(content, path, docDir, docRes);
+ Collect(Child(content, "Content"), res, page, null, false, 0);
+
+ // Annotations drawn on the page (a stamp, a note): the text and pictures of their appearance, placed from its
+ // boundary. Their paths (highlights, underlines) are no table rules.
+ foreach (var file in annotationFiles)
+ {
+ foreach (var annot in Children(_package.LoadXml(file)?.Root, "Annot").Take(1000))
+ {
+ if (Attr(annot, "Visible") == "false")
+ continue;
+ foreach (var appearance in Children(annot, "Appearance"))
+ {
+ var box = Box(Attr(appearance, "Boundary")) ?? default;
+ Collect(appearance, res, page, null, false, 1, (box.X, box.Y), paths: false);
+ }
+ }
+ }
+
+ // Labels are merged once the page's values are there: a value between two characters (共 4 页) keeps them apart.
+ if (page.Fragments.Count(f => f.Template) <= 5000)
+ MergeTemplateLabels(page.Fragments);
(page.Width, page.Height) = area ?? defaultArea;
return page;
}
@@ -229,8 +281,12 @@ internal sealed partial class OfdReader
return null;
}
- /// <summary>The drawing objects of a content tree (layers, page blocks), with the layer's drawing parameters.</summary>
- private void Collect(XElement? container, Resources res, PageContent page, string? layerDraw, bool template, int depth)
+ /// <summary>
+ /// The drawing objects of a content tree (layers, page blocks), with the layer's drawing parameters. Objects of an
+ /// annotation's appearance are placed from its <paramref name="origin"/> and draw no rules (<paramref name="paths"/>).
+ /// </summary>
+ private void Collect(XElement? container, Resources res, PageContent page, string? layerDraw, bool template, int depth,
+ (double X, double Y) origin = default, bool paths = true)
{
if (container is null || depth > MaxDepth)
return;
@@ -241,20 +297,20 @@ internal sealed partial class OfdReader
switch (element.Name.LocalName)
{
case "Layer":
- Collect(element, res, page, Attr(element, "DrawParam") ?? layerDraw, template, depth + 1);
+ Collect(element, res, page, Attr(element, "DrawParam") ?? layerDraw, template, depth + 1, origin, paths);
break;
case "PageBlock":
- Collect(element, res, page, layerDraw, template, depth + 1);
+ Collect(element, res, page, layerDraw, template, depth + 1, origin, paths);
break;
case "TextObject":
Count();
- TextObject(element, res, page, layerDraw, template);
+ TextObject(element, res, page, layerDraw, template, origin);
break;
case "ImageObject":
Count();
- ImageObject(element, res, page);
+ ImageObject(element, res, page, origin);
break;
- case "PathObject":
+ case "PathObject" when paths:
Count();
PathObject(element, res, page, layerDraw);
break;
@@ -270,7 +326,7 @@ internal sealed partial class OfdReader
// ───────────────────────── Text ─────────────────────────
- private static void TextObject(XElement element, Resources res, PageContent page, string? layerDraw, bool template)
+ private static void TextObject(XElement element, Resources res, PageContent page, string? layerDraw, bool template, (double X, double Y) origin)
{
var box = Box(Attr(element, "Boundary")) ?? default;
var ctm = Matrix.Parse(Attr(element, "CTM"));
@@ -298,50 +354,91 @@ internal sealed partial class OfdReader
EastAsianFont: family,
Color: color);
- // A TextCode without X or Y goes on where the one before it ended.
+ // A run of text (trimmed) drawn from (x, y) in the object's space: along the baseline, or down a column (run).
+ void Add(string text, double x, double y, double width, double run, bool continued = false)
+ {
+ var (pageX, pageY) = ctm.Apply(x, y);
+ if (page.Fragments.Count == MaxFragmentsPerPage)
+ throw new InvalidDataException($"An OFD page has more than {MaxFragmentsPerPage:N0} pieces of text; Filee does not read it.");
+ page.Fragments.Add(new Fragment(text, format, fontSize, template)
+ {
+ X = origin.X + box.X + pageX,
+ Baseline = origin.Y + box.Y + pageY,
+ Width = width * scaleX,
+ Run = run * ctm.ScaleY,
+ Continued = continued,
+ });
+ }
+
double penX = 0, penY = 0;
foreach (var code in Children(element, "TextCode"))
{
- var text = string.Concat(code.Value.Select(c => char.IsControl(c) ? ' ' : c));
- var x = Number(Attr(code, "X")) ?? penX;
- var y = Number(Attr(code, "Y")) ?? penY;
- if (text.Length == 0)
+ if (Glyphs(code, size, ref penX, ref penY) is not { } glyphs)
+ continue;
+ var (text, xs, ys, vertical) = glyphs;
+ if (vertical)
+ {
+ var first = text.TakeWhile(char.IsWhiteSpace).Count();
+ var last = text.Length - 1 - text.Reverse().TakeWhile(char.IsWhiteSpace).Count();
+ if (first <= last)
+ Add(text[first..(last + 1)], xs[first], ys[first], size, ys[last] - ys[first]);
continue;
- var dx = Deltas(Attr(code, "DeltaX"), text.Length - 1);
- var dy = Deltas(Attr(code, "DeltaY"), text.Length - 1);
- var vertical = dy is not null && dy.Any(d => d != 0) && (dx is null || dx.All(d => d == 0));
+ }
- // Offsets of each character from the first, along the line (or down the column).
- var offsets = new double[text.Length + 1];
- for (var i = 0; i < text.Length; i++)
+ // A step back or to another baseline starts a new line: some writers put a whole block (the cipher text of
+ // an invoice's 密码区, four lines of 27 characters) into one TextCode.
+ var lineStart = 0;
+ for (var i = 1; i <= text.Length; i++)
{
- var step = vertical ? dy!.ElementAtOrDefault(i) : dx is not null && i < dx.Length ? dx[i] : Advance(text[i], size);
- offsets[i + 1] = offsets[i] + (vertical && i >= dy!.Length ? size : step);
+ if (i < text.Length && Math.Abs(ys[i] - ys[i - 1]) < 0.01 && xs[i] >= xs[i - 1] - 0.01)
+ continue;
+ var segment = text[lineStart..i];
+ var first = lineStart + segment.TakeWhile(char.IsWhiteSpace).Count();
+ var last = i - 1 - segment.Reverse().TakeWhile(char.IsWhiteSpace).Count();
+ if (first <= last)
+ Add(text[first..(last + 1)], xs[first], ys[first], xs[last] - xs[first] + Advance(text[last], size), 0, lineStart > 0);
+ lineStart = i;
}
- (penX, penY) = vertical ? (x, y + offsets[^1]) : (x + offsets[^1], y);
-
- var start = 0;
- while (start < text.Length && char.IsWhiteSpace(text[start]))
- start++;
- var end = text.Length - 1;
- while (end >= start && char.IsWhiteSpace(text[end]))
- end--;
- if (end < start)
- continue;
+ }
+ }
- var (originX, originY) = vertical ? (x, y + offsets[start]) : (x + offsets[start], y);
- var (pageX, pageY) = ctm.Apply(originX, originY);
- var fragment = new Fragment(text[start..(end + 1)], format, fontSize, template)
+ /// <summary>
+ /// The characters of a TextCode and where each is drawn in its object's space; vertical when only DeltaY moves
+ /// them (a column). A TextCode without X or Y goes on where the one before it ended (the pen). A DeltaX list
+ /// shorter than the text goes on with its last value (writers give one value for a run of equal advances) while
+ /// the characters are as wide as the last one it covers; without DeltaX the advance is estimated.
+ /// </summary>
+ private static (string Text, double[] Xs, double[] Ys, bool Vertical)? Glyphs(XElement code, double size, ref double penX, ref double penY)
+ {
+ var text = string.Concat(code.Value.Select(c => char.IsControl(c) ? ' ' : c));
+ var x = Number(Attr(code, "X")) ?? penX;
+ var y = Number(Attr(code, "Y")) ?? penY;
+ if (text.Length == 0)
+ return null;
+ var dx = Deltas(Attr(code, "DeltaX"), text.Length - 1);
+ var dy = Deltas(Attr(code, "DeltaY"), text.Length - 1);
+ var vertical = dy is not null && dy.Any(d => d != 0) && (dx is null || dx.All(d => d == 0));
+
+ var xs = new double[text.Length];
+ var ys = new double[text.Length];
+ (xs[0], ys[0]) = (x, y);
+ for (var i = 1; i < text.Length; i++)
+ {
+ if (vertical)
{
- X = box.X + pageX,
- Baseline = box.Y + pageY,
- Width = (vertical ? size : offsets[end] - offsets[start] + Advance(text[end], size)) * scaleX,
- Run = vertical ? (offsets[end] - offsets[start]) * ctm.ScaleY : 0,
- };
- if (page.Fragments.Count == MaxFragmentsPerPage)
- throw new InvalidDataException($"An OFD page has more than {MaxFragmentsPerPage:N0} pieces of text; Filee does not read it.");
- page.Fragments.Add(fragment);
+ xs[i] = x;
+ ys[i] = ys[i - 1] + (i - 1 < dy!.Length ? dy[i - 1] : size);
+ continue;
+ }
+ var step = dx is null ? Advance(text[i - 1], size)
+ : i - 1 < dx.Length ? dx[i - 1]
+ : dx[^1] > 0 && IsWide(text[i - 1]) == IsWide(text[dx.Length - 1]) ? dx[^1]
+ : Advance(text[i - 1], size);
+ xs[i] = xs[i - 1] + step;
+ ys[i] = ys[i - 1] + (dy is not null && i - 1 < dy.Length ? dy[i - 1] : 0);
}
+ (penX, penY) = vertical ? (x, ys[^1] + size) : (xs[^1] + Advance(text[^1], size), ys[^1]);
+ return (text, xs, ys, vertical);
}
/// <summary>
@@ -380,11 +477,12 @@ internal sealed partial class OfdReader
/// <summary>
/// Single characters of a template stacked in one column (购买方信息, 备注 — the block titles of an invoice) or spread
/// over one line (合 计) become one fragment, so they read as a word. Template content only: the page's own single
- /// characters are values in table cells that must stay apart.
+ /// characters are values in table cells that must stay apart, and a pair with anything between them (共 4 页, the
+ /// page's number between the template's characters) stays apart too.
/// </summary>
- private static void MergeTemplateLabels(List<Fragment> fragments, int first)
+ private static void MergeTemplateLabels(List<Fragment> fragments)
{
- var singles = fragments.Skip(first).Where(f => f.Text.Length == 1 && IsWide(f.Text[0]) && !f.Vertical).ToList();
+ var singles = fragments.Where(f => f.Template && f.Text.Length == 1 && IsWide(f.Text[0]) && !f.Vertical).ToList();
var merged = new HashSet<Fragment>();
// Stacked: same X, one under the other, at most three lines apart.
@@ -417,8 +515,8 @@ internal sealed partial class OfdReader
var gap = right.Left - left.Right;
if (left.Text.Length != 1 || Math.Abs(left.Baseline - right.Baseline) > 0.3 || Math.Abs(left.Size - right.Size) > 0.1
|| gap < -0.1 || gap > 8 * right.Size
- || fragments.Skip(first).Any(f => f != left && f != right && Math.Abs(f.Baseline - left.Baseline) < 0.5 * f.Size
- && f.Left >= left.Right - 0.1 && f.Right <= right.Left + 0.1))
+ || fragments.Any(f => f != left && f != right && Math.Abs(f.Baseline - left.Baseline) < 0.5 * f.Size
+ && (f.Left + f.Right) / 2 > left.Right - 0.1 && (f.Left + f.Right) / 2 < right.Left + 0.1))
{
continue;
}
@@ -466,7 +564,7 @@ internal sealed partial class OfdReader
// ───────────────────────── Pictures ─────────────────────────
- private static void ImageObject(XElement element, Resources res, PageContent page)
+ private static void ImageObject(XElement element, Resources res, PageContent page, (double X, double Y) origin)
{
if (Attr(element, "ResourceID") is not { } id || res.Media(id) is not { } part)
return;
@@ -476,7 +574,7 @@ internal sealed partial class OfdReader
var ctm = Matrix.Parse(Attr(element, "CTM"));
var (left, top, width, height) = ctm != Matrix.Identity ? ctm.Bounds(box.X, box.Y) : box;
if (width >= 0.5 && height >= 0.5 && width < 10_000 && height < 10_000)
- page.Pictures.Add(new Picture(part, left, top, width, height));
+ page.Pictures.Add(new Picture(part, null, origin.X + left, origin.Y + top, width, height));
}
/// <summary>A picture unpacked into the media folder (once per part), as a format the writers embed; null when
diff --git a/tests/Filee.Engines.Tests/OfdTests.cs b/tests/Filee.Engines.Tests/OfdTests.cs
index 4c96f2a0..59963eed 100644
--- a/tests/Filee.Engines.Tests/OfdTests.cs
+++ b/tests/Filee.Engines.Tests/OfdTests.cs
@@ -278,7 +278,9 @@ public class OfdTests(EngineFixture fx) : IClassFixture<EngineFixture>
{
var folder = fx.NewFolder();
var document = OfdReader.Read(MakeWps(folder), Path.Combine(folder, "media"));
- var blocks = document.Sections.Single().Blocks.OfType<HParagraph>().ToList();
+ // Each page starts with an empty line as high as the distance from the top margin to its first text.
+ var all = document.Sections.Single().Blocks.OfType<HParagraph>().ToList();
+ var blocks = all.Where(p => ParagraphText(p).Length > 0).ToList();
Assert.Equal(["医院信息化建设方案", Body, "第一章 总体规划", "第二章 实施步骤"], blocks.Select(ParagraphText));
var title = blocks[0];
@@ -294,8 +296,268 @@ public class OfdTests(EngineFixture fx) : IClassFixture<EngineFixture>
Assert.Equal(Hwp(11.2), body.Format.FirstLine);
Assert.Equal("FangSong_GB2312", body.Inlines.OfType<HText>().First().Format.Font);
- Assert.False(blocks[2].PageBreakBefore);
- Assert.True(blocks[3].PageBreakBefore);
+ // The second page starts with a page break: on that empty line, which keeps the first text's distance.
+ var second = all.IndexOf(blocks[3]);
+ Assert.True(all[second - 1].PageBreakBefore);
+ Assert.Equal("", ParagraphText(all[second - 1]));
+ Assert.Equal(HLineSpacingKind.Fixed, all[second - 1].Format.LineSpacing!.Value.Kind);
+ Assert.Equal(0, blocks[3].Format.Before);
+ Assert.Single(all, p => p.PageBreakBefore);
+ }
+
+ // ───────────────────────── Structures of real invoice writers ─────────────────────────
+
+ /// <summary>
+ /// A one-page OFD around the given page content (and template content), with optional extra parts; page ID 1,
+ /// fonts 3 (宋体) and 5 (Courier New).
+ /// </summary>
+ private static string MakeOfd(string folder, string page, string template = "", Action<ZipArchive>? extra = null,
+ string docExtra = "", string bodyExtra = "", string area = "0 0 210 140")
+ {
+ var path = Path.Combine(folder, $"{Guid.NewGuid():N}.ofd");
+ using var zip = ZipFile.Open(path, ZipArchiveMode.Create);
+ Text(zip, "OFD.xml", $"""<?xml version="1.0" encoding="UTF-8"?><ofd:OFD {Ns} Version="1.1"><ofd:DocBody><ofd:DocRoot>Doc_0/Document.xml</ofd:DocRoot>{bodyExtra}</ofd:DocBody></ofd:OFD>""");
+ Text(zip, "Doc_0/Document.xml", $"""
+ <?xml version="1.0" encoding="UTF-8"?>
+ <ofd:Document {Ns}><ofd:CommonData><ofd:PageArea><ofd:PhysicalBox>{area}</ofd:PhysicalBox></ofd:PageArea>
+ <ofd:PublicRes>PublicRes.xml</ofd:PublicRes><ofd:DocumentRes>DocumentRes.xml</ofd:DocumentRes><ofd:TemplatePage ID="2" BaseLoc="Tpls/Tpl_0/Content.xml"/></ofd:CommonData>
+ <ofd:Pages><ofd:Page ID="1" BaseLoc="Pages/Page_0/Content.xml"/></ofd:Pages>{docExtra}</ofd:Document>
+ """);
+ Text(zip, "Doc_0/PublicRes.xml", $"""<?xml version="1.0" encoding="UTF-8"?><ofd:Res {Ns} BaseLoc="Res"><ofd:Fonts><ofd:Font ID="3" FontName="宋体"/><ofd:Font ID="5" FontName="Courier New"/></ofd:Fonts></ofd:Res>""");
+ Text(zip, "Doc_0/Tpls/Tpl_0/Content.xml", $"""<?xml version="1.0" encoding="UTF-8"?><ofd:Page {Ns}><ofd:Content><ofd:Layer ID="1">{template}</ofd:Layer></ofd:Content></ofd:Page>""");
+ Text(zip, "Doc_0/Pages/Page_0/Content.xml", $"""
+ <?xml version="1.0" encoding="UTF-8"?>
+ <ofd:Page {Ns}><ofd:Template TemplateID="2" ZOrder="Background"/><ofd:Content><ofd:Layer ID="1">{page}</ofd:Layer></ofd:Content></ofd:Page>
+ """);
+ extra?.Invoke(zip);
+ return path;
+ }
+
+ private static string TextObject(string text, double x, double y, double size = 3.175, int font = 3, string code = "", double width = 60) =>
+ $"""<ofd:TextObject ID="1" Boundary="{x} {y - size} {width} {size + 1}" Font="{font}" Size="{size}"><ofd:TextCode X="0" Y="{size}"{code}>{text}</ofd:TextCode></ofd:TextObject>""";
+
+ [Fact]
+ public void A_block_drawn_by_one_text_code_keeps_its_lines_and_a_short_delta_list_goes_on()
+ {
+ // The cipher text of a VAT invoice's 密码区: two lines of four characters in one TextCode — DeltaX steps back
+ // (-7.5) where DeltaY moves down a line. A title whose DeltaX gives one value for all its characters, and a
+ // text placed right where that advance ends: drawn with the font's advance instead, a gap would open.
+ var page = TextObject("ABCDEFGH", 20, 30, 4.2333, 5, """ DeltaX="g 3 2.5 -7.5 g 3 2.5" DeltaY="g 3 0 4.5 g 3 0" """)
+ + TextObject("一二三四", 20, 60, 4, code: """ DeltaX="5" """)
+ + TextObject("五六", 40.3, 60, 4, code: """ DeltaX="5" """);
+ var folder = fx.NewFolder();
+ var document = OfdReader.Read(MakeOfd(folder, page), Path.Combine(folder, "media"));
+ var paragraphs = document.Sections.Single().Blocks.OfType<HParagraph>().Where(p => ParagraphText(p).Length > 0).ToList();
+
+ Assert.Equal("ABCD\nEFGH", ParagraphText(paragraphs[0]));
+ Assert.Equal(HAlign.Left, paragraphs[0].Format.Align);
+ Assert.Equal(Hwp(4.5), paragraphs[0].Format.LineSpacing!.Value.Value); // the block's own line distance
+ Assert.Equal("一二三四五六", ParagraphText(paragraphs[1]));
+ }
+
+ [Fact]
+ public void A_page_value_between_template_characters_keeps_them_apart()
+ {
+ // 共 _ 页 第 _ 页 of a sales list: the template draws the characters, the page the numbers between them.
+ var template = TextObject("共", 160, 50, width: 4) + TextObject("页", 170, 50, width: 4)
+ + TextObject("第", 180, 50, width: 4) + TextObject("页", 190, 50, width: 4)
+ + TextObject("合", 20, 70, width: 4) + TextObject("计", 30, 70, width: 4);
+ var page = TextObject("4", 166, 50, width: 3) + TextObject("1", 186, 50, width: 3);
+ var folder = fx.NewFolder();
+ var document = OfdReader.Read(MakeOfd(folder, page, template), Path.Combine(folder, "media"));
+ var texts = document.Sections.Single().Blocks.OfType<HParagraph>().Select(ParagraphText).Where(t => t.Length > 0).ToList();
+
+ Assert.Matches(@"^共\s*4\s*页\s*第\s*1\s*页$", texts[0]);
+ Assert.Equal("合计", texts[1]); // a pair with nothing between it is still one word
+ }
+
+ [Fact]
+ public void Annotations_add_their_text_and_pictures()
+ {
+ var folder = fx.NewFolder();
+ var png = File.ReadAllBytes(EngineFixture.MakeImage(folder, "stamp.png", MagickFormat.Png, 60, 60));
+ var path = MakeOfd(folder, TextObject("正文内容", 20, 30), docExtra: "<ofd:Annotations>Annots/Annotations.xml</ofd:Annotations>", extra: zip =>
+ {
+ Text(zip, "Doc_0/DocumentRes.xml", $"""<?xml version="1.0"?><ofd:Res {Ns} BaseLoc="Res"><ofd:MultiMedias><ofd:MultiMedia ID="9" Type="Image"><ofd:MediaFile>stamp.png</ofd:MediaFile></ofd:MultiMedia></ofd:MultiMedias></ofd:Res>""");
+ Entry(zip, "Doc_0/Res/stamp.png", png);
+ Text(zip, "Doc_0/Annots/Annotations.xml", $"""<?xml version="1.0"?><ofd:Annotations {Ns}><ofd:Page PageID="1"><ofd:FileLoc>Page_0/Annotation.xml</ofd:FileLoc></ofd:Page></ofd:Annotations>""");
+ // A stamp with a picture and a note with text, both placed from their appearance's boundary; a hidden one.
+ Text(zip, "Doc_0/Annots/Page_0/Annotation.xml", $"""
+ <?xml version="1.0"?>
+ <ofd:PageAnnot {Ns}>
+ <ofd:Annot Type="Stamp" ID="10"><ofd:Appearance Boundary="150 20 30 30"><ofd:ImageObject ID="11" ResourceID="9" Boundary="0 0 30 30" CTM="30 0 0 30 0 0"/></ofd:Appearance></ofd:Annot>
+ <ofd:Annot Type="Highlight" ID="12"><ofd:Appearance Boundary="20 80 100 10">{TextObject("批注:已核对", 0, 5)}<ofd:PathObject ID="13" Boundary="0 0 100 10" Fill="true"><ofd:AbbreviatedData>M 0 0 L 100 0 L 100 10 L 0 10 C</ofd:AbbreviatedData></ofd:PathObject></ofd:Appearance></ofd:Annot>
+ <ofd:Annot Type="Link" ID="14" Visible="false"><ofd:Appearance Boundary="20 100 100 10">{TextObject("隐藏", 0, 5)}</ofd:Appearance></ofd:Annot>
+ </ofd:PageAnnot>
+ """);
+ });
+ var document = OfdReader.Read(path, Path.Combine(folder, "media"));
+ var paragraphs = document.Sections.Single().Blocks.OfType<HParagraph>().ToList();
+ var texts = paragraphs.Select(ParagraphText).Where(t => t.Length > 0).ToList();
+ Assert.Equal(["正文内容", "批注:已核对"], texts);
+ var stamp = paragraphs.SelectMany(p => p.Inlines).OfType<HImage>().Single();
+ Assert.Equal(Hwp(150), stamp.Anchor!.HorizontalOffset);
+ Assert.Equal(Hwp(20), stamp.Anchor!.VerticalOffset);
+ }
+
+ // DER for the seal tests: an SES_Signature (GM/T 0031 v4) reduced to what the reader walks through.
+ private static byte[] Der(byte tag, params byte[][] children)
+ {
+ var body = children.SelectMany(c => c).ToArray();
+ byte[] length = body.Length < 0x80 ? [(byte)body.Length]
+ : body.Length < 0x100 ? [0x81, (byte)body.Length]
+ : [0x82, (byte)(body.Length >> 8), (byte)body.Length];
+ return [tag, .. length, .. body];
+ }
+
+ private static byte[] Ia5(string text) => Der(0x16, Encoding.ASCII.GetBytes(text));
+
+ private static byte[] Signature(string type, byte[] picture) =>
+ Der(0x30,
+ Der(0x30, // TBS_Sign
+ Der(0x02, [4]),
+ Der(0x30, // SESeal
+ Der(0x30, // SES_SealInfo
+ Der(0x30, Ia5("ES"), Der(0x02, [4]), Ia5("TEST")),
+ Ia5("50011200000323"),
+ Der(0x30, Der(0x02, [3]), Der(0x0C, Encoding.UTF8.GetBytes("测试发票监制章"))),
+ Der(0x30, Ia5(type), Der(0x04, picture), Der(0x02, [40]), Der(0x02, [30]))),
+ Der(0x04, [1, 2, 3])),
+ Ia5("/Doc_0/Signs/Sign_0/Signature.xml")),
+ Der(0x04, [4, 5, 6]),
+ Der(0x03, [0, 7]));
+
+ /// <summary>A seal as its own small OFD package: a red oval and a rotated character, as tax-office seals are drawn.</summary>
+ private static byte[] SealPackage()
+ {
+ using var stream = new MemoryStream();
+ using (var zip = new ZipArchive(stream, ZipArchiveMode.Create, leaveOpen: true))
+ {
+ Text(zip, "OFD.xml", $"""<?xml version="1.0"?><ofd:OFD {Ns}><ofd:DocBody><ofd:DocRoot>Doc_0/Document.xml</ofd:DocRoot></ofd:DocBody></ofd:OFD>""");
+ Text(zip, "Doc_0/Document.xml", $"""<?xml version="1.0"?><ofd:Document {Ns}><ofd:CommonData><ofd:PublicRes>PublicRes_0.xml</ofd:PublicRes></ofd:CommonData><ofd:Pages><ofd:Page ID="1" BaseLoc="Pages/Page_0/Content.xml"/></ofd:Pages></ofd:Document>""");
+ Text(zip, "Doc_0/PublicRes_0.xml", $"""<?xml version="1.0"?><ofd:Res {Ns}><ofd:Fonts><ofd:Font ID="4" FontName="楷体"/></ofd:Fonts></ofd:Res>""");
+ Text(zip, "Doc_0/Pages/Page_0/Content.xml", $"""
+ <?xml version="1.0"?>
+ <ofd:Page {Ns}><ofd:Area><ofd:PhysicalBox>0 0 40 30</ofd:PhysicalBox></ofd:Area><ofd:Content><ofd:Layer ID="2">
+ <ofd:TextObject ID="3" Boundary="5 4 4 4" CTM="0.8 -0.6 0.6 0.8 0 0" Font="4" Size="3"><ofd:FillColor Value="255 0 0"/><ofd:TextCode X="0" Y="3">全</ofd:TextCode></ofd:TextObject>
+ <ofd:PathObject ID="4" Boundary="0 0 40 30" LineWidth="1.5"><ofd:StrokeColor Value="255 0 0"/>
+ <ofd:AbbreviatedData>M 39 15 B 39 23 30 29 20 29 B 10 29 1 23 1 15 B 1 7 10 1 20 1 B 30 1 39 7 39 15 C</ofd:AbbreviatedData></ofd:PathObject>
+ </ofd:Layer></ofd:Content></ofd:Page>
+ """);
+ }
+ return stream.ToArray();
+ }
+
+ [Fact]
+ public void Seals_in_signatures_float_where_the_stamp_is()
+ {
+ var folder = fx.NewFolder();
+ var png = File.ReadAllBytes(EngineFixture.MakeImage(folder, "seal.png", MagickFormat.Png, 50, 50));
+ var path = MakeOfd(folder, TextObject("重庆增值税电子普通发票", 60, 15, 6) + TextObject("购买方名称:个人", 20, 60),
+ bodyExtra: "<ofd:Signatures>/Doc_0/Signs/Signatures.xml</ofd:Signatures>", extra: zip =>
+ {
+ Text(zip, "Doc_0/Signs/Signatures.xml", $"""<?xml version="1.0"?><ofd:Signatures {Ns}><ofd:Signature ID="1" BaseLoc="Sign_0/Signature.xml"/><ofd:Signature ID="2" BaseLoc="/Doc_0/Signs/Sign_1/Signature.xml"/><ofd:Signature ID="3" BaseLoc="Sign_2/Signature.xml"/></ofd:Signatures>""");
+ // The tax office's supervision seal over the title (an OFD picture) and the seller's seal (PNG) over
+ // the buyer line; a third signature whose signed value is no DER at all.
+ Text(zip, "Doc_0/Signs/Sign_0/Signature.xml", $"""<?xml version="1.0"?><ofd:Signature {Ns}><ofd:SignedInfo><ofd:StampAnnot ID="1" PageRef="1" Boundary="85 5 40 30"/></ofd:SignedInfo><ofd:SignedValue>/Doc_0/Signs/Sign_0/SignedValue.dat</ofd:SignedValue></ofd:Signature>""");
+ Entry(zip, "Doc_0/Signs/Sign_0/SignedValue.dat", Signature("ofd", SealPackage()));
+ Text(zip, "Doc_0/Signs/Sign_1/Signature.xml", $"""<?xml version="1.0"?><ofd:Signature {Ns}><ofd:SignedInfo><ofd:StampAnnot ID="1" PageRef="1" Boundary="30 50 25 25"/><ofd:StampAnnot ID="2" PageRef="99" Boundary="30 50 25 25"/></ofd:SignedInfo><ofd:SignedValue>SignedValue.dat</ofd:SignedValue></ofd:Signature>""");
+ Entry(zip, "Doc_0/Signs/Sign_1/SignedValue.dat", Signature("PNG", png));
+ Text(zip, "Doc_0/Signs/Sign_2/Signature.xml", $"""<?xml version="1.0"?><ofd:Signature {Ns}><ofd:SignedInfo><ofd:StampAnnot ID="1" PageRef="1" Boundary="30 90 25 25"/></ofd:SignedInfo><ofd:SignedValue>SignedValue.dat</ofd:SignedValue></ofd:Signature>""");
+ Entry(zip, "Doc_0/Signs/Sign_2/SignedValue.dat", [0x30, 0x84, 0xFF, 0xFF, 0xFF, 0xFF, 0x16, 0x03]);
+ });
+
+ var document = OfdReader.Read(path, Path.Combine(folder, "media"));
+ var images = document.Sections.Single().Blocks.OfType<HParagraph>().SelectMany(p => p.Inlines).OfType<HImage>().ToList();
+ Assert.Equal(2, images.Count);
+
+ var office = images.Single(i => i.Anchor!.HorizontalOffset == Hwp(85));
+ Assert.Equal(Hwp(5), office.Anchor!.VerticalOffset);
+ Assert.Equal((Hwp(40), Hwp(30)), (office.Width, office.Height));
+ Assert.Equal("IN_FRONT_OF_TEXT", office.Anchor!.Wrap);
+ // The OFD seal is drawn: a transparent picture at its own size with the red oval on it.
+ using (var drawn = new MagickImage(office.Path))
+ {
+ Assert.Equal(MagickFormat.Png, drawn.Format);
+ Assert.Equal(480u, drawn.Width); // 40 mm at 12 pixels per mm
+ using var pixels = drawn.GetPixels();
+ var colours = pixels.ToByteArray(PixelMapping.RGBA)!;
+ var red = 0;
+ var clear = 0;
+ for (var i = 0; i < colours.Length; i += 4)
+ {
+ if (colours[i + 3] > 200 && colours[i] > 200 && colours[i + 1] < 80)
+ red++;
+ else if (colours[i + 3] == 0)
+ clear++;
+ }
+ Assert.True(red > 2000, $"{red} red pixels");
+ Assert.True(clear > colours.Length / 4 / 2, "the seal is drawn on a transparent background");
+ }
+
+ var seller = images.Single(i => i.Anchor!.HorizontalOffset == Hwp(30));
+ Assert.Equal(Hwp(50), seller.Anchor!.VerticalOffset);
+ Assert.Equal(File.ReadAllBytes(Path.Combine(folder, "seal.png")), File.ReadAllBytes(seller.Path));
+ }
+
+ /// <summary>
+ /// A sales list (销货清单) as tax writers draw it: rules between the columns only, so each column is one cell with
+ /// all rows; the subtotal row (小计) at the bottom of the first column and its amount at the bottom of another.
+ /// </summary>
+ [Fact]
+ public async Task Columns_of_a_list_keep_their_rows_level_and_the_page_its_height()
+ {
+ var template = new StringBuilder();
+ void Rule(double x0, double y0, double x1, double y1) =>
+ template.Append($"""<ofd:PathObject ID="1" Boundary="{x0} {y0} {Math.Max(1, x1 - x0)} {Math.Max(1, y1 - y0)}"><ofd:AbbreviatedData>M 0 0 L {x1 - x0} {y1 - y0}</ofd:AbbreviatedData></ofd:PathObject>""");
+ Rule(5, 30, 205, 30);
+ Rule(5, 37, 205, 37);
+ Rule(5, 110, 205, 110);
+ foreach (var x in new[] { 5.0, 15, 80, 140, 205 })
+ Rule(x, 30, x, 110);
+ template.Append(TextObject("序号", 6, 35, width: 8)).Append(TextObject("项目名称", 40, 35, width: 20))
+ .Append(TextObject("金额", 100, 35, width: 10)).Append(TextObject("税额", 160, 35, width: 10))
+ .Append(TextObject("小计", 6, 105, width: 8));
+ var page = new StringBuilder();
+ for (var row = 0; row < 3; row++)
+ {
+ var y = 43 + 7 * row;
+ page.Append(TextObject($"{row + 1}", 9, y, width: 3)).Append(TextObject("*餐饮服务*餐费", 16, y, width: 40))
+ .Append(TextObject("100.00", 125, y, width: 12)).Append(TextObject("6.00", 195, y, width: 8));
+ }
+ page.Append(TextObject("¥300.00", 122, 105.2, width: 14)).Append(TextObject("¥18.00", 192, 105.2, width: 12));
+ // Under the frame, right before the page's end: it stays on the page.
+ page.Append(TextObject("开票人:张三", 10, 136, width: 30));
+
+ var folder = fx.NewFolder();
+ var path = MakeOfd(folder, page.ToString(), template.ToString());
+ var document = OfdReader.Read(path, Path.Combine(folder, "media"));
+ var table = document.Sections.Single().Blocks.OfType<HTable>().Single();
+ Assert.True(table.Tight);
+ var columns = table.Rows[1].Cells;
+ Assert.Equal(4, columns.Count);
+
+ // Every column starts its first row at the same height and steps down the same way, so 3 and 100.00 and the
+ // subtotal and its amount stay level.
+ double Position(HCell cell, int paragraph) => cell.CellMargin!.Value.Top + cell.Blocks.OfType<HParagraph>().Take(paragraph + 1)
+ .Sum(p => p.Format.Before!.Value + p.Format.LineSpacing!.Value.Value) - cell.Blocks.OfType<HParagraph>().ElementAt(paragraph).Format.LineSpacing!.Value.Value;
+ Assert.All(columns, c => Assert.Equal(HVerticalAlign.Top, c.VerticalAlign));
+ var firstRow = columns.Select(c => Position(c, 0)).ToList();
+ Assert.All(firstRow, p => Assert.InRange(p, firstRow[0] - Hwp(0.3), firstRow[0] + Hwp(0.3)));
+ Assert.InRange(Position(columns[0], 3), Position(columns[2], 3) - Hwp(0.5), Position(columns[2], 3) + Hwp(0.5)); // 小计 | ¥300.00
+
+ // HWPX: no space under the table and no empty line of its own, so the last line does not go to a new page.
+ var job = await fx.ConvertAsync([path], new Preset { TargetFormat = "hwpx" });
+ Assert.Equal(JobState.Completed, job.State);
+ using (var zip = ZipFile.OpenRead(job.Outputs.Single()))
+ {
+ var section = new StreamReader(zip.GetEntry("Contents/section0.xml")!.Open()).ReadToEnd();
+ Assert.Contains("<hp:outMargin left=\"0\" right=\"0\" top=\"0\" bottom=\"0\"/><hp:inMargin", section);
+ }
+ // DOCX: the cells' top padding is written.
+ job = await fx.ConvertAsync([path], new Preset { TargetFormat = "docx" });
+ using (var zip = ZipFile.OpenRead(job.Outputs.Single()))
+ Assert.Contains("<w:tcMar><w:top ", new StreamReader(zip.GetEntry("word/document.xml")!.Open()).ReadToEnd());
}
// ───────────────────────── Hostile and refused packages ─────────────────────────