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.

21.0 KB
Raw Blame
// Spreadsheets and presentations without Excel, PowerPoint or LibreOffice: XLSX / CSV are read in-process (values
// displayed like Excel shows them), converted to each other, and XLSX / CSV / PPTX become HWPX (and through rhwp,
// PDF and images). Test files are generated by XlsxBuilder and PptxBuilder.

using System.Text;
using System.Xml.Linq;
using Filee.Core.Conversion;
using Filee.Core.Presets;
using Filee.Engines.Hwp.Hwpx;
using Filee.Engines.Office.Sheets;
using ImageMagick;
using static Filee.Engines.Tests.HwpxAssert;
using static Filee.Engines.Tests.XlsxBuilder;

namespace Filee.Engines.Tests;

public class OfficeTests(EngineFixture fx) : IClassFixture<EngineFixture>
{
    /// <summary>Only engines that ship with the app (or run in-process): no Pandoc or LibreOffice.</summary>
    private static readonly string[] OptionalEngines = ["pandoc", "libreoffice"];

    private RoutePlanner BuiltInPlanner(params string[] assumeInstalled) =>
        new ConverterCatalog(fx.Converters.Where(c => !OptionalEngines.Contains(c.Id))) { Priority = fx.Catalog.Priority }
            .CreatePlanner(assumeInstalled);

    private async Task<IReadOnlyList<string>> ConvertAsync(string input, string target)
    {
        var job = await fx.ConvertAsync([input], new Preset { TargetFormat = target });
        Assert.True(job.State == JobState.Completed, string.Join("; ", job.Files.Select(f => $"{f.ErrorKey} {f.ErrorDetail}")));
        return [.. job.Outputs];
    }

    /// <summary>
    /// "매출": merged title, frozen header rows, number / date / percent formats, a formula, a boolean and an inline
    /// string; "메모": a line break and a General number; "넓은 표": too wide for a portrait page; plus a hidden sheet.
    /// </summary>
    internal static string SalesWorkbook(string folder)
    {
        var xlsx = new XlsxBuilder();
        var date = new DateTime(2026, 10, 1).ToOADate();
        xlsx.Sheet("매출",
            Row(1, xlsx.Text("A1", "지점별 매출", Header)) +
            Row(2, xlsx.Text("A2", "지점", Header), xlsx.Text("B2", "매출", Header), xlsx.Text("C2", "일자", Header), xlsx.Text("D2", "성장률", Header)) +
            Row(3, xlsx.Text("A3", "서울 강남"), Number("B3", 1350000, Won), Number("C3", date, Date), Number("D3", 0.128, Percent)) +
            Row(4, xlsx.Text("A4", "부산 서면"), Number("B4", 870000, Won), Number("C4", date + 1, Date), Number("D4", 0.09, Percent)) +
            Row(5, xlsx.Text("A5", "합계"), $"<c r=\"B5\" s=\"{Total}\"><f>SUM(B3:B4)</f><v>2220000</v></c>",
                "<c r=\"C5\" t=\"b\"><v>1</v></c>", "<c r=\"D5\" t=\"inlineStr\"><is><t>메모, \"따옴표\"</t></is></c>"),
            before: "<sheetViews><sheetView workbookViewId=\"0\"><pane ySplit=\"2\" topLeftCell=\"A3\" activePane=\"bottomLeft\" state=\"frozen\"/></sheetView></sheetViews>" +
                    "<cols><col min=\"1\" max=\"1\" width=\"14\" customWidth=\"1\"/><col min=\"2\" max=\"4\" width=\"12\" customWidth=\"1\"/></cols>",
            after: "<mergeCells count=\"1\"><mergeCell ref=\"A1:D1\"/></mergeCells>");
        xlsx.Sheet("메모", Row(1, xlsx.Text("A1", "첫 줄\n둘째 줄")) + Row(2, Number("A2", 3.5)));
        xlsx.Sheet("비밀", Row(1, xlsx.Text("A1", "보이면 안 됨")), hidden: true);
        xlsx.Sheet("넓은 표",
            Row(1, [.. Enumerable.Range(0, 12).Select(c => xlsx.Text($"{(char)('A' + c)}1", $"항목 {c + 1}"))]),
            before: "<cols><col min=\"1\" max=\"12\" width=\"12\" customWidth=\"1\"/></cols>");
        return xlsx.Save(Path.Combine(folder, "매출보고.xlsx"));
    }

