From 44eea93284336888399f833b7387acf98bd86af2 Mon Sep 17 00:00:00 2001 From: henry3260 Date: Sun, 15 Nov 2026 19:43:37 +0800 Subject: [PATCH 1/4] fix(go): honor fit-to-page in the XLSX text renderer Worksheets that request fit-to-page were split into fixed nine-column groups and paginated at a fixed font size, so a sheet meant for one page produced several. Keep the columns within the requested page width and shrink the text to the largest zoom at which it fits the requested page height, as LibreOffice Calc does in ScPrintFunc::CalcZoom. --- minipdf-go/office.go | 58 ++++++++++++++++------ minipdf-go/office_test.go | 100 ++++++++++++++++++++++++++++++++++++-- minipdf-go/xlsx.go | 46 ++++++++++++++---- 3 files changed, 177 insertions(+), 27 deletions(-) diff --git a/minipdf-go/office.go b/minipdf-go/office.go index f08d3beb..33683cf9 100644 --- a/minipdf-go/office.go +++ b/minipdf-go/office.go @@ -138,30 +138,61 @@ func renderTextPages(pages []textPage, options ConversionOptions) []byte { if options.Margins != nil { margins = *options.Margins } - addTextPages(document, sourcePage.lines, pageSize, margins, sourcePage.noWrap, sourcePage.skipEmpty) + addTextPages(document, sourcePage.lines, pageSize, margins, sourcePage.noWrap, sourcePage.skipEmpty, 0) } return document.BytesWithOptions(PDFSaveOptions{Compress: options.Compress}) } -func addTextPages(document *PDFDocument, lines []string, pageSize PageSize, margins Margins, noWrap, skipEmpty bool) { +// minimumTextFitZoom is the lowest zoom percentage LibreOffice Calc applies +// when it fits a sheet to a page count (ZOOM_MIN in ScPrintFunc::CalcZoom). +const minimumTextFitZoom = 10 + +// addTextPages lays lines out as pages of text. A positive fitHeight shrinks +// the text until it fits that many pages. +func addTextPages(document *PDFDocument, lines []string, pageSize PageSize, margins Margins, noWrap, skipEmpty bool, fitHeight int) { const ( - fontSize = 11.0 - leading = 15.0 + baseFontSize = 11.0 + baseLeading = 15.0 ) if margins == (Margins{}) { margins = Margins{Left: 54, Top: 54, Right: 54, Bottom: 54} } - wrapped := make([]string, 0, len(lines)) - for _, line := range lines { - if noWrap { - wrapped = append(wrapped, line) - } else { - wrapped = append(wrapped, wrapText(line, textCharactersPerLine(pageSize, margins))...) + wrapAt := func(zoom int) []string { + wrapped := make([]string, 0, len(lines)) + for _, line := range lines { + if noWrap { + wrapped = append(wrapped, line) + } else { + wrapped = append(wrapped, wrapText(line, textCharactersPerLine(pageSize, margins, baseFontSize*float64(zoom)/100))...) + } } + if len(wrapped) == 0 { + wrapped = append(wrapped, "") + } + return wrapped } - if len(wrapped) == 0 { - wrapped = append(wrapped, "") + zoom := 100 + if fitHeight > 0 { + // Like ScPrintFunc::CalcZoom, keep 100% when the content already fits + // and otherwise search for the largest zoom that does. + available := float64(fitHeight) * (pageSize.Height - margins.Top - margins.Bottom) + fits := func(zoom int) bool { + return float64(len(wrapAt(zoom)))*baseLeading*float64(zoom)/100 <= available + } + if !fits(zoom) { + zoom = minimumTextFitZoom + for tooLarge := 100; tooLarge-zoom > 1; { + if middle := (zoom + tooLarge) / 2; fits(middle) { + zoom = middle + } else { + tooLarge = middle + } + } + } } + wrapped := wrapAt(zoom) + fontSize := baseFontSize * float64(zoom) / 100 + leading := baseLeading * float64(zoom) / 100 var page *PDFPage if !skipEmpty { @@ -183,8 +214,7 @@ func addTextPages(document *PDFDocument, lines []string, pageSize PageSize, marg } } -func textCharactersPerLine(pageSize PageSize, margins Margins) int { - const fontSize = 11.0 +func textCharactersPerLine(pageSize PageSize, margins Margins, fontSize float64) int { if margins == (Margins{}) { margins = Margins{Left: 54, Top: 54, Right: 54, Bottom: 54} } diff --git a/minipdf-go/office_test.go b/minipdf-go/office_test.go index 2ac3b0d6..6483a73f 100644 --- a/minipdf-go/office_test.go +++ b/minipdf-go/office_test.go @@ -5,6 +5,7 @@ import ( "bytes" "encoding/xml" "errors" + "fmt" "strings" "testing" ) @@ -319,7 +320,7 @@ func TestTextPaginationPreservesSpacingWhenSkippingEmptyPages(t *testing.T) { lines[0], lines[100], lines[152] = "First", "Middle", "Last" for _, skipEmpty := range []bool{false, true} { document := NewPDFDocument() - addTextPages(document, lines, PageSizeA4, Margins{}, true, skipEmpty) + addTextPages(document, lines, PageSizeA4, Margins{}, true, skipEmpty, 0) pdf := document.Bytes() wantPages := 11 if skipEmpty { @@ -541,6 +542,97 @@ func TestConvertXLSXPaginatesSingleColumnTextOverflow(t *testing.T) { } } +func fitToPageWorksheet(sheetProperties, pageSetup string, rows, columns int) string { + var worksheet strings.Builder + worksheet.WriteString(`` + sheetProperties + ``) + for row := 1; row <= rows; row++ { + fmt.Fprintf(&worksheet, ``, row) + for column := 0; column < columns; column++ { + fmt.Fprintf(&worksheet, `R%dC%d`, 'A'+column, row, row, column+1) + } + worksheet.WriteString(``) + } + worksheet.WriteString(`` + pageSetup + ``) + return worksheet.String() +} + +func TestConvertXLSXFitsWorksheetToPage(t *testing.T) { + const fitToPage = `` + tests := []struct { + name string + sheetProperties string + pageSetup string + pages int + firstPage []string + unscaled bool + }{ + { + name: "without fit to page columns and rows split", + pages: 4, firstPage: []string{"R1C9"}, unscaled: true, + }, + { + name: "default fit is one page wide and one page tall", sheetProperties: fitToPage, + pageSetup: ``, + pages: 1, firstPage: []string{"R1C1", "R1C12", "R60C12"}, + }, + { + name: "automatic height keeps every column on each page", sheetProperties: fitToPage, + pageSetup: ``, + pages: 2, firstPage: []string{"R1C1", "R1C12"}, unscaled: true, + }, + { + name: "page counts apply in both directions", sheetProperties: fitToPage, + pageSetup: ``, + pages: 2, firstPage: []string{"R1C6", "R60C6"}, + }, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + input := officePackageBytes(t, map[string]string{ + "xl/workbook.xml": ``, + "xl/worksheets/sheet1.xml": fitToPageWorksheet(test.sheetProperties, test.pageSetup, 60, 12), + }) + + pdf, err := ConvertBytesToPDF(input) + if err != nil { + t.Fatal(err) + } + if pages := bytes.Count(pdf, []byte("/Type /Page ")); pages != test.pages { + t.Fatalf("PDF page count = %d, want %d", pages, test.pages) + } + firstPage := pdf[:bytes.Index(pdf, []byte("endstream"))] + for _, text := range test.firstPage { + if !bytes.Contains(firstPage, []byte(text)) { + t.Errorf("first page does not contain %q", text) + } + } + if unscaled := bytes.Contains(pdf, []byte("/F1 11 Tf")); unscaled != test.unscaled { + t.Errorf("uses unscaled font size = %t, want %t", unscaled, test.unscaled) + } + }) + } +} + +func TestConvertXLSXFitToPageWrapsLongText(t *testing.T) { + input := officePackageBytes(t, map[string]string{ + "xl/workbook.xml": ``, + "xl/worksheets/sheet1.xml": `` + + `` + strings.Repeat("word ", 1200) + + ``, + }) + + pdf, err := ConvertBytesToPDF(input) + if err != nil { + t.Fatal(err) + } + if words := bytes.Count(pdf, []byte("word")); words != 1200 { + t.Fatalf("rendered word count = %d, want 1200", words) + } + if pages := bytes.Count(pdf, []byte("/Type /Page ")); pages != 1 { + t.Fatalf("PDF page count = %d, want 1", pages) + } +} + func TestExtractWorksheetPreservesSparseRows(t *testing.T) { worksheet := []byte(`` + `First` + @@ -548,7 +640,7 @@ func TestExtractWorksheetPreservesSparseRows(t *testing.T) { `Tenth` + ``) - lines, _, err := extractWorksheet(worksheet, nil) + lines, _, _, err := extractWorksheet(worksheet, nil) if err != nil { t.Fatal(err) } @@ -568,7 +660,7 @@ func TestExtractWorksheetPreservesSparseColumns(t *testing.T) { `Far` + ``) - lines, _, err := extractWorksheet(worksheet, nil) + lines, _, _, err := extractWorksheet(worksheet, nil) if err != nil { t.Fatal(err) } @@ -582,7 +674,7 @@ func TestExtractWorksheetFormatsBooleanCells(t *testing.T) { `10` + `1`) - lines, _, err := extractWorksheet(worksheet, nil) + lines, _, _, err := extractWorksheet(worksheet, nil) if err != nil { t.Fatal(err) } diff --git a/minipdf-go/xlsx.go b/minipdf-go/xlsx.go index ec250980..dec2c5d2 100644 --- a/minipdf-go/xlsx.go +++ b/minipdf-go/xlsx.go @@ -9,6 +9,13 @@ import ( "strings" ) +// worksheetFit is a worksheet's fit-to-page request. A page count of zero +// leaves that direction unconstrained. +type worksheetFit struct { + enabled bool + width, height int +} + func convertXLSX(input []byte, options ConversionOptions) ([]byte, error) { files, err := openOfficePackage(input) if err != nil { @@ -59,7 +66,7 @@ func convertXLSX(input []byte, options ConversionOptions) ([]byte, error) { if readErr != nil { return nil, readErr } - lines, pageSize, parseErr := extractWorksheet(worksheetXML, sharedStrings) + lines, pageSize, fit, parseErr := extractWorksheet(worksheetXML, sharedStrings) if parseErr != nil { return nil, fmt.Errorf("parse %s: %w", name, parseErr) } @@ -85,16 +92,27 @@ func convertXLSX(input []byte, options ConversionOptions) ([]byte, error) { break } } - for _, group := range splitWorksheetColumnGroups(lines, 9) { + // A fitted sheet keeps its columns within the requested page count + // instead of splitting them into fixed groups. + columnsPerPage := 9 + fitWidth := fit.enabled && fit.width > 0 + fitHeight := 0 + if fit.enabled { + fitHeight = fit.height + } + if fitWidth { + columnsPerPage = max(columnsPerPage, (worksheetColumnCount(lines)+fit.width-1)/fit.width) + } + for _, group := range splitWorksheetColumnGroups(lines, columnsPerPage) { overflowPages := [][]string{group} noWrap := false - if worksheetColumnCount(group) == 1 { - overflowPages = splitWorksheetTextOverflow(group, textCharactersPerLine(effectivePageSize, Margins{})) + if !fitWidth && worksheetColumnCount(group) == 1 { + overflowPages = splitWorksheetTextOverflow(group, textCharactersPerLine(effectivePageSize, Margins{}, 11)) noWrap = len(overflowPages) > 1 } for _, overflowPage := range overflowPages { overflowPage = append([]string{""}, overflowPage...) - addTextPages(document, overflowPage, effectivePageSize, Margins{}, noWrap, hasText) + addTextPages(document, overflowPage, effectivePageSize, Margins{}, noWrap, hasText, fitHeight) } } } @@ -383,9 +401,10 @@ func readSharedStrings(files officePackage) ([]string, error) { return values, nil } -func extractWorksheet(data []byte, sharedStrings []string) ([]string, PageSize, error) { +func extractWorksheet(data []byte, sharedStrings []string) ([]string, PageSize, worksheetFit, error) { decoder := xml.NewDecoder(bytes.NewReader(data)) pageSize := PageSizeA4 + fit := worksheetFit{width: 1, height: 1} var lines []string var row []string rowNumber := 0 @@ -395,7 +414,7 @@ func extractWorksheet(data []byte, sharedStrings []string) ([]string, PageSize, if err.Error() == "EOF" { break } - return nil, PageSize{}, err + return nil, PageSize{}, worksheetFit{}, err } switch element := token.(type) { case xml.StartElement: @@ -413,9 +432,12 @@ func extractWorksheet(data []byte, sharedStrings []string) ([]string, PageSize, } value, cellErr := decodeWorksheetCell(decoder, element, sharedStrings) if cellErr != nil { - return nil, PageSize{}, cellErr + return nil, PageSize{}, worksheetFit{}, cellErr } row = append(row, value) + case "pageSetUpPr": + value := attrValue(element, "fitToPage") + fit.enabled = value == "1" || value == "true" case "pageSetup": if attrValue(element, "paperSize") == "1" { pageSize = PageSizeLetter @@ -423,6 +445,12 @@ func extractWorksheet(data []byte, sharedStrings []string) ([]string, PageSize, if attrValue(element, "orientation") == "landscape" { pageSize.Width, pageSize.Height = pageSize.Height, pageSize.Width } + if pages, parseErr := strconv.Atoi(attrValue(element, "fitToWidth")); parseErr == nil && pages >= 0 { + fit.width = pages + } + if pages, parseErr := strconv.Atoi(attrValue(element, "fitToHeight")); parseErr == nil && pages >= 0 { + fit.height = pages + } } case xml.EndElement: if element.Name.Local == "row" { @@ -433,7 +461,7 @@ func extractWorksheet(data []byte, sharedStrings []string) ([]string, PageSize, } } } - return lines, pageSize, nil + return lines, pageSize, fit, nil } func worksheetColumnIndex(reference string) int { From 7ae11bc2a6ee2f28c7b8e8d1aaf3b6d98e446f08 Mon Sep 17 00:00:00 2001 From: henry3260 Date: Mon, 16 Nov 2026 04:13:42 +0800 Subject: [PATCH 2/4] fix(go): match the fit-to-page check to text pagination The fit check counted one line of leading more than the layout loop places on a page, so content that already fit was shrunk by a few percent. Count lines per page the same way the loop does, share the base font size with the worksheet overflow split, and cover the zoom bounds with tests. --- minipdf-go/office.go | 20 +++++++++++++------- minipdf-go/office_test.go | 35 +++++++++++++++++++++++++++++++++++ minipdf-go/xlsx.go | 2 +- 3 files changed, 49 insertions(+), 8 deletions(-) diff --git a/minipdf-go/office.go b/minipdf-go/office.go index 33683cf9..a26d6a4b 100644 --- a/minipdf-go/office.go +++ b/minipdf-go/office.go @@ -147,13 +147,15 @@ func renderTextPages(pages []textPage, options ConversionOptions) []byte { // when it fits a sheet to a page count (ZOOM_MIN in ScPrintFunc::CalcZoom). const minimumTextFitZoom = 10 +// Font size and line spacing of unscaled plain text pages, in points. +const ( + baseFontSize = 11.0 + baseLeading = 15.0 +) + // addTextPages lays lines out as pages of text. A positive fitHeight shrinks -// the text until it fits that many pages. +// the text, down to minimumTextFitZoom, until it fits that many pages. func addTextPages(document *PDFDocument, lines []string, pageSize PageSize, margins Margins, noWrap, skipEmpty bool, fitHeight int) { - const ( - baseFontSize = 11.0 - baseLeading = 15.0 - ) if margins == (Margins{}) { margins = Margins{Left: 54, Top: 54, Right: 54, Bottom: 54} } @@ -175,9 +177,13 @@ func addTextPages(document *PDFDocument, lines []string, pageSize PageSize, marg if fitHeight > 0 { // Like ScPrintFunc::CalcZoom, keep 100% when the content already fits // and otherwise search for the largest zoom that does. - available := float64(fitHeight) * (pageSize.Height - margins.Top - margins.Bottom) + // The layout loop below starts a line wherever the baseline is still + // above the bottom margin, so a page holds one more line than its + // height divided by the leading. + height := pageSize.Height - margins.Top - margins.Bottom fits := func(zoom int) bool { - return float64(len(wrapAt(zoom)))*baseLeading*float64(zoom)/100 <= available + linesPerPage := int(height/(baseLeading*float64(zoom)/100)) + 1 + return len(wrapAt(zoom)) <= fitHeight*linesPerPage } if !fits(zoom) { zoom = minimumTextFitZoom diff --git a/minipdf-go/office_test.go b/minipdf-go/office_test.go index 6483a73f..5ae61e69 100644 --- a/minipdf-go/office_test.go +++ b/minipdf-go/office_test.go @@ -613,6 +613,41 @@ func TestConvertXLSXFitsWorksheetToPage(t *testing.T) { } } +func TestConvertXLSXFitToPageZoomBounds(t *testing.T) { + tests := []struct { + name string + pageSetup string + rows int + pages int + fontSize string + }{ + {name: "content that already fits keeps its size", rows: 48, pages: 1, fontSize: "/F1 11 Tf"}, + {name: "one more line shrinks the text", rows: 49, pages: 1, fontSize: "/F1 10.89 Tf"}, + {name: "several pages share the height", pageSetup: ``, rows: 97, pages: 2, fontSize: "/F1 11 Tf"}, + {name: "zoom stops at the minimum", rows: 5000, pages: 11, fontSize: "/F1 1.1 Tf"}, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + input := officePackageBytes(t, map[string]string{ + "xl/workbook.xml": ``, + "xl/worksheets/sheet1.xml": fitToPageWorksheet( + ``, test.pageSetup, test.rows, 3), + }) + + pdf, err := ConvertBytesToPDF(input) + if err != nil { + t.Fatal(err) + } + if pages := bytes.Count(pdf, []byte("/Type /Page ")); pages != test.pages { + t.Errorf("PDF page count = %d, want %d", pages, test.pages) + } + if !bytes.Contains(pdf, []byte(test.fontSize)) { + t.Errorf("PDF does not use font size %q", test.fontSize) + } + }) + } +} + func TestConvertXLSXFitToPageWrapsLongText(t *testing.T) { input := officePackageBytes(t, map[string]string{ "xl/workbook.xml": ``, diff --git a/minipdf-go/xlsx.go b/minipdf-go/xlsx.go index dec2c5d2..8f4114c2 100644 --- a/minipdf-go/xlsx.go +++ b/minipdf-go/xlsx.go @@ -107,7 +107,7 @@ func convertXLSX(input []byte, options ConversionOptions) ([]byte, error) { overflowPages := [][]string{group} noWrap := false if !fitWidth && worksheetColumnCount(group) == 1 { - overflowPages = splitWorksheetTextOverflow(group, textCharactersPerLine(effectivePageSize, Margins{}, 11)) + overflowPages = splitWorksheetTextOverflow(group, textCharactersPerLine(effectivePageSize, Margins{}, baseFontSize)) noWrap = len(overflowPages) > 1 } for _, overflowPage := range overflowPages { From b37a8333080acc65bad378af83aa36bbfc9c546b Mon Sep 17 00:00:00 2001 From: henry3260 Date: Mon, 16 Nov 2026 04:38:06 +0800 Subject: [PATCH 3/4] fix(go): count fit-to-page pages like the text layout The closed-form lines-per-page count disagreed with the layout loop when the usable height is an exact multiple of the leading, so a fitted sheet on Letter or Legal paper could spill onto one page more than requested. Count pages in the fit check with the same arithmetic as the layout loop and add a Letter regression test. --- minipdf-go/office.go | 19 +++++++++++++------ minipdf-go/office_test.go | 1 + 2 files changed, 14 insertions(+), 6 deletions(-) diff --git a/minipdf-go/office.go b/minipdf-go/office.go index a26d6a4b..a2a2b590 100644 --- a/minipdf-go/office.go +++ b/minipdf-go/office.go @@ -177,13 +177,20 @@ func addTextPages(document *PDFDocument, lines []string, pageSize PageSize, marg if fitHeight > 0 { // Like ScPrintFunc::CalcZoom, keep 100% when the content already fits // and otherwise search for the largest zoom that does. - // The layout loop below starts a line wherever the baseline is still - // above the bottom margin, so a page holds one more line than its - // height divided by the leading. - height := pageSize.Height - margins.Top - margins.Bottom + // Count pages with the same arithmetic as the layout loop below, so + // the check and the layout cannot disagree about a page break. fits := func(zoom int) bool { - linesPerPage := int(height/(baseLeading*float64(zoom)/100)) + 1 - return len(wrapAt(zoom)) <= fitHeight*linesPerPage + leading := baseLeading * float64(zoom) / 100 + pages := 1 + y := pageSize.Height - margins.Top + for range wrapAt(zoom) { + if y < margins.Bottom { + pages++ + y = pageSize.Height - margins.Top + } + y -= leading + } + return pages <= fitHeight } if !fits(zoom) { zoom = minimumTextFitZoom diff --git a/minipdf-go/office_test.go b/minipdf-go/office_test.go index 5ae61e69..eef490cf 100644 --- a/minipdf-go/office_test.go +++ b/minipdf-go/office_test.go @@ -624,6 +624,7 @@ func TestConvertXLSXFitToPageZoomBounds(t *testing.T) { {name: "content that already fits keeps its size", rows: 48, pages: 1, fontSize: "/F1 11 Tf"}, {name: "one more line shrinks the text", rows: 49, pages: 1, fontSize: "/F1 10.89 Tf"}, {name: "several pages share the height", pageSetup: ``, rows: 97, pages: 2, fontSize: "/F1 11 Tf"}, + {name: "Letter height is a multiple of the leading", pageSetup: ``, rows: 95, pages: 1, fontSize: "/F1 5.17 Tf"}, {name: "zoom stops at the minimum", rows: 5000, pages: 11, fontSize: "/F1 1.1 Tf"}, } for _, test := range tests { From ff3f5eb9f9bb4f7722f84e832ae8c2c63a7befb2 Mon Sep 17 00:00:00 2001 From: Wei Lin Date: Tue, 17 Nov 2026 00:07:59 +0800 Subject: [PATCH 4/4] fix(go): address fit pagination and long-cell wrapping reviews Count only emitted pages during height fitting, preserve sparse-page spacing, and avoid rebuilding rune suffixes while wrapping. Add regression and allocation benchmarks. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- minipdf-go/office.go | 43 +++++++--- minipdf-go/office_test.go | 162 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 195 insertions(+), 10 deletions(-) diff --git a/minipdf-go/office.go b/minipdf-go/office.go index a2a2b590..af910f14 100644 --- a/minipdf-go/office.go +++ b/minipdf-go/office.go @@ -181,24 +181,44 @@ func addTextPages(document *PDFDocument, lines []string, pageSize PageSize, marg // the check and the layout cannot disagree about a page break. fits := func(zoom int) bool { leading := baseLeading * float64(zoom) / 100 - pages := 1 + pages := 0 + pageHasText := false + if !skipEmpty { + pages = 1 + pageHasText = true + } y := pageSize.Height - margins.Top - for range wrapAt(zoom) { + for _, line := range wrapAt(zoom) { if y < margins.Bottom { - pages++ + pageHasText = false y = pageSize.Height - margins.Top } + if (!skipEmpty || strings.TrimSpace(line) != "") && !pageHasText { + pages++ + pageHasText = true + if pages > fitHeight { + return false + } + } y -= leading } return pages <= fitHeight } if !fits(zoom) { - zoom = minimumTextFitZoom - for tooLarge := 100; tooLarge-zoom > 1; { - if middle := (zoom + tooLarge) / 2; fits(middle) { - zoom = middle - } else { - tooLarge = middle + if skipEmpty { + // Visible page counts are not monotonic: moving a page break + // can merge or separate sparse text around skipped empty pages. + // Check percentages in descending order to find the largest fit. + for zoom--; zoom > minimumTextFitZoom && !fits(zoom); zoom-- { + } + } else { + zoom = minimumTextFitZoom + for tooLarge := 100; tooLarge-zoom > 1; { + if middle := (zoom + tooLarge) / 2; fits(middle) { + zoom = middle + } else { + tooLarge = middle + } } } } @@ -254,7 +274,10 @@ func wrapText(text string, limit int) []string { } } lines = append(lines, strings.TrimSpace(string(runes[:breakAt]))) - runes = []rune(strings.TrimLeftFunc(string(runes[breakAt:]), unicode.IsSpace)) + runes = runes[breakAt:] + for len(runes) > 0 && unicode.IsSpace(runes[0]) { + runes = runes[1:] + } } lines = append(lines, string(runes)) } diff --git a/minipdf-go/office_test.go b/minipdf-go/office_test.go index eef490cf..44fe44e6 100644 --- a/minipdf-go/office_test.go +++ b/minipdf-go/office_test.go @@ -6,6 +6,8 @@ import ( "encoding/xml" "errors" "fmt" + "math" + "slices" "strings" "testing" ) @@ -649,6 +651,166 @@ func TestConvertXLSXFitToPageZoomBounds(t *testing.T) { } } +func TestConvertXLSXFitToPageSkipsEmptyPages(t *testing.T) { + tests := []struct { + name string + rows []int + lastRow int + fitHeight int + pages int + fontSize string + }{ + {name: "trailing empty pages", rows: []int{1}, lastRow: 5000, fitHeight: 1, pages: 1, fontSize: "/F1 11 Tf"}, + {name: "widely separated text fits two visible pages", rows: []int{1, 1000}, lastRow: 1001, fitHeight: 2, pages: 2, fontSize: "/F1 11 Tf"}, + {name: "leading and interior empty pages", rows: []int{101, 153}, lastRow: 510, fitHeight: 2, pages: 2, fontSize: "/F1 11 Tf"}, + {name: "sparse pages choose the largest fitting zoom", rows: []int{1, 100, 147}, lastRow: 510, fitHeight: 2, pages: 2, fontSize: "/F1 10.89 Tf"}, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + var sheet strings.Builder + sheet.WriteString(``) + for _, row := range test.rows { + fmt.Fprintf(&sheet, `Text%d`, row, row, row) + } + fmt.Fprintf(&sheet, ``, test.lastRow, test.fitHeight) + pdf, err := ConvertBytesToPDF(officePackageBytes(t, map[string]string{ + "xl/workbook.xml": ``, + "xl/worksheets/sheet1.xml": sheet.String(), + })) + if err != nil { + t.Fatal(err) + } + if pages := bytes.Count(pdf, []byte("/Type /Page ")); pages != test.pages { + t.Errorf("page count = %d, want %d", pages, test.pages) + } + if !bytes.Contains(pdf, []byte(test.fontSize)) { + t.Errorf("PDF does not use font size %q", test.fontSize) + } + for _, row := range test.rows { + if !bytes.Contains(pdf, []byte(fmt.Sprintf("Text%d", row))) { + t.Errorf("PDF lost text from row %d", row) + } + } + }) + } +} + +func TestTextFitPreservesSpacingWhenSkippingEmptyPages(t *testing.T) { + lines := make([]string, 510) + lines[0], lines[100], lines[152] = "First", "Middle", "Last" + document := NewPDFDocument() + addTextPages(document, lines, PageSizeA4, Margins{}, true, true, 3) + assertPDFContains(t, document.Bytes(), nil, "/F1 11 Tf", "54 787.89 Td", "54 757.89 Td", "54 712.89 Td") +} + +func TestTextFitEmptyPagesAndMinimumZoom(t *testing.T) { + for _, skipEmpty := range []bool{false, true} { + t.Run(fmt.Sprintf("skipEmpty=%t", skipEmpty), func(t *testing.T) { + for _, test := range []struct { + name string + lines []string + pages int + nonemptyPages int + fontSize float64 + }{ + {name: "no lines", pages: 1, fontSize: baseFontSize}, + {name: "Unicode whitespace", lines: []string{"", " \t", "\u2003\u3000"}, pages: 1, fontSize: baseFontSize}, + {name: "blank pagination windows", lines: make([]string, 100), pages: 1, fontSize: baseFontSize * 49 / 100}, + {name: "only minimum zoom fits", lines: strings.Split(strings.Repeat("Text\n", 488)+"Text", "\n"), pages: 1, nonemptyPages: 1, fontSize: 1.1}, + } { + t.Run(test.name, func(t *testing.T) { + document := NewPDFDocument() + addTextPages(document, test.lines, PageSizeA4, Margins{}, true, skipEmpty, 1) + wantPages := test.pages + if skipEmpty { + wantPages = test.nonemptyPages + } + if pages := len(document.pages); pages != wantPages { + t.Fatalf("page count = %d, want %d", pages, wantPages) + } + for _, page := range document.pages { + for _, operation := range page.operations { + text, ok := operation.(textOperation) + if !ok || text.fontSize != test.fontSize { + t.Errorf("operation = %#v, want text at %gpt", operation, test.fontSize) + } + } + } + }) + } + }) + } +} + +func TestTextFitScalesLineSpacing(t *testing.T) { + lines := make([]string, 100) + lines[0], lines[99] = "First", "Last" + for _, skipEmpty := range []bool{false, true} { + t.Run(fmt.Sprintf("skipEmpty=%t", skipEmpty), func(t *testing.T) { + document := NewPDFDocument() + addTextPages(document, lines, PageSizeA4, Margins{}, true, skipEmpty, 1) + if len(document.pages) != 1 { + t.Fatalf("page count = %d, want 1", len(document.pages)) + } + var texts []textOperation + for _, operation := range document.pages[0].operations { + if text, ok := operation.(textOperation); ok && text.text != "" { + texts = append(texts, text) + } + } + if len(texts) != 2 { + t.Fatalf("nonempty text operations = %d, want 2", len(texts)) + } + // 49% is the largest integer zoom that fits all 100 line positions. + for _, text := range texts { + if text.fontSize != baseFontSize*49/100 { + t.Errorf("font size = %g, want %g", text.fontSize, baseFontSize*49/100) + } + } + wantDistance := 99 * baseLeading * 49 / 100 + if distance := texts[0].y - texts[1].y; math.Abs(distance-wantDistance) > 1e-9 { + t.Errorf("line distance = %g, want %g", distance, wantDistance) + } + }) + } +} + +func TestWrapTextPreservesWhitespaceAndUnicode(t *testing.T) { + for _, test := range []struct { + name, text string + limit int + want []string + }{ + {name: "empty", want: []string{""}, limit: 10}, + {name: "hard breaks", text: "abcdefghij", limit: 3, want: []string{"abc", "def", "ghi", "j"}}, + {name: "word breaks", text: "alpha beta gamma", limit: 10, want: []string{"alpha", "beta gamma"}}, + {name: "unicode spaces", text: "猫狗\u2003鱼鸟\u2003山水", limit: 4, want: []string{"猫狗", "鱼鸟", "山水"}}, + {name: "newlines", text: "ab\n\ncd\n", limit: 3, want: []string{"ab", "", "cd", ""}}, + {name: "trailing spaces", text: "abcd ", limit: 3, want: []string{"abc", "d "}}, + } { + t.Run(test.name, func(t *testing.T) { + got := wrapText(test.text, test.limit) + if !slices.Equal(got, test.want) { + t.Errorf("wrapped lines = %q, want %q", got, test.want) + } + }) + } +} + +func BenchmarkWrapTextLongCell(b *testing.B) { + for _, length := range []int{10000, 20000} { + b.Run(fmt.Sprint(length), func(b *testing.B) { + text := strings.Repeat("X", length) + b.ReportAllocs() + b.SetBytes(int64(length)) + b.ResetTimer() + for i := 0; i < b.N; i++ { + wrapText(text, 85) + } + }) + } +} + func TestConvertXLSXFitToPageWrapsLongText(t *testing.T) { input := officePackageBytes(t, map[string]string{ "xl/workbook.xml": ``,