    // ───────────────────────── Spreadsheets ─────────────────────────

    [Fact]
    public void Xlsx_values_and_styles_are_read_like_excel_shows_them()
    {
        var book = XlsxReader.Read(SalesWorkbook(fx.NewFolder()));

        Assert.Equal(["매출", "메모", "넓은 표"], book.Sheets.Select(s => s.Name)); // the hidden sheet is left out
        var sales = book.Sheets[0];
        Assert.Equal("1,350,000원", sales.Get(2, 1)!.Text);
        Assert.True(sales.Get(2, 1)!.IsNumber);
        Assert.Equal("2026-10-01", sales.Get(2, 2)!.Text);
        Assert.Equal("12.8%", sales.Get(2, 3)!.Text);
        Assert.Equal("2,220,000원", sales.Get(4, 1)!.Text); // cached formula result
        Assert.Equal("TRUE", sales.Get(4, 2)!.Text);
        Assert.Equal("메모, \"따옴표\"", sales.Get(4, 3)!.Text);

        var header = sales.Get(1, 0)!.Style;
        Assert.True(header.Bold);
        Assert.Equal("#FFFFFF", header.Color);
        Assert.Equal("#1F4E79", header.Fill);
        Assert.Equal(CellAlign.Center, header.Align);
        Assert.Equal("thin", header.Bottom.Style);
        var total = sales.Get(4, 1)!.Style;
        Assert.Equal("#C00000", total.Color);
        Assert.True(total.Top.IsVisible);

        Assert.Equal(new CellRange(0, 0, 0, 3), Assert.Single(sales.Merges));
        Assert.Equal(2, sales.FrozenRows);
        Assert.Equal(14, sales.ColumnWidth(0));
        Assert.Equal(12, sales.ColumnWidth(3));

        var memo = book.Sheets[1];
        Assert.Equal("첫 줄\n둘째 줄", memo.Get(0, 0)!.Text);
        Assert.Equal("3.5", memo.Get(1, 0)!.Text);
    }

    [Fact]
    public async Task Xlsx_to_csv_writes_one_file_per_sheet_for_excel()
    {
        var outputs = await ConvertAsync(SalesWorkbook(fx.NewFolder()), "csv");

        Assert.Equal(["매출보고_매출.csv", "매출보고_메모.csv", "매출보고_넓은 표.csv"], outputs.Select(Path.GetFileName));
        var bytes = await File.ReadAllBytesAsync(outputs[0], TestContext.Current.CancellationToken);
        Assert.Equal([0xEF, 0xBB, 0xBF], bytes[..3]); // Excel needs the BOM to read UTF-8
        Assert.Equal(
            "지점별 매출,,,\r\n" +
            "지점,매출,일자,성장률\r\n" +
            "서울 강남,\"1,350,000원\",2026-10-01,12.8%\r\n" +
            "부산 서면,\"870,000원\",2026-10-02,9.0%\r\n" +
            "합계,\"2,220,000원\",TRUE,\"메모, \"\"따옴표\"\"\"\r\n",
            Encoding.UTF8.GetString(bytes, 3, bytes.Length - 3));
    }

    [Fact]
    public async Task Csv_to_xlsx_and_back_keeps_every_value()
    {
        var dir = fx.NewFolder();
        const string Csv = "이름,금액,메모\r\n김민지,1200,\"줄\n바꿈\"\r\n\"Lee, J\",3.5,\"\"\"인용\"\"\"\r\n";
        var csv = Path.Combine(dir, "명단.csv");
        await File.WriteAllTextAsync(csv, Csv, TestContext.Current.CancellationToken);

        var xlsx = Assert.Single(await ConvertAsync(csv, "xlsx"));
        var sheet = Assert.Single(XlsxReader.Read(xlsx).Sheets);
        Assert.Equal("김민지", sheet.Get(1, 0)!.Text);
        Assert.Equal("1200", sheet.Get(1, 1)!.Text);
        Assert.True(sheet.Get(1, 1)!.IsNumber); // stored as a number, so Excel can calculate with it
        Assert.Equal("줄\n바꿈", sheet.Get(1, 2)!.Text);
        Assert.Equal("Lee, J", sheet.Get(2, 0)!.Text);

        File.Move(xlsx, Path.Combine(dir, "사본.xlsx"));
        var back = Assert.Single(await ConvertAsync(Path.Combine(dir, "사본.xlsx"), "csv"));
        Assert.Equal(Csv, (await File.ReadAllTextAsync(back, TestContext.Current.CancellationToken)).TrimStart(''));
    }

    [Fact]
    public async Task Csv_from_korean_excel_is_read_as_cp949_with_its_delimiter()
    {
        Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
        var csv = Path.Combine(fx.NewFolder(), "점수.csv");
        await File.WriteAllBytesAsync(csv, Encoding.GetEncoding(949).GetBytes("이름;점수\r\n홍길동;90\r\n"), TestContext.Current.CancellationToken);

        var sheet = Assert.Single(CsvFormat.Read(csv).Sheets);

        Assert.Equal("홍길동", sheet.Get(1, 0)!.Text);
        Assert.Equal("90", sheet.Get(1, 1)!.Text);
    }

    [Fact]
    public void Csv_rows_that_fail_part_way_or_meet_a_read_only_file_leave_it_as_it_was()
    {
        var dir = fx.NewFolder();
        var csv = Path.Combine(dir, "rows.csv");
        File.WriteAllText(csv, "kept");

        Assert.Throws<IOException>(() => CsvFormat.WriteRows(FailingRows(), csv));
        Assert.Equal("kept", File.ReadAllText(csv));
        Assert.Equal([csv], Directory.GetFiles(dir));

        File.SetAttributes(csv, FileAttributes.ReadOnly);
        try
        {
            Assert.Throws<UnauthorizedAccessException>(() => CsvFormat.WriteRows([["a"]], csv));
            Assert.Equal("kept", File.ReadAllText(csv));
            Assert.Equal([csv], Directory.GetFiles(dir));
        }
        finally
        {
            File.SetAttributes(csv, FileAttributes.Normal);
        }

        CsvFormat.WriteRows([["a", "b,c"]], csv);
        Assert.Equal([0xEF, 0xBB, 0xBF, .. Encoding.UTF8.GetBytes("a,\"b,c\"\r\n")], File.ReadAllBytes(csv));
        Assert.Equal([csv], Directory.GetFiles(dir));

        static IEnumerable<IEnumerable<string>> FailingRows()
        {
            yield return ["a", "b"];
            throw new IOException("the second row failed");
        }
    }

    [Fact]
    public void Csv_rows_that_fail_keep_their_error_when_the_partial_file_cannot_be_deleted()
    {
        var dir = fx.NewFolder();
        var csv = Path.Combine(dir, "rows.csv");
        File.WriteAllText(csv, "kept");
        FileStream? held = null;
        try
        {
            var error = Assert.Throws<IOException>(() => CsvFormat.WriteRows(Rows(), csv));
            Assert.Equal("the second row failed", error.Message);
            Assert.Equal("kept", File.ReadAllText(csv));
        }
        finally
        {
            held?.Dispose();
            if (!OperatingSystem.IsWindows())
                File.SetUnixFileMode(dir, UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute);
            foreach (var partial in Directory.GetFiles(dir, "*.filee-tmp"))
                File.Delete(partial);
        }

        IEnumerable<IEnumerable<string>> Rows()
        {
            yield return ["a"];
            // From here deleting the partial file fails: on Windows while a handle without delete sharing is open,
            // on Unix in a folder that can't be written.
            if (OperatingSystem.IsWindows())
                held = new FileStream(Assert.Single(Directory.GetFiles(dir, "*.filee-tmp")), FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
            else
                File.SetUnixFileMode(dir, UnixFileMode.UserRead | UnixFileMode.UserExecute);
            throw new IOException("the second row failed");
        }
    }

    [Fact]
    public async Task Xlsx_to_hwpx_makes_a_table_per_sheet()
    {
        var hwpx = Assert.Single(await ConvertAsync(SalesWorkbook(fx.NewFolder()), "hwpx"));

        ValidPackage(hwpx, expectImages: 0);
        Assert.Equal(3, (int)Xml(hwpx, "Contents/header.xml").Attribute("secCnt")!);
        var sales = Xml(hwpx);
        var table = sales.Descendants(Hp + "tbl").Single();
        Assert.Equal(("5", "4", "1"), ((string?)table.Attribute("rowCnt"), (string?)table.Attribute("colCnt"), (string?)table.Attribute("repeatHeader")));
        var title = sales.Descendants(Hp + "tc").First(c => c.Value.Contains("지점별 매출"));
        Assert.Equal("4", (string?)title.Element(Hp + "cellSpan")!.Attribute("colSpan"));
        // Frozen rows repeat on every page.
        Assert.Equal(2, sales.Descendants(Hp + "tr").Count(r => r.Elements(Hp + "tc").All(c => (string?)c.Attribute("header") == "1")));
        Assert.Contains("2,220,000원", sales.Value);
        Assert.Contains("faceColor=\"#1F4E79\"", Xml(hwpx, "Contents/header.xml").ToString());

        // Portrait for the narrow sheets, landscape for the wide one.
        string Orientation(int section) => (string)Xml(hwpx, $"Contents/section{section}.xml").Descendants(Hp + "pagePr").Single().Attribute("landscape")!;
        Assert.Equal(["WIDELY", "WIDELY", "NARROWLY"], new[] { 0, 1, 2 }.Select(Orientation));
        Assert.DoesNotContain("보이면 안 됨", string.Concat(new[] { 0, 1, 2 }.Select(i => Xml(hwpx, $"Contents/section{i}.xml").Value)));

        RenderWithRhwp(fx, hwpx, "xlsx-sales");
    }

    [Fact]
    public void Print_titles_name_the_rows_they_repeat()
    {
        Assert.Equal((2, 3), XlsxReader.PrintTitleRows("'공사 내역서'!$3:$4"));
        Assert.Equal((0, 1), XlsxReader.PrintTitleRows("Sheet1!$A:$B,Sheet1!$1:$2"));
        Assert.Null(XlsxReader.PrintTitleRows("Sheet1!$A:$B")); // columns only
    }

    [Fact]
    public async Task Rows_to_repeat_at_the_top_repeat_on_every_page_of_a_pdf_bound_table()
    {
        // Issue #407: a bill of quantities with a title, then two heading rows set as "Rows to repeat at top" and a
        // page break. The title comes once; the headings start every page's table.
        var xlsx = new XlsxBuilder();
        xlsx.Sheet("숨김", Row(1, xlsx.Text("A1", "x")), hidden: true); // hidden sheets still count in localSheetId
        var rows = Row(1, xlsx.Text("A1", "공사 내역서", Header)) + Row(2, xlsx.Text("A2", "현장: 서울")) +
                   Row(3, xlsx.Text("A3", "품명", Header), xlsx.Text("B3", "금액", Header)) +
                   Row(4, xlsx.Text("A4", "규격", Header), xlsx.Text("B4", "원", Header)) +
                   string.Concat(Enumerable.Range(5, 40).Select(r => Row(r, xlsx.Text($"A{r}", $"자재 {r}"), Number($"B{r}", r * 1000))));
        xlsx.Sheet("내역", rows, after: "<rowBreaks count=\"1\" manualBreakCount=\"1\"><brk id=\"24\" max=\"16383\" man=\"1\"/></rowBreaks>");
        xlsx.DefinedNames = "<definedNames><definedName name=\"_xlnm.Print_Titles\" localSheetId=\"1\">내역!$3:$4</definedName></definedNames>";
        var path = xlsx.Save(Path.Combine(fx.NewFolder(), "내역서.xlsx"));

        Assert.Equal((2, 3), Assert.Single(XlsxReader.Read(path).Sheets).TitleRows);
        var tables = SheetDocument.Build(XlsxReader.Read(path)).Sections.Single().Blocks.OfType<HTable>().ToList();

        Assert.Equal(3, tables.Count); // the title, then one table per printed page
        Assert.Equal(2, tables[0].Rows.Count);
        Assert.DoesNotContain(tables[0].Rows, r => r.Header);
        foreach (var page in tables.Skip(1))
            Assert.Equal([true, true, false], page.Rows.Take(3).Select(r => r.Header));
        Assert.Equal(2 + 20, tables[1].Rows.Count); // rows 5-24, then the break
        Assert.Equal(2 + 20, tables[2].Rows.Count); // rows 25-44
        Assert.True(tables[2].PageBreakBefore);
    }

    // ───────────────────────── Presentations ─────────────────────────

    private static byte[] Png()
    {
        using var image = new MagickImage(MagickColors.MediumPurple, 160, 90);
        return image.ToByteArray(MagickFormat.Png);
    }

    [Fact]
    public async Task Pptx_slides_become_pages_with_their_objects_in_place()
    {
        var pptx = new PptxBuilder();
        var chart = pptx.Image(Png());
        pptx.Slide(pptx.Title("2026년 사업 보고"));
        pptx.Slide(
            pptx.Title("다음 분기 계획") +
            pptx.Body(("매출 증가", 0), ("지점 확대", 1)) +
            pptx.Shape("roundRect", 838200, 4400000, 3000000, 1500000, "#7F77DD", "강조") +
            pptx.Picture(chart, 8000000, 1900000, 3000000, 1687500) +
            pptx.Table(4000000, 4400000, 1200000, 370840, ["지점", "매출"], ["강남", "16.2억"], ["서면", "8.7억"]) +
            pptx.Group(6000000, 4000000, 2000000, 1000000, 0.5, pptx.Shape("ellipse", 0, 0, 4000000, 2000000, "#1D9E75", "단계 1")),
            background: "#1F1E2D");
        var path = pptx.Save(Path.Combine(fx.NewFolder(), "계획.pptx"));

        var hwpx = Assert.Single(await ConvertAsync(path, "hwpx"));

        ValidPackage(hwpx, expectImages: 1);
        var section = Xml(hwpx);
        // The page is the slide (EMU / 127 = HWPUNIT), one page per slide; 한글 stores it as a turned portrait sheet.
        var pagePr = section.Descendants(Hp + "pagePr").Single();
        Assert.Equal((54000, 96000, "NARROWLY"), ((int)pagePr.Attribute("width")!, (int)pagePr.Attribute("height")!, (string?)pagePr.Attribute("landscape")));
        Assert.Single(section.Elements(Hp + "p"), p => (string?)p.Attribute("pageBreak") == "1");

        // Title placeholders take position from the master and centring from its title style.
        var titleBox = section.Descendants(Hp + "rect").First(r => r.Value.Contains("2026년 사업 보고"));
        var position = titleBox.Element(Hp + "pos")!;
        Assert.Equal(("6600", "2875"), ((string?)position.Attribute("horzOffset"), (string?)position.Attribute("vertOffset")));
        var titleParagraph = ParagraphWith(section, "2026년 사업 보고");
        Assert.Equal("CENTER", (string?)HeadItem(hwpx, "paraPr", (string)titleParagraph.Attribute("paraPrIDRef")!).Element(Hh + "align")!.Attribute("horizontal"));

        // Body placeholders get the master's bullets per level.
        Assert.StartsWith("• ", ParagraphWith(section, "매출 증가").Value);
        Assert.StartsWith("– ", ParagraphWith(section, "지점 확대").Value);

        // Shapes keep their outline around the text; group children are scaled into the slide.
        Assert.Equal("17", (string?)section.Descendants(Hp + "rect").Single(r => r.Element(Hp + "drawText")?.Value.Contains("강조") == true).Attribute("ratio"));
        var ellipse = section.Descendants(Hp + "ellipse").Single();
        Assert.Contains("단계 1", ellipse.Element(Hp + "drawText")!.Value);
        Assert.Equal("15748", (string?)ellipse.Element(Hp + "sz")!.Attribute("width"));
        Assert.Equal("47244", (string?)ellipse.Element(Hp + "pos")!.Attribute("horzOffset"));

        // Table with the default style: accent 1 header row.
        var table = section.Descendants(Hp + "tbl").Single();
        Assert.Equal("3", (string?)table.Attribute("rowCnt"));
        Assert.Contains("faceColor=\"#4472C4\"", Xml(hwpx, "Contents/header.xml").ToString());

        // Master decoration on both slides, background on the second.
        var xml = section.ToString(SaveOptions.DisableFormatting);
        Assert.Equal(2, CountOf(xml, $"faceColor=\"{PptxBuilder.BarColor}\""));
        Assert.Equal(1, CountOf(xml, "faceColor=\"#1F1E2D\""));

        if (RenderWithRhwp(fx, hwpx, "pptx-slides") is { } pages)
            Assert.Equal(2, pages);
    }

    private static int CountOf(string text, string value)
    {
        var count = 0;
        for (var i = text.IndexOf(value, StringComparison.Ordinal); i >= 0; i = text.IndexOf(value, i + 1, StringComparison.Ordinal))
            count++;
        return count;
    }

    [Fact]
    public async Task Pptx_to_pdf_without_powerpoint()
    {
        Assert.SkipUnless(fx.Converters.Any(c => c.Id == "rhwp" && fx.Catalog.StatusOf(c).IsAvailable), "rhwp not found");
        var pptx = new PptxBuilder();
        pptx.Slide(pptx.Title("첫 장"));
        pptx.Slide(pptx.Title("둘째 장"));
        pptx.Slide(pptx.Title("셋째 장"));
        var path = pptx.Save(Path.Combine(fx.NewFolder(), "세 장.pptx"));

        var pdf = Assert.Single(await ConvertAsync(path, "pdf"));

        // PDFium (for counting pages) is only known to the platform analyzer on desktop and mobile systems.
        if (OperatingSystem.IsWindows() || OperatingSystem.IsMacOS() || OperatingSystem.IsLinux())
            Assert.Equal(3, PDFtoImage.Conversion.GetPageCount(await File.ReadAllBytesAsync(pdf, TestContext.Current.CancellationToken)));
    }

    // ───────────────────────── Routes ─────────────────────────

    [Theory]
    [InlineData("xlsx", "csv", "spreadsheet")]
    [InlineData("csv", "xlsx", "spreadsheet")]
    [InlineData("xlsx", "hwpx", "hwpx-writer")]
    [InlineData("csv", "hwpx", "hwpx-writer")]
    [InlineData("pptx", "hwpx", "hwpx-writer")]
    [InlineData("xlsx", "pdf", "hwpx-writer,rhwp")]
    [InlineData("csv", "pdf", "hwpx-writer,rhwp")]
    [InlineData("pptx", "pdf", "hwpx-writer,rhwp")]
    [InlineData("docx", "pdf", "hwpx-writer,rhwp")]
    public void Office_files_convert_without_optional_engines(string from, string to, string engines)
    {
        Assert.Equal(engines.Split(','), BuiltInPlanner("rhwp").Plan(from, to)!.Steps.Select(s => s.Converter.Id));
        // Built-in conversions win even when LibreOffice is installed, except presentations → PDF, which LibreOffice
        // lays out like PowerPoint (Settings → Engines, on by default; see LibreOfficeRouteTests).
        var withLibreOffice = fx.Catalog.CreatePlanner(["libreoffice", "rhwp"]).Plan(from, to)!.Steps;
        if (from == "pptx" && to == "pdf")
            Assert.Equal("libreoffice", Assert.Single(withLibreOffice).Converter.Id);
        else
            Assert.DoesNotContain(withLibreOffice, s => s.Converter.Id == "libreoffice");
    }

    [Theory]
    [InlineData("doc", "pdf")]
    [InlineData("ppt", "pdf")]
    [InlineData("docx", "odt")]
    public void Rare_formats_need_libreoffice(string from, string to)
    {
        Assert.Null(BuiltInPlanner("rhwp").Plan(from, to));
        if (fx.Catalog.CreatePlanner(["libreoffice", "rhwp"]).Plan(from, to) is { } route)
            Assert.Contains(route.Steps, s => s.Converter.Id == "libreoffice");
    }
}