From e6a0d6f599922eee8d1887dcc0eb06d1240cfb4e Mon Sep 17 00:00:00 2001 From: Wei Lin Date: Tue, 17 Nov 2026 00:08:38 +0800 Subject: [PATCH 1/3] feat(go): render single-page DOCX tables, fonts, and images Preserve table geometry, merges, styles, registered and installed font metrics, and package images. Keep unsupported pagination and metafiles on the existing text path. TestIssue93 improves from 0.3331 to 0.9757 with all 27 unrelated issue DOCX outputs byte-identical. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- minipdf-go/README.md | 34 +- minipdf-go/docx.go | 3 + minipdf-go/docx_font.go | 172 +++++ minipdf-go/docx_render.go | 1141 ++++++++++++++++++++++++++++++++ minipdf-go/docx_render_test.go | 367 ++++++++++ minipdf-go/pdf.go | 8 +- 6 files changed, 1717 insertions(+), 8 deletions(-) create mode 100644 minipdf-go/docx_font.go create mode 100644 minipdf-go/docx_render.go create mode 100644 minipdf-go/docx_render_test.go diff --git a/minipdf-go/README.md b/minipdf-go/README.md index c660d926..9d69ca3c 100644 --- a/minipdf-go/README.md +++ b/minipdf-go/README.md @@ -8,7 +8,8 @@ The experimental native Go implementation of MiniPdf. It provides a reusable > The Go implementation is an early foundation and is not feature-equivalent > with MiniPdf for .NET or Rust. It currently renders basic text from XLSX, -> DOCX, and PPTX packages. Complex Office layout is not yet supported. +> DOCX, and PPTX packages, and a supported subset of DOCX tables. Complex +> Office layout is not yet supported. ## Requirements @@ -87,8 +88,11 @@ defer minipdf.ClearRegisteredFonts() ``` Registered `.ttf` fonts are embedded as Type0/CID fonts with ToUnicode maps. -Font subsetting, TrueType Collections, automatic system-font discovery, and -complex-script shaping are not yet implemented. +The structured DOCX table renderer also accepts registered TrueType collections +(the first face), and resolves selected installed Windows fonts, including +SimSun/SimHei and their Chinese family names. Collections are rebuilt as standalone +sfnt fonts before PDF embedding. Font subsetting and complex-script shaping are +not yet implemented. Font binaries are not distributed with MiniPdf. Override the output page size: @@ -120,7 +124,7 @@ minipdf data.xlsx --max-rows 100 --max-columns 12 --landscape | Capability | Go status | |---|---| | XLSX to PDF | Basic cell text and shared strings | -| DOCX to PDF | Basic paragraphs, tabs, line breaks, and explicit page breaks | +| DOCX to PDF | Basic text; supported table documents also preserve grid widths, horizontal/vertical merges, borders, fills, run fonts, highlights, paragraph spacing/alignment, and PNG/JPEG drawings | | PPTX to PDF | Basic slide text | | PDF output | Dependency-free PDF 1.4 writer | | Page size | Office geometry, A4/Letter presets, or custom points | @@ -128,6 +132,28 @@ minipdf data.xlsx --max-rows 100 --max-columns 12 --landscape | Input safety | Bounded ZIP entry count, size, expansion ratio, encryption, and path validation | | Interfaces | Go package with file, byte, and stream APIs; native CLI | +Single-page DOCX documents with non-nested, non-floating table grids can use the +structured renderer. It resolves paragraph/style inheritance and theme fonts, uses glyph +metrics for wrapping, respects East Asian punctuation boundaries, and honors +Word's FE-layout CJK metric compatibility flag. Images use their package +relationships and DrawingML extents; simple VML text-box images use their margin +offsets and text-box insets. Image decoding is limited to 25 million pixels. +Missing or invalid embedded images produce errors rather than disappearing. + +Documents requiring unsupported section changes, numbering, anchored drawings, +exact-height rows, multi-page structured layout, or referenced EMF/WMF images +retain the existing text converter. If measured paragraph, inline-image, or +table flow would cross the first page's content boundary, the entire document +uses the text converter; structured pagination, keep rules, and row splitting +are not implemented. Metafile formats are checked before +structured rendering; malformed PNG/JPEG images still produce decoding errors. +Images inside table cells, complex drawing geometry, conditional +table styles, headers/footers, and complex-script shaping remain unsupported. +Structured text uses matching registered fonts or selected licensed Windows +fonts, with Arial/SimSun glyph fallback when available. Missing Unicode glyphs +produce an explicit error on the structured path. Fonts are embedded without +subsetting, so large CJK fonts can substantially increase PDF size. + XLSX text output skips entirely empty pages within worksheets containing text, including empty horizontal column groups and pages from trailing formatted rows. Blank rows within nonempty pages retain their spacing. Layout-only worksheets diff --git a/minipdf-go/docx.go b/minipdf-go/docx.go index a01df532..9e859415 100644 --- a/minipdf-go/docx.go +++ b/minipdf-go/docx.go @@ -32,6 +32,9 @@ func convertDOCX(input []byte, options ConversionOptions) ([]byte, error) { if err := validateDOCXLayout(effectivePageSize, effectiveMargins); err != nil { return nil, err } + if rendered, supported, err := renderDOCXTables(files, documentXML, effectivePageSize, effectiveMargins, options); supported || err != nil { + return rendered, err + } textPages := make([]textPage, len(pages)) for index, lines := range pages { textPages[index] = textPage{lines: lines, size: pageSize, margins: margins} diff --git a/minipdf-go/docx_font.go b/minipdf-go/docx_font.go new file mode 100644 index 00000000..e13386bc --- /dev/null +++ b/minipdf-go/docx_font.go @@ -0,0 +1,172 @@ +package minipdf + +import ( + "encoding/binary" + "fmt" + "os" + "path/filepath" + "runtime" + "strings" + + "golang.org/x/image/font" + "golang.org/x/image/font/sfnt" + "golang.org/x/image/math/fixed" +) + +// A PDF FontFile2 contains a single sfnt, not the enclosing TTC. Rebuild its +// directory because offsets inside a collection are relative to the TTC file. +func docxCollectionFont(data []byte, index int) ([]byte, error) { + if len(data) < 12 || string(data[:4]) != "ttcf" { + if index == 0 { + return data, nil + } + return nil, fmt.Errorf("font is not a collection") + } + count := int(binary.BigEndian.Uint32(data[8:12])) + if index < 0 || index >= count || count > (len(data)-12)/4 { + return nil, fmt.Errorf("invalid font collection directory") + } + offset := int(binary.BigEndian.Uint32(data[12+index*4 : 16+index*4])) + if offset < 0 || offset > len(data)-12 { + return nil, fmt.Errorf("invalid font collection offset") + } + n := int(binary.BigEndian.Uint16(data[offset+4 : offset+6])) + if n > (len(data)-offset-12)/16 { + return nil, fmt.Errorf("invalid sfnt directory") + } + out := append([]byte(nil), data[offset:offset+12+n*16]...) + for i := 0; i < n; i++ { + record := out[12+i*16 : 28+i*16] + start := int(binary.BigEndian.Uint32(record[8:12])) + length := int(binary.BigEndian.Uint32(record[12:16])) + if start < 0 || length < 0 || start > len(data) || length > len(data)-start { + return nil, fmt.Errorf("invalid sfnt table bounds") + } + binary.BigEndian.PutUint32(record[8:12], uint32(len(out))) + out = append(out, data[start:start+length]...) + for len(out)%4 != 0 { + out = append(out, 0) + } + } + // checkSumAdjustment is defined for the standalone font, not its collection. + for i := 0; i < n; i++ { + r := out[12+i*16 : 28+i*16] + if string(r[:4]) == "head" { + o := int(binary.BigEndian.Uint32(r[8:12])) + if int(binary.BigEndian.Uint32(r[12:16])) < 12 { + return nil, fmt.Errorf("invalid head table") + } + binary.BigEndian.PutUint32(out[o+8:o+12], 0) + var sum uint32 + for j := 0; j < len(out); j += 4 { + sum += binary.BigEndian.Uint32(out[j : j+4]) + } + binary.BigEndian.PutUint32(out[o+8:o+12], 0xB1B0AFBA-sum) + } + } + return out, nil +} + +func loadDOCXFont(name string, bold, italic bool) (*embeddedFont, error) { + variant := name + if bold { + variant += " Bold" + } + if italic { + variant += " Italic" + } + var data []byte + for _, registered := range RegisteredFonts() { + if strings.EqualFold(registered.Name, variant) { + data = registered.Data + break + } + } + if data == nil && runtime.GOOS == "windows" { + var file string + switch strings.ToLower(name) { + case "宋体", "simsun": + file = "simsun.ttc" + case "黑体", "simhei": + file = "simhei.ttf" + case "楷体", "kaiti": + file = "simkai.ttf" + case "仿宋", "fangsong": + file = "simfang.ttf" + case "times new roman": + file = "times.ttf" + if bold { + file = "timesbd.ttf" + } + if italic { + file = "timesi.ttf" + if bold { + file = "timesbi.ttf" + } + } + default: + return readXLSXFont(name, bold, italic) + } + if root := os.Getenv("WINDIR"); root != "" { + var err error + data, err = os.ReadFile(filepath.Join(root, "Fonts", file)) + if os.IsNotExist(err) { + return nil, nil + } + if err != nil { + return nil, err + } + } + } + if data == nil { + return nil, nil + } + data, err := docxCollectionFont(data, 0) + if err != nil { + return nil, fmt.Errorf("DOCX font %q: %w", name, err) + } + parsed, err := sfnt.Parse(data) + if err != nil { + return nil, fmt.Errorf("DOCX font %q: %w", name, err) + } + if postscript, err := parsed.Name(nil, sfnt.NameIDPostScript); err == nil && postscript != "" { + variant = postscript + } + ppem := fixed.Int26_6(parsed.UnitsPerEm()) + metrics, err := parsed.Metrics(nil, ppem, font.HintingNone) + if err != nil { + return nil, err + } + result := &embeddedFont{name: sanitizePDFFontName(variant), data: data, font: parsed, runeToGlyph: make(map[rune]sfnt.GlyphIndex), glyphToRune: make(map[sfnt.GlyphIndex]rune), advances: make([]float64, parsed.NumGlyphs()), ascent: float64(metrics.Ascent) / float64(ppem), descent: float64(metrics.Descent) / float64(ppem)} + for i := range result.advances { + a, err := parsed.GlyphAdvance(nil, sfnt.GlyphIndex(i), ppem, font.HintingNone) + if err != nil { + return nil, err + } + result.advances[i] = float64(a) / float64(ppem) + } + return result, nil +} + +func docxFontCJK(data []byte) bool { + if len(data) < 12 { + return false + } + n := int(binary.BigEndian.Uint16(data[4:6])) + if n > (len(data)-12)/16 { + return false + } + for i := 0; i < n; i++ { + r := data[12+i*16 : 28+i*16] + if string(r[:4]) != "OS/2" { + continue + } + o := int(binary.BigEndian.Uint32(r[8:12])) + length := int(binary.BigEndian.Uint32(r[12:16])) + if length < 86 || o < 0 || o > len(data)-length { + return false + } + return binary.BigEndian.Uint32(data[o+78:o+82])&(0xf<<17) != 0 + } + return false +} diff --git a/minipdf-go/docx_render.go b/minipdf-go/docx_render.go new file mode 100644 index 00000000..aae45569 --- /dev/null +++ b/minipdf-go/docx_render.go @@ -0,0 +1,1141 @@ +package minipdf + +import ( + "bytes" + "encoding/xml" + "fmt" + "image" + _ "image/jpeg" + _ "image/png" + "io" + "math" + "path" + "strconv" + "strings" + "unicode" +) + +type docxNode struct { + name string + attrs map[string]string + children []*docxNode + text string +} + +func parseDOCXNode(data []byte) (*docxNode, error) { + root := &docxNode{} + stack := []*docxNode{root} + dec := xml.NewDecoder(bytes.NewReader(data)) + for { + token, err := dec.Token() + if err == io.EOF { + break + } + if err != nil { + return nil, err + } + switch t := token.(type) { + case xml.StartElement: + n := &docxNode{name: t.Name.Local, attrs: map[string]string{}} + for _, a := range t.Attr { + n.attrs[a.Name.Local] = a.Value + } + p := stack[len(stack)-1] + p.children = append(p.children, n) + stack = append(stack, n) + case xml.EndElement: + stack = stack[:len(stack)-1] + case xml.CharData: + stack[len(stack)-1].text += string(t) + } + } + if len(root.children) == 0 { + return nil, fmt.Errorf("empty DOCX XML") + } + return root.children[0], nil +} +func (n *docxNode) child(name string) *docxNode { + if n != nil { + for _, c := range n.children { + if c.name == name { + return c + } + } + } + return nil +} +func (n *docxNode) attr(key string) string { + if n == nil { + return "" + } + return n.attrs[key] +} +func (n *docxNode) value(name string) string { return n.child(name).attr("val") } +func (n *docxNode) descendants(name string) []*docxNode { + var out []*docxNode + if n != nil { + for _, c := range n.children { + if c.name == name { + out = append(out, c) + } + out = append(out, c.descendants(name)...) + } + } + return out +} +func docxNumber(s string) float64 { + v, _ := strconv.ParseFloat(s, 64) + if math.IsNaN(v) || math.IsInf(v, 0) { + return 0 + } + return v +} +func docxOn(n *docxNode) bool { + return n != nil && n.attr("val") != "0" && n.attr("val") != "false" && n.attr("val") != "off" +} + +type docxRunStyle struct { + size float64 + fonts map[string]string + bold, italic bool + color PDFColor + highlight *PDFColor + lang string +} +type docxParagraphStyle struct { + run docxRunStyle + before, after, line float64 + lineRule, align string + left, right, first float64 + snap bool +} +type docxStyles struct { + nodes map[string]*docxNode + defaults docxParagraphStyle + theme map[string]string + fonts map[string]*embeddedFont + cjkMetrics bool +} + +func (s *docxStyles) applyRun(style docxRunStyle, n *docxNode) docxRunStyle { + f := map[string]string{} + for k, v := range style.fonts { + f[k] = v + } + style.fonts = f + if n == nil { + return style + } + if sz := n.child("sz"); sz != nil && docxNumber(sz.attr("val")) > 0 { + style.size = docxNumber(sz.attr("val")) / 2 + } + if fonts := n.child("rFonts"); fonts != nil { + for _, key := range []string{"ascii", "hAnsi", "eastAsia", "cs"} { + if v := fonts.attr(key); v != "" { + style.fonts[key] = v + delete(style.fonts, key+"Theme") + } + if v := fonts.attr(key + "Theme"); v != "" { + style.fonts[key+"Theme"] = v + delete(style.fonts, key) + } + } + } + if n.child("b") != nil { + style.bold = docxOn(n.child("b")) + } + if n.child("i") != nil { + style.italic = docxOn(n.child("i")) + } + if lang := n.child("lang").attr("eastAsia"); lang != "" { + style.lang = lang + } + if c := n.child("color"); c != nil { + style.color = docxColor(c.attr("val")) + } + if h := n.child("highlight"); h != nil { + style.highlight = nil + colors := map[string]string{"yellow": "FFFF00", "green": "00FF00", "cyan": "00FFFF", "magenta": "FF00FF", "blue": "0000FF", "red": "FF0000", "darkYellow": "808000"} + if v, ok := colors[h.attr("val")]; ok { + c := docxColor(v) + style.highlight = &c + } + } + return style +} +func (s *docxStyles) applyParagraph(style docxParagraphStyle, n *docxNode) docxParagraphStyle { + if n == nil { + return style + } + style.run = s.applyRun(style.run, n.child("rPr")) + if p := n.child("spacing"); p != nil { + for _, item := range []struct { + key string + out *float64 + }{{"before", &style.before}, {"after", &style.after}, {"line", &style.line}} { + if v, ok := p.attrs[item.key]; ok { + *item.out = docxNumber(v) / 20 + } + } + if p.attr("lineRule") != "" { + style.lineRule = p.attr("lineRule") + } + } + if p := n.child("jc"); p != nil { + style.align = p.attr("val") + } + if p := n.child("ind"); p != nil { + for _, item := range []struct { + key string + out *float64 + }{{"left", &style.left}, {"right", &style.right}, {"firstLine", &style.first}} { + if v, ok := p.attrs[item.key]; ok { + *item.out = docxNumber(v) / 20 + } + } + if v, ok := p.attrs["hanging"]; ok { + style.first = -docxNumber(v) / 20 + } + } + if p := n.child("snapToGrid"); p != nil { + style.snap = docxOn(p) + } + return style +} +func (s *docxStyles) inherit(style docxParagraphStyle, id string, seen map[string]bool) docxParagraphStyle { + if seen[id] { + return style + } + seen[id] = true + n := s.nodes[id] + if n == nil { + return style + } + style = s.inherit(style, n.value("basedOn"), seen) + style = s.applyParagraph(style, n.child("pPr")) + style.run = s.applyRun(style.run, n.child("rPr")) + return style +} +func (s *docxStyles) paragraph(n *docxNode) docxParagraphStyle { + style := s.defaults + pr := n.child("pPr") + style = s.inherit(style, pr.value("pStyle"), map[string]bool{}) + return s.applyParagraph(style, pr) +} +func docxColor(value string) PDFColor { + v, err := strconv.ParseUint(value, 16, 24) + if err != nil { + return PDFColorBlack + } + return PDFColor{Red: float64(v>>16) / 255, Green: float64((v>>8)&255) / 255, Blue: float64(v&255) / 255} +} + +func readDOCXStyles(files officePackage) (*docxStyles, error) { + s := &docxStyles{nodes: map[string]*docxNode{}, theme: map[string]string{}, fonts: map[string]*embeddedFont{}, defaults: docxParagraphStyle{run: docxRunStyle{size: 12, fonts: map[string]string{"ascii": "Arial", "eastAsia": "SimSun"}}, snap: true}} + if _, ok := files["word/settings.xml"]; ok { + data, err := files.read("word/settings.xml") + if err != nil { + return nil, err + } + root, err := parseDOCXNode(data) + if err != nil { + return nil, err + } + s.cjkMetrics = docxOn(root.child("compat").child("useFELayout")) + } + if _, ok := files["word/theme/theme1.xml"]; ok { + data, err := files.read("word/theme/theme1.xml") + if err != nil { + return nil, err + } + root, err := parseDOCXNode(data) + if err != nil { + return nil, err + } + for _, group := range []string{"major", "minor"} { + for _, n := range root.descendants(group + "Font") { + s.theme[group+"HAnsi"] = n.child("latin").attr("typeface") + s.theme[group+"Ascii"] = s.theme[group+"HAnsi"] + s.theme[group+"EastAsia"] = n.child("ea").attr("typeface") + for _, f := range n.children { + if f.name == "font" { + s.theme[group+":"+f.attr("script")] = f.attr("typeface") + } + } + } + } + } + if _, ok := files["word/styles.xml"]; ok { + data, err := files.read("word/styles.xml") + if err != nil { + return nil, err + } + root, err := parseDOCXNode(data) + if err != nil { + return nil, err + } + d := root.child("docDefaults") + s.defaults.run = s.applyRun(s.defaults.run, d.child("rPrDefault").child("rPr")) + s.defaults = s.applyParagraph(s.defaults, d.child("pPrDefault").child("pPr")) + normal := "" + for _, n := range root.children { + if n.name == "style" { + s.nodes[n.attr("styleId")] = n + if n.attr("type") == "paragraph" && n.attr("default") == "1" { + normal = n.attr("styleId") + } + } + } + s.defaults = s.inherit(s.defaults, normal, map[string]bool{}) + } + return s, nil +} +func (s *docxStyles) font(style docxRunStyle, r rune) (*embeddedFont, error) { + key := "ascii" + if r > 127 { + key = "hAnsi" + } + if docxAsian(r) { + key = "eastAsia" + } + name := style.fonts[key] + if theme := style.fonts[key+"Theme"]; theme != "" { + name = s.theme[theme] + if strings.HasSuffix(theme, "EastAsia") && name == "" { + script := "Hans" + if strings.HasPrefix(style.lang, "ja") { + script = "Jpan" + } + if strings.HasPrefix(style.lang, "ko") { + script = "Hang" + } + if style.lang == "zh-TW" || style.lang == "zh-HK" { + script = "Hant" + } + name = s.theme[strings.TrimSuffix(theme, "EastAsia")+":"+script] + } + } + if name == "" { + name = "Arial" + if docxAsian(r) { + name = "SimSun" + } + } + cache := fmt.Sprintf("%s/%t/%t", name, style.bold, style.italic) + f, ok := s.fonts[cache] + if !ok { + var err error + f, err = loadDOCXFont(name, style.bold, style.italic) + if err != nil { + return nil, err + } + s.fonts[cache] = f + } + if r > 127 && (f == nil || !f.canEncode(string(r))) { + fallback := "Arial" + if docxAsian(r) { + fallback = "SimSun" + } + fallbackKey := fmt.Sprintf("%s/%t/%t", fallback, style.bold, style.italic) + if fallbackKey != cache { + fallbackFont, ok := s.fonts[fallbackKey] + if !ok { + var err error + fallbackFont, err = loadDOCXFont(fallback, style.bold, style.italic) + if err != nil { + return nil, err + } + s.fonts[fallbackKey] = fallbackFont + } + if fallbackFont != nil && fallbackFont.canEncode(string(r)) { + return fallbackFont, nil + } + } + } + return f, nil +} +func docxAsian(r rune) bool { + return unicode.Is(unicode.Han, r) || unicode.Is(unicode.Hiragana, r) || unicode.Is(unicode.Katakana, r) || r >= 0x3000 && r <= 0x303f || r >= 0xff00 && r <= 0xffef || r == 0x25a1 +} + +type docxGlyph struct { + r rune + style docxRunStyle + font *embeddedFont + width, ascent, descent float64 +} +type docxLine struct { + glyphs []docxGlyph + width, height, ascent float64 +} +type docxParagraph struct { + style docxParagraphStyle + lines []docxLine + height float64 +} +type docxImage struct { + op imageOperation + floating bool + left, top float64 +} + +func (s *docxStyles) layoutParagraph(n *docxNode, width, grid float64) (docxParagraph, error) { + p := docxParagraph{style: s.paragraph(n)} + var glyphs []docxGlyph + var visit func(*docxNode, docxRunStyle) error + visit = func(n *docxNode, style docxRunStyle) error { + if n.name == "pPr" || n.name == "rPr" || n.name == "pict" || n.name == "drawing" { + return nil + } + if n.name == "r" { + if id := n.child("rPr").value("rStyle"); id != "" { + inherited := s.inherit(docxParagraphStyle{run: style}, id, map[string]bool{}) + style = inherited.run + } + style = s.applyRun(style, n.child("rPr")) + } + text := "" + if n.name == "t" { + text = n.text + } + if n.name == "tab" { + text = " " + } + if n.name == "br" || n.name == "cr" { + text = "\n" + } + for _, r := range text { + if r == '\n' { + glyphs = append(glyphs, docxGlyph{r: r}) + continue + } + f, err := s.font(style, r) + if err != nil { + return err + } + g := docxGlyph{r: r, style: style, font: f, width: style.size * .5, ascent: style.size * .9, descent: style.size * .25} + if docxAsian(r) { + g.width = style.size + } + if f != nil { + if !f.canEncode(string(r)) { + return fmt.Errorf("DOCX font %q has no glyph for U+%04X", f.name, r) + } + g.width = measureXLSXFont(string(r), style.size, f) + g.ascent = f.ascent * style.size + g.descent = f.descent * style.size + // Writer fntcache.cxx, lcl_ApplyCjkHeightAdjustment: Word's + // FE layout scales metrics for fonts advertising CJK code pages. + if s.cjkMetrics && grid == 0 && docxFontCJK(f.data) { + g.ascent *= 1.27 + g.descent *= 1.27 + } + } else if r > 127 { + return fmt.Errorf("DOCX character U+%04X requires an installed or registered font", r) + } + glyphs = append(glyphs, g) + } + for _, c := range n.children { + if err := visit(c, style); err != nil { + return err + } + } + return nil + } + if err := visit(n, p.style.run); err != nil { + return p, err + } + emptyFont, err := s.font(p.style.run, ' ') + if err != nil { + return p, err + } + // Word's automatic East Asian/Latin spacing is a quarter-em at script boundaries. + for i := 1; i < len(glyphs); i++ { + a, b := glyphs[i-1].r, glyphs[i].r + if (unicode.Is(unicode.Han, a) && docxLatin(b)) || (docxLatin(a) && unicode.Is(unicode.Han, b)) { + glyphs[i-1].width += math.Min(glyphs[i-1].style.size, glyphs[i].style.size) / 4 + } + } + available := math.Max(1, width-p.style.left-p.style.right) + var line docxLine + flush := func() { + if len(line.glyphs) == 0 { + f := emptyFont + line.ascent = p.style.run.size * .9 + line.height = p.style.run.size * 1.3 + if f != nil { + line.ascent = f.ascent * p.style.run.size + line.height = (f.ascent + f.descent) * p.style.run.size + if s.cjkMetrics && grid == 0 && docxFontCJK(f.data) { + line.ascent *= 1.27 + line.height *= 1.27 + } + } + } + line.height = math.Max(line.height, line.ascent) + if grid > 0 && p.style.snap { + h := math.Ceil((line.height-.001)/grid) * grid + line.ascent += (h - line.height) / 2 + line.height = h + } + if p.style.line > 0 { + if p.style.lineRule == "exact" { + line.height = p.style.line + line.ascent = math.Min(line.ascent, line.height*.8) + } else if p.style.lineRule == "atLeast" { + line.height = math.Max(line.height, p.style.line) + } else { + h := line.height * p.style.line / 12 + if grid > 0 && p.style.snap { + h = math.Ceil((h-.001)/grid) * grid + } + line.ascent += (h - line.height) / 2 + line.height = h + } + } + p.height += line.height + p.lines = append(p.lines, line) + line = docxLine{} + } + for i := 0; i < len(glyphs); i++ { + g := glyphs[i] + if g.r == '\n' { + flush() + continue + } + limit := available + if len(p.lines) == 0 { + limit -= p.style.first + } + if line.width+g.width > limit+.01 && len(line.glyphs) > 0 && !(len(line.glyphs) == 1 && (strings.ContainsRune("(([【《「『", line.glyphs[0].r) || strings.ContainsRune("),。!?、;:)]】》」』", g.r))) { + var carry []docxGlyph + last := line.glyphs[len(line.glyphs)-1] + if strings.ContainsRune("(([【《「『", last.r) || strings.ContainsRune("),。!?、;:)]】》」』", g.r) { + carry = []docxGlyph{last} + line.glyphs = line.glyphs[:len(line.glyphs)-1] + line.width -= last.width + } else if docxLatin(g.r) && docxLatin(last.r) { + for j := len(line.glyphs) - 1; j >= 0; j-- { + if unicode.IsSpace(line.glyphs[j].r) { + carry = append(carry, line.glyphs[j+1:]...) + line.glyphs = line.glyphs[:j+1] + line.width = 0 + for _, c := range line.glyphs { + line.width += c.width + } + break + } + } + } + flush() + for _, c := range carry { + line.glyphs = append(line.glyphs, c) + line.width += c.width + line.ascent = math.Max(line.ascent, c.ascent) + line.height = math.Max(line.height, c.ascent+c.descent) + } + } + line.glyphs = append(line.glyphs, g) + line.width += g.width + line.ascent = math.Max(line.ascent, g.ascent) + line.height = math.Max(line.height, g.ascent+g.descent) + } + flush() + p.height += p.style.before + p.style.after + return p, nil +} +func docxLatin(r rune) bool { return r < 128 && (unicode.IsLetter(r) || unicode.IsDigit(r)) } + +func drawDOCXParagraph(page *PDFPage, p docxParagraph, x, top, width float64) { + top += p.style.before + for i, line := range p.lines { + left := x + p.style.left + if i == 0 { + left += p.style.first + } + switch p.style.align { + case "center": + left += (width - p.style.left - p.style.right - line.width) / 2 + case "right": + left += width - p.style.left - p.style.right - line.width + } + baseline := page.Height - top - line.ascent + for _, g := range line.glyphs { + if g.style.highlight != nil { + page.AddRect(left, page.Height-top-line.height, g.width, line.height, *g.style.highlight) + } + page.operations = append(page.operations, textOperation{text: string(g.r), x: left, y: baseline, fontSize: g.style.size, horizontalScale: 100, color: g.style.color, bold: g.style.bold, italic: g.style.italic, embedded: g.font}) + left += g.width + } + top += line.height + } +} + +type docxBorder struct { + style string + width float64 + color PDFColor +} + +func readDOCXBorder(n *docxNode) docxBorder { + if n == nil { + return docxBorder{} + } + return docxBorder{style: n.attr("val"), width: docxNumber(n.attr("sz")) / 8, color: docxColor(n.attr("color"))} +} +func docxBorders(n *docxNode, inherited map[string]docxBorder) map[string]docxBorder { + b := map[string]docxBorder{} + for k, v := range inherited { + b[k] = v + } + if n != nil { + for _, c := range n.children { + b[c.name] = readDOCXBorder(c) + } + } + return b +} + +type docxCell struct { + column, span, row, rowSpan int + continuation bool + width float64 + paras []docxParagraph + contentHeight float64 + margins Margins + borders map[string]docxBorder + align string + fill *PDFColor +} +type docxTable struct { + cells []*docxCell + columns, rows []float64 + width float64 + align string + indent float64 +} + +func (s *docxStyles) table(n *docxNode, available float64) (docxTable, error) { + t := docxTable{align: n.child("tblPr").value("jc")} + pr := n.child("tblPr") + var inherited map[string]docxBorder + tm := Margins{Left: 5.4, Right: 5.4} + var styleChain func(string, map[string]bool) + styleChain = func(id string, seen map[string]bool) { + if seen[id] { + return + } + seen[id] = true + if st := s.nodes[id]; st != nil { + styleChain(st.value("basedOn"), seen) + inherited = docxBorders(st.child("tblPr").child("tblBorders"), inherited) + tm = docxCellMargins(st.child("tblPr").child("tblCellMar"), tm) + } + } + styleChain(pr.value("tblStyle"), map[string]bool{}) + inherited = docxBorders(pr.child("tblBorders"), inherited) + tm = docxCellMargins(pr.child("tblCellMar"), tm) + t.indent = docxNumber(pr.child("tblInd").attr("w")) / 20 + for _, col := range n.child("tblGrid").children { + if col.name == "gridCol" { + t.columns = append(t.columns, docxNumber(col.attr("w"))/20) + } + } + for _, w := range t.columns { + t.width += w + } + if w := pr.child("tblW"); w.attr("type") == "dxa" && docxNumber(w.attr("w")) > 0 { + t.width = docxNumber(w.attr("w")) / 20 + } + if w := pr.child("tblW"); w.attr("type") == "pct" { + t.width = available * docxNumber(w.attr("w")) / 5000 + } + gridWidth := 0.0 + for _, w := range t.columns { + gridWidth += w + } + if gridWidth <= 0 || t.width <= 0 { + return t, fmt.Errorf("DOCX table has no positive grid") + } + for i := range t.columns { + t.columns[i] *= t.width / gridWidth + } + active := map[int]*docxCell{} + for _, row := range n.children { + if row.name != "tr" { + continue + } + ri := len(t.rows) + height := docxNumber(row.child("trPr").child("trHeight").attr("val")) / 20 + t.rows = append(t.rows, height) + column := 0 + for _, node := range row.children { + if node.name != "tc" { + continue + } + cp := node.child("tcPr") + span := int(docxNumber(cp.child("gridSpan").attr("val"))) + if span < 1 { + span = 1 + } + if column+span > len(t.columns) { + return t, fmt.Errorf("DOCX cell span exceeds table grid") + } + cell := &docxCell{column: column, span: span, row: ri, rowSpan: 1, margins: docxCellMargins(cp.child("tcMar"), tm), align: cp.value("vAlign"), borders: map[string]docxBorder{}} + for i := column; i < column+span; i++ { + cell.width += t.columns[i] + } + for _, edge := range []string{"top", "left", "bottom", "right"} { + key := edge + if edge == "top" && ri > 0 { + key = "insideH" + } + if edge == "left" && column > 0 { + key = "insideV" + } + if edge == "right" && column+span < len(t.columns) { + key = "insideV" + } + cell.borders[edge] = inherited[key] + } + cell.borders = docxBorders(cp.child("tcBorders"), cell.borders) + if shd := cp.child("shd"); shd != nil && shd.attr("fill") != "" && shd.attr("fill") != "auto" { + c := docxColor(shd.attr("fill")) + cell.fill = &c + } + if merge := cp.child("vMerge"); merge != nil { + if merge.attr("val") == "restart" { + active[column] = cell + } else if start := active[column]; start != nil && start.span == span { + start.rowSpan++ + cell.continuation = true + start.borders["bottom"] = cell.borders["bottom"] + } else { + return t, fmt.Errorf("DOCX vertical merge has no matching start") + } + } else { + delete(active, column) + } + if !cell.continuation { + for _, pn := range node.children { + if pn.name == "p" { + p, err := s.layoutParagraph(pn, math.Max(1, cell.width-cell.margins.Left-cell.margins.Right), 0) + if err != nil { + return t, err + } + cell.paras = append(cell.paras, p) + cell.contentHeight += p.height + } + } + } + t.cells = append(t.cells, cell) + column += span + } + if column != len(t.columns) { + return t, fmt.Errorf("DOCX row does not cover table grid") + } + } + for _, c := range t.cells { + if c.continuation || c.rowSpan > 1 { + continue + } + needed := c.contentHeight + c.margins.Top + c.margins.Bottom + docxBorderWidth(c.borders["top"]) + docxBorderWidth(c.borders["bottom"]) + t.rows[c.row] = math.Max(t.rows[c.row], needed) + } + for _, c := range t.cells { + if c.continuation || c.rowSpan == 1 { + continue + } + height := 0.0 + for i := c.row; i < c.row+c.rowSpan; i++ { + height += t.rows[i] + } + needed := c.contentHeight + c.margins.Top + c.margins.Bottom + docxBorderWidth(c.borders["top"]) + docxBorderWidth(c.borders["bottom"]) + if needed > height { + extra := (needed - height) / float64(c.rowSpan) + for i := c.row; i < c.row+c.rowSpan; i++ { + t.rows[i] += extra + } + } + } + return t, nil +} +func docxCellMargins(n *docxNode, m Margins) Margins { + for _, item := range []struct { + key string + out *float64 + }{{"left", &m.Left}, {"right", &m.Right}, {"top", &m.Top}, {"bottom", &m.Bottom}} { + if p := n.child(item.key); p != nil { + *item.out = docxNumber(p.attr("w")) / 20 + } + } + return m +} +func docxBorderWidth(b docxBorder) float64 { + if b.style == "" || b.style == "nil" || b.style == "none" { + return 0 + } + return math.Max(.25, b.width) +} +func drawDOCXBorder(page *PDFPage, b docxBorder, x1, y1, x2, y2 float64) { + w := docxBorderWidth(b) + if w == 0 { + return + } + if b.style == "dotted" || b.style == "dotDash" || b.style == "dashed" { + length := math.Hypot(x2-x1, y2-y1) + if length == 0 { + return + } + dash := w * 2 + if b.style == "dashed" { + dash = w * 6 + } + for at := 0.0; at < length; at += dash + w*2 { + end := math.Min(length, at+dash) + page.AddLine(x1+(x2-x1)*at/length, y1+(y2-y1)*at/length, x1+(x2-x1)*end/length, y1+(y2-y1)*end/length, b.color, w) + } + return + } + page.AddLine(x1, y1, x2, y2, b.color, w) +} +func drawDOCXTable(page *PDFPage, t docxTable, x, top float64) { + xs := []float64{x} + ys := []float64{top} + for _, w := range t.columns { + xs = append(xs, xs[len(xs)-1]+w) + } + for _, h := range t.rows { + ys = append(ys, ys[len(ys)-1]+h) + } + for _, c := range t.cells { + if c.continuation { + continue + } + left, right := xs[c.column], xs[c.column+c.span] + upper, lower := ys[c.row], ys[c.row+c.rowSpan] + if c.fill != nil { + page.AddRect(left, page.Height-lower, right-left, lower-upper, *c.fill) + } + drawDOCXBorder(page, c.borders["top"], left, page.Height-upper, right, page.Height-upper) + drawDOCXBorder(page, c.borders["bottom"], left, page.Height-lower, right, page.Height-lower) + drawDOCXBorder(page, c.borders["left"], left, page.Height-upper, left, page.Height-lower) + drawDOCXBorder(page, c.borders["right"], right, page.Height-upper, right, page.Height-lower) + contentTop := upper + c.margins.Top + docxBorderWidth(c.borders["top"]) + space := lower - upper - c.margins.Top - c.margins.Bottom - docxBorderWidth(c.borders["top"]) - docxBorderWidth(c.borders["bottom"]) - c.contentHeight + if c.align == "center" { + contentTop += space / 2 + } + if c.align == "bottom" { + contentTop += space + } + for _, p := range c.paras { + drawDOCXParagraph(page, p, left+c.margins.Left, contentTop, c.width-c.margins.Left-c.margins.Right) + contentTop += p.height + } + } +} + +func readDOCXImages(files officePackage, n *docxNode) ([]docxImage, error) { + if len(n.descendants("blip")) == 0 { + return nil, nil + } + data, err := files.read("word/_rels/document.xml.rels") + if err != nil { + return nil, err + } + rels, err := parseDOCXNode(data) + if err != nil { + return nil, err + } + targets := map[string]string{} + for _, r := range rels.children { + if r.attr("TargetMode") != "External" { + targets[r.attr("Id")] = r.attr("Target") + } + } + var out []docxImage + var visit func(*docxNode, *docxNode) error + visit = func(n, shape *docxNode) error { + if n.name == "shape" { + shape = n + } + if n.name == "drawing" { + blips := n.descendants("blip") + extents := n.descendants("extent") + if len(blips) == 0 || len(extents) == 0 { + return fmt.Errorf("unsupported DOCX drawing") + } + target, ok := targets[blips[0].attr("embed")] + if !ok { + return fmt.Errorf("DOCX drawing image relationship is missing") + } + name := path.Join("word", target) + data, err := files.read(name) + if err != nil { + return err + } + config, _, err := image.DecodeConfig(bytes.NewReader(data)) + if err != nil { + return fmt.Errorf("read DOCX image %s: %w", name, err) + } + if config.Width <= 0 || config.Height <= 0 || int64(config.Width) > 25000000/int64(config.Height) { + return fmt.Errorf("DOCX image exceeds 25 million pixels") + } + source, _, err := image.Decode(bytes.NewReader(data)) + if err != nil { + return fmt.Errorf("decode DOCX image %s: %w", name, err) + } + op, err := newPDFImage(source, source.Bounds()) + if err != nil { + return err + } + op.width = docxNumber(extents[0].attr("cx")) / 12700 + op.height = docxNumber(extents[0].attr("cy")) / 12700 + if op.width <= 0 || op.height <= 0 { + return fmt.Errorf("DOCX image has invalid extent") + } + picture := docxImage{op: op} + if shape != nil { + picture.floating = true + props := map[string]string{} + for _, v := range strings.Split(shape.attr("style"), ";") { + kv := strings.SplitN(v, ":", 2) + if len(kv) == 2 { + props[strings.TrimSpace(kv[0])] = strings.TrimSpace(kv[1]) + } + } + left, err := docxVMLLength(props["margin-left"]) + if err != nil { + return err + } + top, err := docxVMLLength(props["margin-top"]) + if err != nil { + return err + } + insetLeft, insetTop := 7.2, 3.6 + if inset := shape.child("textbox").attr("inset"); inset != "" { + parts := strings.Split(inset, ",") + if len(parts) != 4 { + return fmt.Errorf("invalid DOCX text-box inset") + } + insetLeft, err = docxVMLLength(parts[0]) + if err != nil { + return err + } + insetTop, err = docxVMLLength(parts[1]) + if err != nil { + return err + } + } + picture.left = left + insetLeft + picture.top = top + insetTop + } + out = append(out, picture) + return nil + } + for _, c := range n.children { + if err := visit(c, shape); err != nil { + return err + } + } + return nil + } + if err := visit(n, nil); err != nil { + return nil, err + } + return out, nil +} + +func docxUnsupportedMetafiles(files officePackage, body *docxNode) (bool, error) { + blips := body.descendants("blip") + if len(blips) == 0 { + return false, nil + } + data, err := files.read("word/_rels/document.xml.rels") + if err != nil { + return false, err + } + rels, err := parseDOCXNode(data) + if err != nil { + return false, err + } + targets := map[string]string{} + for _, rel := range rels.children { + if rel.attr("TargetMode") != "External" { + targets[rel.attr("Id")] = rel.attr("Target") + } + } + unsupported := false + for _, blip := range blips { + target, ok := targets[blip.attr("embed")] + if !ok { + return false, fmt.Errorf("DOCX drawing image relationship is missing") + } + name := path.Join("word", target) + if _, ok := files[name]; !ok { + return false, fmt.Errorf("Office package part %q is missing", name) + } + switch strings.ToLower(path.Ext(target)) { + case ".emf", ".wmf": + unsupported = true + } + } + return unsupported, nil +} + +func docxVMLLength(value string) (float64, error) { + value = strings.TrimSpace(value) + if value == "" { + return 0, nil + } + for _, unit := range []struct { + name string + scale float64 + }{{"pt", 1}, {"in", 72}, {"cm", 72 / 2.54}, {"mm", 72 / 25.4}, {"px", 72.0 / 96}} { + if strings.HasSuffix(value, unit.name) { + n, err := strconv.ParseFloat(strings.TrimSuffix(value, unit.name), 64) + if err != nil || math.IsNaN(n) || math.IsInf(n, 0) { + return 0, fmt.Errorf("invalid DOCX VML length %q", value) + } + return n * unit.scale, nil + } + } + if value == "0" { + return 0, nil + } + return 0, fmt.Errorf("unsupported DOCX VML length %q", value) +} + +// This structured renderer supports single-page table layouts. Page breaking, +// paragraph keep rules, and row splitting remain on the existing text path. +func renderDOCXTables(files officePackage, data []byte, size PageSize, margins Margins, options ConversionOptions) ([]byte, bool, error) { + root, err := parseDOCXNode(data) + if err != nil { + return nil, false, err + } + body := root.child("body") + if body == nil { + return nil, false, nil + } + if len(body.descendants("numPr")) > 0 || len(body.descendants("anchor")) > 0 || len(body.descendants("pageBreakBefore")) > 0 { + return nil, false, nil + } + for _, br := range body.descendants("br") { + if br.attr("type") == "page" { + return nil, false, nil + } + } + for _, height := range body.descendants("trHeight") { + if height.attr("hRule") == "exact" { + return nil, false, nil + } + } + for _, border := range append(body.descendants("tcBorders"), body.descendants("tblBorders")...) { + for _, edge := range border.children { + switch edge.attr("val") { + case "", "nil", "none", "single", "dotted", "dotDash", "dashed": + default: + return nil, false, nil + } + } + } + hasTable := false + for _, n := range body.children { + if n.name != "p" && n.name != "tbl" && n.name != "sectPr" && n.name != "bookmarkStart" && n.name != "bookmarkEnd" { + return nil, false, nil + } + if n.name == "tbl" { + hasTable = true + if len(n.descendants("tbl")) > 0 || len(n.descendants("drawing")) > 0 || n.child("tblPr").child("tblpPr") != nil || n.child("tblGrid") == nil { + return nil, false, nil + } + for _, c := range n.child("tblGrid").children { + if c.name == "gridCol" && docxNumber(c.attr("w")) <= 0 { + return nil, false, nil + } + } + } + if n.name == "p" && (n.child("pPr").child("sectPr") != nil || len(n.descendants("numPr")) > 0) { + return nil, false, nil + } + } + if !hasTable { + return nil, false, nil + } + unsupportedImages, err := docxUnsupportedMetafiles(files, body) + if err != nil { + return nil, true, err + } + if unsupportedImages { + return nil, false, nil + } + s, err := readDOCXStyles(files) + if err != nil { + return nil, true, err + } + grid := docxNumber(body.child("sectPr").child("docGrid").attr("linePitch")) / 20 + doc := NewPDFDocument() + page := doc.AddPage(size.Width, size.Height) + top := margins.Top + previousAfter := 0.0 + available := size.Width - margins.Left - margins.Right + for _, n := range body.children { + switch n.name { + case "p": + p, err := s.layoutParagraph(n, available, grid) + if err != nil { + return nil, true, err + } + p.style.before = math.Max(0, p.style.before-previousAfter) + p.height -= math.Min(previousAfter, s.paragraph(n).before) + if top+p.height > size.Height-margins.Bottom { + return nil, false, nil + } + drawDOCXParagraph(page, p, margins.Left, top, available) + pictures, err := readDOCXImages(files, n) + if err != nil { + return nil, true, err + } + for _, picture := range pictures { + op := picture.op + op.x = margins.Left + picture.left + op.y = size.Height - top - picture.top - op.height + if !picture.floating { + op.x = margins.Left + op.y = size.Height - top - op.height + p.height = math.Max(p.height, op.height) + } + page.operations = append(page.operations, op) + } + if top+p.height > size.Height-margins.Bottom { + return nil, false, nil + } + top += p.height + previousAfter = p.style.after + case "tbl": + t, err := s.table(n, available) + if err != nil { + return nil, true, err + } + height := 0.0 + for _, h := range t.rows { + height += h + } + if top+height > size.Height-margins.Bottom { + return nil, false, nil + } + left := margins.Left + t.indent + if t.align == "center" { + left = margins.Left + (available-t.width)/2 + } + if t.align == "right" { + left = size.Width - margins.Right - t.width + } + drawDOCXTable(page, t, left, top) + top += height + previousAfter = 0 + } + } + return doc.BytesWithOptions(PDFSaveOptions{Compress: options.Compress}), true, nil +} diff --git a/minipdf-go/docx_render_test.go b/minipdf-go/docx_render_test.go new file mode 100644 index 00000000..ebdf0342 --- /dev/null +++ b/minipdf-go/docx_render_test.go @@ -0,0 +1,367 @@ +package minipdf + +import ( + "bytes" + "encoding/binary" + "image" + "image/png" + "math" + "strings" + "testing" + + "golang.org/x/image/font/gofont/goregular" + "golang.org/x/image/font/sfnt" +) + +func docxTestStyles(t *testing.T, styles string) *docxStyles { + t.Helper() + ClearRegisteredFonts() + t.Cleanup(ClearRegisteredFonts) + RegisterFont("Portable Test", goregular.TTF) + files, err := openOfficePackage(officePackageBytes(t, map[string]string{"word/styles.xml": styles})) + if err != nil { + t.Fatal(err) + } + s, err := readDOCXStyles(files) + if err != nil { + t.Fatal(err) + } + return s +} + +func TestDOCXTableGridMergedCellsAndInheritedStyles(t *testing.T) { + s := docxTestStyles(t, ``) + n, err := parseDOCXNode([]byte(`

Merged

Wide

Left

Right

`)) + if err != nil { + t.Fatal(err) + } + table, err := s.table(n, 300) + if err != nil { + t.Fatal(err) + } + if table.width != 240 || table.cells[0].rowSpan != 2 || !table.cells[2].continuation || table.cells[1].width != 180 { + t.Fatalf("incorrect table geometry: %+v", table) + } + page := NewPDFDocument().AddPage(400, 500) + drawDOCXTable(page, table, 30, 50) + var merged []textOperation + var highlighted bool + for _, op := range page.operations { + switch op := op.(type) { + case textOperation: + if op.text == "M" { + merged = append(merged, op) + } + case rectOperation: + highlighted = highlighted || op.color == (PDFColor{Red: 1, Green: 1}) + } + } + if len(merged) != 1 || merged[0].x != 30 || merged[0].y >= 450 || merged[0].y <= 410 || !highlighted { + t.Fatalf("merged text or highlight not rendered: %+v, highlight=%t", merged, highlighted) + } + if table.cells[0].borders["left"].width != 1 { + t.Fatal("table style border was lost") + } +} + +func TestDOCXRunFontAndParagraphInheritance(t *testing.T) { + s := docxTestStyles(t, ``) + n, err := parseDOCXNode([]byte(`

AΩ

`)) + if err != nil { + t.Fatal(err) + } + + p, err := s.layoutParagraph(n, 200, 0) + if err != nil { + t.Fatal(err) + } + if p.style.before != 2 || p.style.after != 4 || p.style.align != "center" { + t.Fatalf("paragraph inheritance lost: %+v", p.style) + } + g := p.lines[0].glyphs + if len(g) != 2 || g[0].style.size != 14 || g[1].style.size != 9 || g[1].font == nil || g[0].style.color.Red != 1 || g[1].style.color.Blue != 1 { + t.Fatalf("run inheritance lost: %+v", g) + } + if math.Abs(p.lines[0].width-(measureXLSXFont("A", 14, g[0].font)+measureXLSXFont("Ω", 9, g[1].font))) > .001 { + t.Fatal("layout did not use glyph advances") + } +} + +func TestDOCXWrappingKeepsLatinWordsTogether(t *testing.T) { + s := docxTestStyles(t, ``) + n, err := parseDOCXNode([]byte(`

alpha beta

`)) + if err != nil { + t.Fatal(err) + } + f, err := s.font(s.defaults.run, 'a') + if err != nil { + t.Fatal(err) + } + p, err := s.layoutParagraph(n, measureXLSXFont("alpha be", 10, f), 0) + if err != nil { + t.Fatal(err) + } + var lines []string + for _, line := range p.lines { + var text strings.Builder + for _, g := range line.glyphs { + text.WriteRune(g.r) + } + lines = append(lines, text.String()) + } + if strings.Join(lines, "|") != "alpha |beta" { + t.Fatalf("Latin word split at arbitrary glyph: %v", lines) + } +} + +func TestDOCXCollectionFontRebasesTables(t *testing.T) { + collection := make([]byte, 16+len(goregular.TTF)) + copy(collection, "ttcf") + binary.BigEndian.PutUint32(collection[4:8], 0x10000) + binary.BigEndian.PutUint32(collection[8:12], 1) + binary.BigEndian.PutUint32(collection[12:16], 16) + copy(collection[16:], goregular.TTF) + n := int(binary.BigEndian.Uint16(collection[20:22])) + for i := 0; i < n; i++ { + r := collection[28+i*16 : 44+i*16] + binary.BigEndian.PutUint32(r[8:12], binary.BigEndian.Uint32(r[8:12])+16) + } + standalone, err := docxCollectionFont(collection, 0) + if err != nil { + t.Fatal(err) + } + f, err := sfnt.Parse(standalone) + if err != nil { + t.Fatal(err) + } + glyph, err := f.GlyphIndex(nil, 'Ω') + if err != nil || glyph == 0 { + t.Fatalf("collection glyph lost: %d %v", glyph, err) + } + if _, err = docxCollectionFont(collection, 1); err == nil { + t.Fatal("out-of-range collection index accepted") + } + broken := bytes.Clone(collection) + binary.BigEndian.PutUint32(broken[12:16], uint32(len(broken))) + if _, err = docxCollectionFont(broken, 0); err == nil { + t.Fatal("invalid collection offset accepted") + } +} + +func TestDOCXEquivalentFontInstancesUseCanonicalPDFResource(t *testing.T) { + ClearRegisteredFonts() + t.Cleanup(ClearRegisteredFonts) + RegisterFont("Portable Test", goregular.TTF) + a, err := loadDOCXFont("Portable Test", false, false) + if err != nil { + t.Fatal(err) + } + b, err := loadDOCXFont("Portable Test", false, false) + if err != nil { + t.Fatal(err) + } + d := NewPDFDocument() + p := d.AddPage(200, 200) + p.operations = append(p.operations, textOperation{text: "A", x: 10, y: 100, fontSize: 12, embedded: a}, textOperation{text: "Ω", x: 30, y: 100, fontSize: 12, embedded: b}) + pdf := d.Bytes() + if a.resource == "" || b.resource != a.resource || bytes.Count(pdf, []byte("/Subtype /Type0")) != 1 || bytes.Contains(pdf, []byte("BT / ")) { + t.Fatal("equivalent font instances have unresolved PDF resources") + } +} + +func TestDOCXMissingImageRelationshipReturnsError(t *testing.T) { + n, err := parseDOCXNode([]byte(`

`)) + if err != nil { + t.Fatal(err) + } + files, err := openOfficePackage(officePackageBytes(t, map[string]string{"word/_rels/document.xml.rels": ""})) + if err != nil { + t.Fatal(err) + } + _, err = readDOCXImages(files, n) + if err == nil || !strings.Contains(err.Error(), "relationship") { + t.Fatalf("missing image was silently discarded: %v", err) + } +} + +func TestDOCXPackagePictureExtentAndTextBoxInsets(t *testing.T) { + var encoded bytes.Buffer + if err := png.Encode(&encoded, image.NewRGBA(image.Rect(0, 0, 2, 3))); err != nil { + t.Fatal(err) + } + files, err := openOfficePackage(officePackageBytes(t, map[string]string{"word/_rels/document.xml.rels": ``, "word/media/picture.png": encoded.String()})) + if err != nil { + t.Fatal(err) + } + n, err := parseDOCXNode([]byte(`

`)) + if err != nil { + t.Fatal(err) + } + images, err := readDOCXImages(files, n) + if err != nil { + t.Fatal(err) + } + if len(images) != 1 || !images[0].floating || images[0].left != 75 || images[0].top != 6 || images[0].op.width != 20 || images[0].op.height != 30 || images[0].op.pixelWidth != 2 { + t.Fatalf("picture geometry lost: %+v", images) + } +} + +func TestDOCXFELayoutScalesCJKCapableFontMetrics(t *testing.T) { + data := bytes.Clone(goregular.TTF) + n := int(binary.BigEndian.Uint16(data[4:6])) + found := false + for i := 0; i < n; i++ { + r := data[12+i*16 : 28+i*16] + if string(r[:4]) == "OS/2" { + o := int(binary.BigEndian.Uint32(r[8:12])) + if binary.BigEndian.Uint32(r[12:16]) < 86 { + t.Skip("portable test font has no code-page capabilities") + } + binary.BigEndian.PutUint32(data[o+78:o+82], 1<<18) + found = true + } + } + if !found { + t.Fatal("test font has no OS/2 table") + } + ClearRegisteredFonts() + t.Cleanup(ClearRegisteredFonts) + RegisterFont("CJK capable", data) + s := &docxStyles{nodes: map[string]*docxNode{}, fonts: map[string]*embeddedFont{}, theme: map[string]string{}, defaults: docxParagraphStyle{run: docxRunStyle{size: 10, fonts: map[string]string{"ascii": "CJK capable"}}}} + root, err := parseDOCXNode([]byte(`

A

`)) + if err != nil { + t.Fatal(err) + } + plain, err := s.layoutParagraph(root, 100, 0) + if err != nil { + t.Fatal(err) + } + s.cjkMetrics = true + adjusted, err := s.layoutParagraph(root, 100, 0) + if err != nil { + t.Fatal(err) + } + if math.Abs(adjusted.lines[0].height/plain.lines[0].height-1.27) > .001 || adjusted.lines[0].width != plain.lines[0].width { + t.Fatal("FE compatibility did not scale vertical metrics independently of glyph width") + } +} + +func TestDOCXEastAsianPunctuationDoesNotStartOrEndWrappedLine(t *testing.T) { + ClearRegisteredFonts() + t.Cleanup(ClearRegisteredFonts) + f, err := loadDOCXFont("SimSun", false, false) + if err != nil { + t.Fatal(err) + } + if f == nil { + t.Skip("requires licensed installed SimSun") + } + s := &docxStyles{nodes: map[string]*docxNode{}, fonts: map[string]*embeddedFont{"SimSun/false/false": f}, theme: map[string]string{}, defaults: docxParagraphStyle{run: docxRunStyle{size: 8, fonts: map[string]string{"eastAsia": "SimSun"}}}} + n, err := parseDOCXNode([]byte(`

机房(扶梯上机舱)

`)) + if err != nil { + t.Fatal(err) + } + p, err := s.layoutParagraph(n, 24.9, 0) + if err != nil { + t.Fatal(err) + } + var lines []string + for _, line := range p.lines { + var text strings.Builder + for _, g := range line.glyphs { + text.WriteRune(g.r) + } + lines = append(lines, text.String()) + } + if strings.Join(lines, "|") != "机房|(扶梯|上机|舱)" { + t.Fatalf("invalid East Asian punctuation break: %v", lines) + } +} + +func TestDOCXUnsupportedMetafilesRetainLegacyConversion(t *testing.T) { + document := `

Text preserved

Cell preserved

` + for _, extension := range []string{"emf", "WMF", "png", "jpeg"} { + t.Run(extension, func(t *testing.T) { + name := "word/media/image." + extension + input := officePackageBytes(t, map[string]string{ + "word/document.xml": document, + "word/_rels/document.xml.rels": ``, + name: "not a raster image", + }) + files, err := openOfficePackage(input) + if err != nil { + t.Fatal(err) + } + _, supported, err := renderDOCXTables(files, []byte(document), PageSizeA4, Margins{Left: 40, Top: 40, Right: 40, Bottom: 40}, ConversionOptions{}) + if extension == "png" || extension == "jpeg" { + if !supported || err == nil || !strings.Contains(err.Error(), "DOCX image") { + t.Fatalf("malformed raster image was swallowed: supported=%t, err=%v", supported, err) + } + return + } + if supported || err != nil { + t.Fatalf("metafile should retain legacy conversion: supported=%t, err=%v", supported, err) + } + pdf, err := ConvertBytesToPDF(input) + assertPDFContains(t, pdf, err, "Text preserved", "Cell preserved") + }) + } +} + +func TestDOCXStructuredPaginationRetainsLegacyConversion(t *testing.T) { + ClearRegisteredFonts() + t.Cleanup(ClearRegisteredFonts) + RegisterFont("Portable Test", goregular.TTF) + const table = `

Table

` + for _, test := range []struct { + name, tail string + supported bool + }{ + {"table overflow", table, false}, + {"paragraph overflow", `

Tail

`, false}, + {"single-page flow", `

Tail

`, true}, + } { + t.Run(test.name, func(t *testing.T) { + data := []byte(`` + table + test.tail + ``) + input := officePackageBytes(t, map[string]string{ + "word/document.xml": string(data), + "word/styles.xml": ``, + }) + files, err := openOfficePackage(input) + if err != nil { + t.Fatal(err) + } + size := PageSize{Width: 200, Height: 100} + margins := Margins{Left: 10, Top: 10, Right: 10, Bottom: 10} + options := ConversionOptions{PageSize: &size, Margins: &margins} + _, supported, err := renderDOCXTables(files, data, size, margins, options) + if err != nil || supported != test.supported { + t.Fatalf("single-page capability: supported=%t, err=%v", supported, err) + } + if test.supported { + return + } + pages, sourceSize, sourceMargins, err := extractDOCX(data) + if err != nil { + t.Fatal(err) + } + var textPages []textPage + for _, lines := range pages { + textPages = append(textPages, textPage{lines: lines, size: sourceSize, margins: sourceMargins}) + } + want := renderTextPages(textPages, options) + got, err := ConvertBytesToPDFWithOptions(input, options) + if err != nil || !bytes.Equal(got, want) { + t.Fatalf("pagination fallback changed legacy PDF: %v", err) + } + }) + } +} + +func TestDOCXUnsupportedLayoutKeepsTextConverter(t *testing.T) { + data := []byte(`

First
Second

`) + _, supported, err := renderDOCXTables(nil, data, PageSizeA4, Margins{Left: 40, Right: 40, Top: 40, Bottom: 40}, ConversionOptions{}) + if err != nil || supported { + t.Fatalf("unsupported explicit pagination was not retained on legacy path: %t, %v", supported, err) + } +} diff --git a/minipdf-go/pdf.go b/minipdf-go/pdf.go index fa906f0c..1fc51638 100644 --- a/minipdf-go/pdf.go +++ b/minipdf-go/pdf.go @@ -235,13 +235,13 @@ func (document *PDFDocument) BytesWithOptions(options PDFSaveOptions) []byte { if font == embedded { continue } - for alias, canonical := range seenFonts { - alias.resource = canonical.resource - alias.objectID = canonical.objectID - } font.resource = fmt.Sprintf("FU%d", index+1) font.objectID = appendEmbeddedFontObjects(&objects, font) } + for alias, canonical := range seenFonts { + alias.resource = canonical.resource + alias.objectID = canonical.objectID + } italicResources := "" if hasItalic { regular := appendPDFObject(&objects, []byte("<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica-Oblique /Encoding /WinAnsiEncoding >>")) From 3cf00185fa74be1ad23bc6d7e5766bd82ef2be53 Mon Sep 17 00:00:00 2001 From: Wei Lin Date: Tue, 17 Nov 2026 00:54:33 +0800 Subject: [PATCH 2/3] fix(go): address DOCX renderer review findings Bound border drawing, preserve font emphasis and alias glyph maps, honor Korean font selection and document grid types, correct cell borders and image targets, and retain legacy behavior for unsupported layouts and missing host fonts. Add focused regression tests. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- minipdf-go/README.md | 15 +- minipdf-go/docx_font.go | 44 +++++- minipdf-go/docx_render.go | 126 ++++++++++++--- minipdf-go/docx_render_test.go | 273 +++++++++++++++++++++++++++++++++ minipdf-go/font.go | 19 +-- minipdf-go/pdf.go | 40 ++++- 6 files changed, 481 insertions(+), 36 deletions(-) diff --git a/minipdf-go/README.md b/minipdf-go/README.md index 9d69ca3c..8b836be6 100644 --- a/minipdf-go/README.md +++ b/minipdf-go/README.md @@ -141,17 +141,26 @@ offsets and text-box insets. Image decoding is limited to 25 million pixels. Missing or invalid embedded images produce errors rather than disappearing. Documents requiring unsupported section changes, numbering, anchored drawings, +text-bearing VML text boxes, omitted row grid columns (`gridBefore`/`gridAfter`), exact-height rows, multi-page structured layout, or referenced EMF/WMF images retain the existing text converter. If measured paragraph, inline-image, or table flow would cross the first page's content boundary, the entire document uses the text converter; structured pagination, keep rules, and row splitting -are not implemented. Metafile formats are checked before +are not implemented. Tables extending beyond the physical page width also retain +text conversion. Metafile formats are checked before structured rendering; malformed PNG/JPEG images still produce decoding errors. +Linked-only images and inline paragraphs mixing images with text, multiple images, +or explicit line breaks also retain text conversion. Single image-only paragraphs +honor alignment, indentation, and paragraph spacing. Line-grid snapping requires +`docGrid` type `lines` or `linesAndChars`; an omitted/default type does not snap. +Dashed borders use a single native PDF stroke, without retained segment expansion. Images inside table cells, complex drawing geometry, conditional table styles, headers/footers, and complex-script shaping remain unsupported. Structured text uses matching registered fonts or selected licensed Windows -fonts, with Arial/SimSun glyph fallback when available. Missing Unicode glyphs -produce an explicit error on the structured path. Fonts are embedded without +fonts, with Arial/SimSun glyph fallback when available. Requested bold/italic is +synthesized only when the loaded face lacks that emphasis. An unavailable host +font required for Unicode text retains legacy conversion; a present font with +missing glyphs still produces an explicit error on the structured path. Fonts are embedded without subsetting, so large CJK fonts can substantially increase PDF size. XLSX text output skips entirely empty pages within worksheets containing text, diff --git a/minipdf-go/docx_font.go b/minipdf-go/docx_font.go index e13386bc..40ce4420 100644 --- a/minipdf-go/docx_font.go +++ b/minipdf-go/docx_font.go @@ -82,6 +82,14 @@ func loadDOCXFont(name string, bold, italic bool) (*embeddedFont, error) { break } } + if data == nil && (bold || italic) { + for _, registered := range RegisteredFonts() { + if strings.EqualFold(registered.Name, name) { + data = registered.Data + break + } + } + } if data == nil && runtime.GOOS == "windows" { var file string switch strings.ToLower(name) { @@ -105,7 +113,14 @@ func loadDOCXFont(name string, bold, italic bool) (*embeddedFont, error) { } } default: - return readXLSXFont(name, bold, italic) + f, err := readXLSXFont(name, bold, italic) + if err == nil && f == nil && (bold || italic) { + f, err = readXLSXFont(name, false, false) + } + if f != nil { + f.nativeBold, f.nativeItalic = docxFontEmphasis(f.data) + } + return f, err } if root := os.Getenv("WINDIR"); root != "" { var err error @@ -138,6 +153,7 @@ func loadDOCXFont(name string, bold, italic bool) (*embeddedFont, error) { return nil, err } result := &embeddedFont{name: sanitizePDFFontName(variant), data: data, font: parsed, runeToGlyph: make(map[rune]sfnt.GlyphIndex), glyphToRune: make(map[sfnt.GlyphIndex]rune), advances: make([]float64, parsed.NumGlyphs()), ascent: float64(metrics.Ascent) / float64(ppem), descent: float64(metrics.Descent) / float64(ppem)} + result.nativeBold, result.nativeItalic = docxFontEmphasis(data) for i := range result.advances { a, err := parsed.GlyphAdvance(nil, sfnt.GlyphIndex(i), ppem, font.HintingNone) if err != nil { @@ -148,6 +164,32 @@ func loadDOCXFont(name string, bold, italic bool) (*embeddedFont, error) { return result, nil } +func docxFontEmphasis(data []byte) (bold, italic bool) { + if len(data) < 12 { + return + } + n := int(binary.BigEndian.Uint16(data[4:6])) + if n > (len(data)-12)/16 { + return + } + for i := 0; i < n; i++ { + r := data[12+i*16 : 28+i*16] + o, length := int(binary.BigEndian.Uint32(r[8:12])), int(binary.BigEndian.Uint32(r[12:16])) + if o < 0 || length < 0 || o > len(data)-length { + continue + } + if string(r[:4]) == "OS/2" && length >= 64 { + flags := binary.BigEndian.Uint16(data[o+62 : o+64]) + return flags&(1<<5) != 0, flags&1 != 0 + } + if string(r[:4]) == "head" && length >= 46 { + flags := binary.BigEndian.Uint16(data[o+44 : o+46]) + bold, italic = flags&1 != 0, flags&2 != 0 + } + } + return +} + func docxFontCJK(data []byte) bool { if len(data) < 12 { return false diff --git a/minipdf-go/docx_render.go b/minipdf-go/docx_render.go index aae45569..b08241be 100644 --- a/minipdf-go/docx_render.go +++ b/minipdf-go/docx_render.go @@ -3,6 +3,7 @@ package minipdf import ( "bytes" "encoding/xml" + "errors" "fmt" "image" _ "image/jpeg" @@ -15,6 +16,9 @@ import ( "unicode" ) +var errDOCXFontUnavailable = errors.New("DOCX font unavailable") +var errDOCXTableLayoutUnsupported = errors.New("DOCX table layout unsupported") + type docxNode struct { name string attrs map[string]string @@ -355,7 +359,7 @@ func (s *docxStyles) font(style docxRunStyle, r rune) (*embeddedFont, error) { return f, nil } func docxAsian(r rune) bool { - return unicode.Is(unicode.Han, r) || unicode.Is(unicode.Hiragana, r) || unicode.Is(unicode.Katakana, r) || r >= 0x3000 && r <= 0x303f || r >= 0xff00 && r <= 0xffef || r == 0x25a1 + return unicode.Is(unicode.Han, r) || unicode.Is(unicode.Hangul, r) || unicode.Is(unicode.Hiragana, r) || unicode.Is(unicode.Katakana, r) || r >= 0x3000 && r <= 0x303f || r >= 0xff00 && r <= 0xffef || r == 0x25a1 } type docxGlyph struct { @@ -431,7 +435,7 @@ func (s *docxStyles) layoutParagraph(n *docxNode, width, grid float64) (docxPara g.descent *= 1.27 } } else if r > 127 { - return fmt.Errorf("DOCX character U+%04X requires an installed or registered font", r) + return fmt.Errorf("DOCX character U+%04X requires an installed or registered font: %w", r, errDOCXFontUnavailable) } glyphs = append(glyphs, g) } @@ -564,7 +568,7 @@ func drawDOCXParagraph(page *PDFPage, p docxParagraph, x, top, width float64) { if g.style.highlight != nil { page.AddRect(left, page.Height-top-line.height, g.width, line.height, *g.style.highlight) } - page.operations = append(page.operations, textOperation{text: string(g.r), x: left, y: baseline, fontSize: g.style.size, horizontalScale: 100, color: g.style.color, bold: g.style.bold, italic: g.style.italic, embedded: g.font}) + page.operations = append(page.operations, textOperation{text: string(g.r), x: left, y: baseline, fontSize: g.style.size, horizontalScale: 100, color: g.style.color, bold: g.style.bold, italic: g.style.italic, embedded: g.font, synthesize: true}) left += g.width } top += line.height @@ -661,6 +665,12 @@ func (s *docxStyles) table(n *docxNode, available float64) (docxTable, error) { t.columns[i] *= t.width / gridWidth } active := map[int]*docxCell{} + rowCount := 0 + for _, row := range n.children { + if row.name == "tr" { + rowCount++ + } + } for _, row := range n.children { if row.name != "tr" { continue @@ -679,7 +689,7 @@ func (s *docxStyles) table(n *docxNode, available float64) (docxTable, error) { span = 1 } if column+span > len(t.columns) { - return t, fmt.Errorf("DOCX cell span exceeds table grid") + return t, fmt.Errorf("DOCX cell span exceeds table grid: %w", errDOCXTableLayoutUnsupported) } cell := &docxCell{column: column, span: span, row: ri, rowSpan: 1, margins: docxCellMargins(cp.child("tcMar"), tm), align: cp.value("vAlign"), borders: map[string]docxBorder{}} for i := column; i < column+span; i++ { @@ -690,6 +700,9 @@ func (s *docxStyles) table(n *docxNode, available float64) (docxTable, error) { if edge == "top" && ri > 0 { key = "insideH" } + if edge == "bottom" && ri < rowCount-1 { + key = "insideH" + } if edge == "left" && column > 0 { key = "insideV" } @@ -711,7 +724,7 @@ func (s *docxStyles) table(n *docxNode, available float64) (docxTable, error) { cell.continuation = true start.borders["bottom"] = cell.borders["bottom"] } else { - return t, fmt.Errorf("DOCX vertical merge has no matching start") + return t, fmt.Errorf("DOCX vertical merge has no matching start: %w", errDOCXTableLayoutUnsupported) } } else { delete(active, column) @@ -732,7 +745,7 @@ func (s *docxStyles) table(n *docxNode, available float64) (docxTable, error) { column += span } if column != len(t.columns) { - return t, fmt.Errorf("DOCX row does not cover table grid") + return t, fmt.Errorf("DOCX row does not cover table grid: %w", errDOCXTableLayoutUnsupported) } } for _, c := range t.cells { @@ -783,18 +796,11 @@ func drawDOCXBorder(page *PDFPage, b docxBorder, x1, y1, x2, y2 float64) { return } if b.style == "dotted" || b.style == "dotDash" || b.style == "dashed" { - length := math.Hypot(x2-x1, y2-y1) - if length == 0 { - return - } dash := w * 2 if b.style == "dashed" { dash = w * 6 } - for at := 0.0; at < length; at += dash + w*2 { - end := math.Min(length, at+dash) - page.AddLine(x1+(x2-x1)*at/length, y1+(y2-y1)*at/length, x1+(x2-x1)*end/length, y1+(y2-y1)*end/length, b.color, w) - } + page.operations = append(page.operations, lineOperation{x1: x1, y1: y1, x2: x2, y2: y2, color: b.color, width: w, dash: []float64{dash, w * 2}}) return } page.AddLine(x1, y1, x2, y2, b.color, w) @@ -870,7 +876,7 @@ func readDOCXImages(files officePackage, n *docxNode) ([]docxImage, error) { if !ok { return fmt.Errorf("DOCX drawing image relationship is missing") } - name := path.Join("word", target) + name := xlsxResolveRelationshipTarget("word/document.xml", target) data, err := files.read(name) if err != nil { return err @@ -968,17 +974,29 @@ func docxUnsupportedMetafiles(files officePackage, body *docxNode) (bool, error) } unsupported := false for _, blip := range blips { + if blip.attr("embed") == "" && blip.attr("link") != "" { + unsupported = true + continue + } target, ok := targets[blip.attr("embed")] if !ok { return false, fmt.Errorf("DOCX drawing image relationship is missing") } - name := path.Join("word", target) + name := xlsxResolveRelationshipTarget("word/document.xml", target) if _, ok := files[name]; !ok { return false, fmt.Errorf("Office package part %q is missing", name) } switch strings.ToLower(path.Ext(target)) { case ".emf", ".wmf": unsupported = true + case ".png", ".jpg", ".jpeg": + data, err := files.read(name) + if err != nil { + return false, err + } + if _, _, err := image.DecodeConfig(bytes.NewReader(data)); err != nil { + return false, fmt.Errorf("read DOCX image %s: %w", name, err) + } } } return unsupported, nil @@ -1021,6 +1039,16 @@ func renderDOCXTables(files officePackage, data []byte, size PageSize, margins M if len(body.descendants("numPr")) > 0 || len(body.descendants("anchor")) > 0 || len(body.descendants("pageBreakBefore")) > 0 { return nil, false, nil } + if len(body.descendants("gridBefore")) > 0 || len(body.descendants("gridAfter")) > 0 { + return nil, false, nil + } + for _, box := range body.descendants("txbxContent") { + for _, text := range box.descendants("t") { + if text.text != "" { + return nil, false, nil + } + } + } for _, br := range body.descendants("br") { if br.attr("type") == "page" { return nil, false, nil @@ -1070,11 +1098,17 @@ func renderDOCXTables(files officePackage, data []byte, size PageSize, margins M if unsupportedImages { return nil, false, nil } + if docxUnsupportedInlineFlow(body) { + return nil, false, nil + } s, err := readDOCXStyles(files) if err != nil { return nil, true, err } - grid := docxNumber(body.child("sectPr").child("docGrid").attr("linePitch")) / 20 + grid := 0.0 + if g := body.child("sectPr").child("docGrid"); g.attr("type") == "lines" || g.attr("type") == "linesAndChars" { + grid = docxNumber(g.attr("linePitch")) / 20 + } doc := NewPDFDocument() page := doc.AddPage(size.Width, size.Height) top := margins.Top @@ -1085,6 +1119,9 @@ func renderDOCXTables(files officePackage, data []byte, size PageSize, margins M case "p": p, err := s.layoutParagraph(n, available, grid) if err != nil { + if errors.Is(err, errDOCXFontUnavailable) { + return nil, false, nil + } return nil, true, err } p.style.before = math.Max(0, p.style.before-previousAfter) @@ -1102,9 +1139,18 @@ func renderDOCXTables(files officePackage, data []byte, size PageSize, margins M op.x = margins.Left + picture.left op.y = size.Height - top - picture.top - op.height if !picture.floating { - op.x = margins.Left - op.y = size.Height - top - op.height - p.height = math.Max(p.height, op.height) + contentWidth := available - p.style.left - p.style.right - p.style.first + if op.width > contentWidth { + return nil, false, nil + } + op.x = margins.Left + p.style.left + p.style.first + if p.style.align == "center" { + op.x += (contentWidth - op.width) / 2 + } else if p.style.align == "right" { + op.x += contentWidth - op.width + } + op.y = size.Height - top - p.style.before - op.height + p.height = p.style.before + math.Max(p.height-p.style.before-p.style.after, op.height) + p.style.after } page.operations = append(page.operations, op) } @@ -1116,6 +1162,9 @@ func renderDOCXTables(files officePackage, data []byte, size PageSize, margins M case "tbl": t, err := s.table(n, available) if err != nil { + if errors.Is(err, errDOCXFontUnavailable) || errors.Is(err, errDOCXTableLayoutUnsupported) { + return nil, false, nil + } return nil, true, err } height := 0.0 @@ -1132,6 +1181,9 @@ func renderDOCXTables(files officePackage, data []byte, size PageSize, margins M if t.align == "right" { left = size.Width - margins.Right - t.width } + if left < 0 || left+t.width > size.Width { + return nil, false, nil + } drawDOCXTable(page, t, left, top) top += height previousAfter = 0 @@ -1139,3 +1191,37 @@ func renderDOCXTables(files officePackage, data []byte, size PageSize, margins M } return doc.BytesWithOptions(PDFSaveOptions{Compress: options.Compress}), true, nil } + +func docxUnsupportedInlineFlow(body *docxNode) bool { + for _, p := range body.descendants("p") { + inlineCount := 0 + var countInline func(*docxNode) + countInline = func(n *docxNode) { + // VML pictures have floating placement, not paragraph inline flow. + if n.name == "pict" { + return + } + if n.name == "drawing" && n.child("inline") != nil { + inlineCount++ + } + for _, c := range n.children { + countInline(c) + } + } + countInline(p) + if inlineCount > 1 { + return true + } + if inlineCount == 1 { + if len(p.descendants("br")) > 0 || len(p.descendants("cr")) > 0 || len(p.descendants("tab")) > 0 { + return true + } + for _, text := range p.descendants("t") { + if text.text != "" { + return true + } + } + } + } + return false +} diff --git a/minipdf-go/docx_render_test.go b/minipdf-go/docx_render_test.go index ebdf0342..f2c7f5d1 100644 --- a/minipdf-go/docx_render_test.go +++ b/minipdf-go/docx_render_test.go @@ -3,12 +3,15 @@ package minipdf import ( "bytes" "encoding/binary" + "errors" + "fmt" "image" "image/png" "math" "strings" "testing" + "golang.org/x/image/font/gofont/gobolditalic" "golang.org/x/image/font/gofont/goregular" "golang.org/x/image/font/sfnt" ) @@ -167,6 +170,10 @@ func TestDOCXEquivalentFontInstancesUseCanonicalPDFResource(t *testing.T) { if a.resource == "" || b.resource != a.resource || bytes.Count(pdf, []byte("/Subtype /Type0")) != 1 || bytes.Contains(pdf, []byte("BT / ")) { t.Fatal("equivalent font instances have unresolved PDF resources") } + encoded, ok := b.encode("Ω") + if !ok || !bytes.Contains(pdf, []byte("BT /"+a.resource+" 12 Tf 0 0 0 rg 30 100 Td <"+encoded+"> Tj")) || bytes.Contains(pdf, []byte("30 100 Td (?)")) { + t.Fatal("alias Unicode text did not use the canonical embedded glyph resource") + } } func TestDOCXMissingImageRelationshipReturnsError(t *testing.T) { @@ -365,3 +372,269 @@ func TestDOCXUnsupportedLayoutKeepsTextConverter(t *testing.T) { t.Fatalf("unsupported explicit pagination was not retained on legacy path: %t, %v", supported, err) } } + +func TestDOCXDashRenderingHasBoundedOperations(t *testing.T) { + for _, style := range []string{"dotted", "dotDash", "dashed"} { + page := NewPDFDocument().AddPage(612, 792) + drawDOCXBorder(page, docxBorder{style: style, width: .25}, 10, 10, float64(2147483647)/20, 10) + if len(page.operations) != 1 { + t.Fatalf("%s retained %d operations for off-page geometry", style, len(page.operations)) + } + var stream bytes.Buffer + page.operations[0].appendPDF(&stream, nil) + if !strings.Contains(stream.String(), "] 0 d ") || bytes.Count(stream.Bytes(), []byte(" l S")) != 1 || !strings.HasSuffix(stream.String(), "Q\n") { + t.Fatalf("dash stroke is not a single isolated native PDF operation: %s", &stream) + } + } + s := docxTestStyles(t, docxReviewStyles) + data := []byte(`

`) + files, err := openOfficePackage(officePackageBytes(t, map[string]string{"word/styles.xml": docxReviewStyles})) + if err != nil { + t.Fatal(err) + } + root, err := parseDOCXNode(data) + if err != nil { + t.Fatal(err) + } + table, err := s.table(root.child("body").child("tbl"), 500) + if err != nil { + t.Fatal(err) + } + page := NewPDFDocument().AddPage(612, 792) + drawDOCXTable(page, table, 40, 40) + if len(page.operations) != 1 { + t.Fatalf("full extreme-grid table retained %d operations", len(page.operations)) + } + _, supported, err := renderDOCXTables(files, data, PageSizeA4, Margins{Left: 40, Right: 40, Top: 40, Bottom: 40}, ConversionOptions{}) + if supported || err != nil { + t.Fatalf("table outside physical page did not decline native layout: %t %v", supported, err) + } +} + +func TestDOCXSynthesizesOnlyMissingFontEmphasis(t *testing.T) { + ClearRegisteredFonts() + t.Cleanup(ClearRegisteredFonts) + RegisterFont("Portable Test", goregular.TTF) + for _, native := range []bool{false, true} { + if native { + RegisterFont("Portable Test Bold Italic", gobolditalic.TTF) + } + f, err := loadDOCXFont("Portable Test", true, true) + if err != nil || f == nil { + t.Fatalf("styled registered font unavailable: %v", err) + } + if f.nativeBold != native || f.nativeItalic != native { + t.Fatalf("native emphasis incorrectly identified: %+v", f) + } + f.collect("Ω") + f.resource = "FU1" + var stream bytes.Buffer + op := textOperation{text: "Ω", x: 10, y: 20, fontSize: 12, bold: true, italic: true, color: PDFColor{Red: 1}, embedded: f, synthesize: true} + op.appendPDF(&stream, nil) + if !strings.Contains(stream.String(), "/FU1 12 Tf") || strings.Contains(stream.String(), "(?)") { + t.Fatal("emphasis lost Unicode embedding") + } + if native { + if strings.Contains(stream.String(), "2 Tr") || strings.Contains(stream.String(), " Tm") { + t.Fatal("native bold italic face was double-synthesized") + } + } else if !strings.Contains(stream.String(), "2 Tr") || !strings.Contains(stream.String(), "0.21256 1 10 20 Tm") || !strings.Contains(stream.String(), "1 0 0 RG") || !strings.HasSuffix(stream.String(), "Q\n") { + t.Fatalf("missing face was not synthesized with isolated stroke/slant: %s", &stream) + } + } +} + +func TestDOCXHangulUsesEastAsianAndKoreanThemeFonts(t *testing.T) { + data := bytes.Clone(goregular.TTF) + original, err := sfnt.Parse(data) + if err != nil { + t.Fatal(err) + } + glyph, err := original.GlyphIndex(nil, 'Ω') + if err != nil { + t.Fatal(err) + } + // Supply a synthetic cmap for the portable font; no host Korean font is required. + cmap := make([]byte, 40) + binary.BigEndian.PutUint16(cmap[2:4], 1) + binary.BigEndian.PutUint16(cmap[4:6], 3) + binary.BigEndian.PutUint16(cmap[6:8], 10) + binary.BigEndian.PutUint32(cmap[8:12], 12) + binary.BigEndian.PutUint16(cmap[12:14], 12) + binary.BigEndian.PutUint32(cmap[16:20], 28) + binary.BigEndian.PutUint32(cmap[24:28], 1) + binary.BigEndian.PutUint32(cmap[28:32], 0xac00) + binary.BigEndian.PutUint32(cmap[32:36], 0xac00) + binary.BigEndian.PutUint32(cmap[36:40], uint32(glyph)) + for i, n := 0, int(binary.BigEndian.Uint16(data[4:6])); i < n; i++ { + r := data[12+i*16 : 28+i*16] + if string(r[:4]) == "cmap" { + binary.BigEndian.PutUint32(r[8:12], uint32(len(data))) + binary.BigEndian.PutUint32(r[12:16], uint32(len(cmap))) + } + } + data = append(data, cmap...) + ClearRegisteredFonts() + t.Cleanup(ClearRegisteredFonts) + RegisterFont("Korean Test", data) + s := &docxStyles{fonts: map[string]*embeddedFont{}, theme: map[string]string{"minor:Hang": "Korean Test"}} + for _, fonts := range []map[string]string{{"eastAsia": "Korean Test", "hAnsi": "Wrong font"}, {"eastAsiaTheme": "minorEastAsia", "hAnsi": "Wrong font"}} { + f, err := s.font(docxRunStyle{fonts: fonts, lang: "ko-KR"}, '가') + if err != nil || f == nil || !bytes.Equal(f.data, data) || !f.canEncode("가") { + t.Fatalf("Hangul did not select the East Asian Korean font: %v", err) + } + } +} + +func TestDOCXInteriorBottomBordersAndMergeFinalEdge(t *testing.T) { + s := docxTestStyles(t, ``) + for _, inside := range []string{"none", "dashed"} { + xml := `

` + n, err := parseDOCXNode([]byte(xml)) + if err != nil { + t.Fatal(err) + } + table, err := s.table(n, 300) + if err != nil { + t.Fatal(err) + } + if table.cells[1].borders["bottom"].style != inside || table.cells[0].borders["bottom"].style != "single" || table.cells[3].borders["bottom"].width != 2 || table.cells[3].borders["top"].style != "dotted" { + t.Fatalf("interior/outer/override/merge edges lost for %s", inside) + } + } +} + +const docxReviewTable = `

Cell

` +const docxReviewStyles = `` + +func docxReviewPackage(t *testing.T, body string, parts map[string]string) (officePackage, []byte, []byte) { + t.Helper() + if parts == nil { + parts = map[string]string{} + } + data := []byte(`` + body + ``) + parts["word/document.xml"] = string(data) + parts["word/styles.xml"] = docxReviewStyles + input := officePackageBytes(t, parts) + files, err := openOfficePackage(input) + if err != nil { + t.Fatal(err) + } + return files, data, input +} + +func TestDOCXUnsupportedReviewLayoutsRetainLegacy(t *testing.T) { + ClearRegisteredFonts() + t.Cleanup(ClearRegisteredFonts) + RegisterFont("Portable Test", goregular.TTF) + var encoded bytes.Buffer + if err := png.Encode(&encoded, image.NewRGBA(image.Rect(0, 0, 2, 3))); err != nil { + t.Fatal(err) + } + picture := `` + for _, test := range []struct{ name, body string }{ + {"gridBefore", strings.Replace(docxReviewTable, "", ``, 1)}, + {"gridAfter", strings.Replace(docxReviewTable, "", ``, 1)}, + {"span", strings.Replace(docxReviewTable, "", ``, 1)}, + {"merge", strings.Replace(docxReviewTable, "", ``, 1)}, + {"text box", `

Box text

` + docxReviewTable}, + {"mixed inline text", `

Before` + picture + `

` + docxReviewTable}, + {"multiple inline images", `

` + picture + picture + `

` + docxReviewTable}, + {"inline break", `


` + picture + `

` + docxReviewTable}, + {"linked image", `

` + strings.Replace(picture, `embed="picture"`, `link="external"`, 1) + `

` + docxReviewTable}, + } { + t.Run(test.name, func(t *testing.T) { + files, data, input := docxReviewPackage(t, test.body, map[string]string{"word/_rels/document.xml.rels": ``, "word/media/image.png": encoded.String()}) + _, supported, err := renderDOCXTables(files, data, PageSizeA4, Margins{Left: 40, Top: 40, Right: 40, Bottom: 40}, ConversionOptions{}) + if supported || err != nil { + t.Fatalf("layout did not fall back: supported=%t err=%v", supported, err) + } + pdf, err := ConvertBytesToPDF(input) + if err != nil { + t.Fatal(err) + } + pages, size, margins, err := extractDOCX(data) + if err != nil { + t.Fatal(err) + } + var legacy []textPage + var text []string + for _, lines := range pages { + legacy = append(legacy, textPage{lines: lines, size: size, margins: margins}) + text = append(text, lines...) + } + if !bytes.Equal(pdf, renderTextPages(legacy, ConversionOptions{})) || !strings.Contains(strings.Join(text, "\n"), "Cell") { + t.Fatal("fallback changed legacy text conversion") + } + if test.name == "text box" && !strings.Contains(strings.Join(text, "\n"), "Box text") { + t.Fatal("fallback lost text-box text") + } + }) + } +} + +func TestDOCXImageOnlyAlignmentAndAbsoluteTargets(t *testing.T) { + ClearRegisteredFonts() + t.Cleanup(ClearRegisteredFonts) + RegisterFont("Portable Test", goregular.TTF) + var encoded bytes.Buffer + if err := png.Encode(&encoded, image.NewRGBA(image.Rect(0, 0, 2, 3))); err != nil { + t.Fatal(err) + } + for _, test := range []struct { + align string + x float64 + }{{"left", 40}, {"center", 90}, {"right", 140}} { + body := `

` + docxReviewTable + files, data, _ := docxReviewPackage(t, body, map[string]string{"word/_rels/document.xml.rels": ``, "word/media/image.png": encoded.String()}) + pdf, supported, err := renderDOCXTables(files, data, PageSize{Width: 200, Height: 300}, Margins{Left: 40, Top: 40, Right: 40, Bottom: 40}, ConversionOptions{}) + if err != nil || !supported || !bytes.Contains(pdf, []byte(fmt.Sprintf("20 0 0 30 %s 225 cm", pdfNumber(test.x)))) { + t.Fatalf("%s image lost absolute target/spacing/alignment: supported=%t err=%v", test.align, supported, err) + } + } +} + +func TestDOCXGridTypeControlsLineSnapping(t *testing.T) { + ClearRegisteredFonts() + t.Cleanup(ClearRegisteredFonts) + RegisterFont("Portable Test", goregular.TTF) + var plain []byte + for _, typ := range []string{"", "default", "snapToChars", "lines", "linesAndChars"} { + files, data, _ := docxReviewPackage(t, `

Text

`+docxReviewTable+``, nil) + pdf, supported, err := renderDOCXTables(files, data, PageSizeA4, Margins{Left: 40, Top: 40, Right: 40, Bottom: 40}, ConversionOptions{}) + if err != nil || !supported { + t.Fatalf("grid %s failed: %v", typ, err) + } + if typ == "" { + plain = pdf + } + if (typ == "default" || typ == "snapToChars") && !bytes.Equal(pdf, plain) { + t.Fatalf("inactive grid %s altered paragraph layout", typ) + } + if (typ == "lines" || typ == "linesAndChars") && bytes.Equal(pdf, plain) { + t.Fatalf("active grid %s did not snap lines", typ) + } + } +} + +func TestDOCXUnavailableFontsFallbackButMissingGlyphsFail(t *testing.T) { + ClearRegisteredFonts() + t.Cleanup(ClearRegisteredFonts) + t.Setenv("WINDIR", "") + for _, body := range []string{`

é

` + docxReviewTable, strings.Replace(docxReviewTable, "Cell", "é", 1)} { + files, data, input := docxReviewPackage(t, body, nil) + _, supported, err := renderDOCXTables(files, data, PageSizeA4, Margins{Left: 40, Top: 40, Right: 40, Bottom: 40}, ConversionOptions{}) + if err != nil || supported { + t.Fatalf("missing environment font did not fall back: %t %v", supported, err) + } + if _, err := ConvertBytesToPDF(input); err != nil { + t.Fatalf("legacy font fallback failed: %v", err) + } + } + RegisterFont("Portable Test", goregular.TTF) + files, data, _ := docxReviewPackage(t, strings.Replace(docxReviewTable, "Cell", "\U0001f600", 1), nil) + _, supported, err := renderDOCXTables(files, data, PageSizeA4, Margins{Left: 40, Top: 40, Right: 40, Bottom: 40}, ConversionOptions{}) + if !supported || err == nil || errors.Is(err, errDOCXFontUnavailable) || !strings.Contains(err.Error(), "has no glyph") { + t.Fatalf("present font's missing glyph was silently downgraded: %t %v", supported, err) + } +} diff --git a/minipdf-go/font.go b/minipdf-go/font.go index fae73b63..31944ffd 100644 --- a/minipdf-go/font.go +++ b/minipdf-go/font.go @@ -13,15 +13,16 @@ import ( ) type embeddedFont struct { - name string - data []byte - font *sfnt.Font - runeToGlyph map[rune]sfnt.GlyphIndex - glyphToRune map[sfnt.GlyphIndex]rune - objectID int - resource string - advances []float64 - ascent, descent float64 + name string + data []byte + font *sfnt.Font + runeToGlyph map[rune]sfnt.GlyphIndex + glyphToRune map[sfnt.GlyphIndex]rune + objectID int + resource string + advances []float64 + ascent, descent float64 + nativeBold, nativeItalic bool } func prepareEmbeddedFont(pages []*PDFPage) *embeddedFont { diff --git a/minipdf-go/pdf.go b/minipdf-go/pdf.go index 1fc51638..8c987282 100644 --- a/minipdf-go/pdf.go +++ b/minipdf-go/pdf.go @@ -84,6 +84,7 @@ type textOperation struct { bold bool italic bool embedded *embeddedFont + synthesize bool } func (operation textOperation) appendPDF(buffer *bytes.Buffer, embedded *embeddedFont) { @@ -96,17 +97,37 @@ func (operation textOperation) appendPDF(buffer *bytes.Buffer, embedded *embedde } if embedded != nil { if encoded, ok := embedded.encode(operation.text); ok { - fmt.Fprintf(buffer, "BT /%s %s Tf %s%s %s %s rg %s %s Td <%s> Tj ET\n", + syntheticBold := operation.synthesize && operation.bold && !embedded.nativeBold + syntheticItalic := operation.synthesize && operation.italic && !embedded.nativeItalic + synthetic := syntheticBold || syntheticItalic + position := pdfNumber(operation.x) + " " + pdfNumber(operation.y) + " Td" + if synthetic { + buffer.WriteString("q ") + if syntheticBold { + fmt.Fprintf(buffer, "%s w %s %s %s RG ", pdfNumber(operation.fontSize/30), pdfNumber(operation.color.Red), pdfNumber(operation.color.Green), pdfNumber(operation.color.Blue)) + } + if syntheticItalic { + position = "1 0 0.21256 1 " + pdfNumber(operation.x) + " " + pdfNumber(operation.y) + " Tm" + } + } + mode := "" + if syntheticBold { + mode = "2 Tr " + } + fmt.Fprintf(buffer, "BT /%s %s Tf %s%s%s %s %s rg %s <%s> Tj ET\n", embedded.resource, pdfNumber(operation.fontSize), horizontalScale, + mode, pdfNumber(operation.color.Red), pdfNumber(operation.color.Green), pdfNumber(operation.color.Blue), - pdfNumber(operation.x), - pdfNumber(operation.y), + position, encoded, ) + if synthetic { + buffer.WriteString("Q\n") + } return } } @@ -154,9 +175,17 @@ type lineOperation struct { x1, y1, x2, y2 float64 color PDFColor width float64 + dash []float64 } func (operation lineOperation) appendPDF(buffer *bytes.Buffer, _ *embeddedFont) { + if len(operation.dash) > 0 { + buffer.WriteString("q [") + for _, length := range operation.dash { + buffer.WriteString(pdfNumber(length) + " ") + } + buffer.WriteString("] 0 d ") + } fmt.Fprintf(buffer, "%s %s %s RG %s w %s %s m %s %s l S\n", pdfNumber(operation.color.Red), pdfNumber(operation.color.Green), @@ -167,6 +196,9 @@ func (operation lineOperation) appendPDF(buffer *bytes.Buffer, _ *embeddedFont) pdfNumber(operation.x2), pdfNumber(operation.y2), ) + if len(operation.dash) > 0 { + buffer.WriteString("Q\n") + } } func (document *PDFDocument) Bytes() []byte { @@ -241,6 +273,8 @@ func (document *PDFDocument) BytesWithOptions(options PDFSaveOptions) []byte { for alias, canonical := range seenFonts { alias.resource = canonical.resource alias.objectID = canonical.objectID + alias.runeToGlyph = canonical.runeToGlyph + alias.glyphToRune = canonical.glyphToRune } italicResources := "" if hasItalic { From 4ebe339411c9a31eeaa0e1f12e35636d279be1f5 Mon Sep 17 00:00:00 2001 From: Wei Lin Date: Tue, 17 Nov 2026 09:10:49 +0800 Subject: [PATCH 3/3] chore: split non-.NET implementations into PdfLibrarys repositories Preserve each language's Git history in PdfLibrarys/minipdf-go, minipdf-java, minipdf-node, minipdf-python, and minipdf-rs. Migrate CI/release workflows, fixture dependencies, repository metadata, and pinned Rust bindings before removing the original language trees. Retain .NET source, tests, demo, API, and shared benchmark tooling. Update contribution guidance, issue templates, and all translated READMEs to link independent implementations. Validation: all five standalone CI matrices pass; .NET solution builds and all 469 corpus-enabled tests pass; 36 reviewer automation tests pass; .NET Invoice visual score 0.9832. Java full 28-case DOCX comparison preserves page counts with no visual decrease beyond 0.002; approved issue91 regression score improves from 0.9600 to 0.9711. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .claude/skills/minipdf-contribution/SKILL.md | 30 +- .github/ISSUE_TEMPLATE/bug_report.yml | 2 - .github/ISSUE_TEMPLATE/conversion_quality.yml | 2 - .github/ISSUE_TEMPLATE/documentation.yml | 2 - .github/ISSUE_TEMPLATE/feature_request.yml | 2 - .github/ISSUE_TEMPLATE/question.yml | 2 - .github/PULL_REQUEST_TEMPLATE.md | 2 +- .github/workflows/crates-publish.yml | 81 - .github/workflows/go-ci.yml | 64 - .github/workflows/go-release.yml | 124 - .github/workflows/java-ci.yml | 102 - .github/workflows/java-publish.yml | 122 - .github/workflows/node-ci.yml | 96 - .github/workflows/npm-publish.yml | 230 - .github/workflows/pypi-publish.yml | 140 - .github/workflows/python-ci.yml | 59 - .github/workflows/rust-ecosystem-release.yml | 69 - .gitignore | 3 - CONTRIBUTING.md | 37 +- FEATURE_PARITY.md | 64 +- MAINTAINERS.md | 4 +- README.md | 115 +- ROADMAP.md | 19 +- SECURITY.md | 7 +- documents/README.fr.md | 117 +- documents/README.it.md | 117 +- documents/README.ja.md | 117 +- documents/README.ko.md | 117 +- documents/README.zh-CN.md | 117 +- documents/README.zh-TW.md | 117 +- minipdf-go/LICENSE | 200 - minipdf-go/README.md | 265 - minipdf-go/cmd/minipdf/main.go | 240 - minipdf-go/cmd/minipdf/main_test.go | 96 - minipdf-go/docx.go | 131 - minipdf-go/docx_font.go | 214 - minipdf-go/docx_render.go | 1227 --- minipdf-go/docx_render_test.go | 640 -- minipdf-go/font.go | 217 - minipdf-go/go.mod | 7 - minipdf-go/go.sum | 4 - minipdf-go/minipdf.go | 232 - minipdf-go/minipdf_test.go | 133 - minipdf-go/office.go | 324 - minipdf-go/office_test.go | 1124 --- minipdf-go/pdf.go | 365 - minipdf-go/pdf_image.go | 53 - minipdf-go/pdf_test.go | 119 - minipdf-go/pptx.go | 110 - minipdf-go/xlsx.go | 531 -- minipdf-go/xlsx_chart.go | 497 -- minipdf-go/xlsx_color.go | 212 - minipdf-go/xlsx_color_test.go | 119 - minipdf-go/xlsx_conditional.go | 203 - minipdf-go/xlsx_conditional_test.go | 221 - minipdf-go/xlsx_font.go | 96 - minipdf-go/xlsx_footer.go | 190 - minipdf-go/xlsx_layout_test.go | 269 - minipdf-go/xlsx_number.go | 192 - minipdf-go/xlsx_picture.go | 122 - minipdf-go/xlsx_print.go | 240 - minipdf-go/xlsx_print_test.go | 254 - minipdf-go/xlsx_render.go | 1048 --- .../.mvn/wrapper/maven-wrapper.properties | 3 - minipdf-java/README.md | 107 - minipdf-java/minipdf-cli/pom.xml | 49 - .../minipdf/cli/MiniPdfCommand.java | 245 - minipdf-java/minipdf-tests/pom.xml | 51 - .../minipdf/BasicOfficeConversionTest.java | 362 - .../minipdf/ClassicFixtureSmokeTest.java | 372 - .../minipdf/FontRegistrationTest.java | 39 - .../minipdf/OfficeFormatDetectionTest.java | 61 - .../minipdf/OoxmlSecurityTest.java | 52 - .../minisoftware/minipdf/PageSizeTest.java | 36 - .../minisoftware/minipdf/PdfDocumentTest.java | 226 - .../minipdf/cli/MiniPdfCommandTest.java | 128 - .../internal/FontEmbeddingPolicyTest.java | 17 - .../internal/docx/PoiDocxRendererTest.java | 325 - .../internal/xlsx/PoiXlsxRendererTest.java | 171 - minipdf-java/minipdf/pom.xml | 34 - .../minipdf/ConversionOptions.java | 25 - .../github/minisoftware/minipdf/MiniPdf.java | 98 - .../minipdf/MiniPdfException.java | 29 - .../minisoftware/minipdf/OfficeFormat.java | 8 - .../github/minisoftware/minipdf/PageSize.java | 55 - .../github/minisoftware/minipdf/PdfColor.java | 63 - .../minisoftware/minipdf/PdfDocument.java | 237 - .../github/minisoftware/minipdf/PdfPage.java | 83 - .../minisoftware/minipdf/RegisteredFont.java | 39 - .../minipdf/TrueTypeFontData.java | 518 -- .../minipdf/internal/FontEmbeddingPolicy.java | 14 - .../internal/OfficePackageDetector.java | 28 - .../minipdf/internal/OoxmlPackage.java | 120 - .../minipdf/internal/SecureXml.java | 31 - .../internal/SimplePdfTextRenderer.java | 454 -- .../minipdf/internal/docx/DocxConverter.java | 187 - .../internal/docx/PoiDocxRenderer.java | 4964 ------------ .../minipdf/internal/pptx/PptxConverter.java | 246 - .../internal/xlsx/LegacyVmlPictureReader.java | 327 - .../internal/xlsx/PoiXlsxRenderer.java | 2341 ------ .../minipdf/internal/xlsx/XlsxConverter.java | 126 - minipdf-java/mvnw | 295 - minipdf-java/mvnw.cmd | 189 - minipdf-java/pom.xml | 165 - minipdf-node/Cargo.lock | 920 --- minipdf-node/Cargo.toml | 23 - minipdf-node/LICENSE | 194 - minipdf-node/README.md | 110 - minipdf-node/build.rs | 3 - minipdf-node/index.d.ts | 22 - minipdf-node/index.js | 312 - minipdf-node/lib/index.d.ts | 44 - minipdf-node/lib/index.js | 13 - minipdf-node/package-lock.json | 51 - minipdf-node/package.json | 65 - minipdf-node/scripts/postprocess-loader.js | 62 - minipdf-node/scripts/prepare-release.js | 92 - minipdf-node/src/lib.rs | 114 - minipdf-node/test/index.test.js | 155 - minipdf-python/LICENSE | 200 - minipdf-python/README.md | 66 - minipdf-python/native/Cargo.lock | 886 --- minipdf-python/native/Cargo.toml | 20 - minipdf-python/native/src/lib.rs | 87 - minipdf-python/pyproject.toml | 62 - minipdf-python/src/minipdf/__init__.py | 28 - minipdf-python/src/minipdf/__main__.py | 3 - minipdf-python/src/minipdf/_native.pyi | 19 - minipdf-python/src/minipdf/api.py | 82 - minipdf-python/src/minipdf/cli.py | 50 - minipdf-python/src/minipdf/docx.py | 146 - minipdf-python/src/minipdf/errors.py | 14 - minipdf-python/src/minipdf/office.py | 120 - minipdf-python/src/minipdf/options.py | 38 - minipdf-python/src/minipdf/pdf.py | 128 - minipdf-python/src/minipdf/pptx.py | 103 - minipdf-python/src/minipdf/xlsx.py | 113 - minipdf-python/tests/helpers.py | 133 - minipdf-python/tests/test_api.py | 109 - minipdf-python/tests/test_cli.py | 54 - minipdf-python/tests/test_docx.py | 42 - minipdf-python/tests/test_options.py | 24 - minipdf-rs/Cargo.lock | 892 --- minipdf-rs/Cargo.toml | 29 - minipdf-rs/README.md | 192 - minipdf-rs/crates/minipdf-cli/Cargo.toml | 22 - minipdf-rs/crates/minipdf-cli/src/main.rs | 239 - minipdf-rs/crates/minipdf/Cargo.toml | 29 - minipdf-rs/crates/minipdf/src/docx.rs | 2598 ------- minipdf-rs/crates/minipdf/src/fonts.rs | 260 - minipdf-rs/crates/minipdf/src/lib.rs | 232 - minipdf-rs/crates/minipdf/src/office.rs | 31 - minipdf-rs/crates/minipdf/src/pdf.rs | 1558 ---- minipdf-rs/crates/minipdf/src/pptx.rs | 2840 ------- minipdf-rs/crates/minipdf/src/xlsx.rs | 6642 ----------------- scripts/Build-Python-Native.ps1 | 35 - scripts/Invoke-LanguageVisualBenchmark.ps1 | 158 +- scripts/Invoke-NpmStageRelease.ps1 | 140 - scripts/Run-All-Language-VisualBenchmarks.ps1 | 44 - scripts/Run-Go-VisualBenchmark.ps1 | 2 - scripts/Run-Java-VisualBenchmark.ps1 | 2 - scripts/Run-Node-VisualBenchmark.ps1 | 2 - scripts/Run-Python-VisualBenchmark.ps1 | 2 - scripts/Run-Rust-Benchmark-Matrix.ps1 | 120 - scripts/Run-Rust-Benchmark.ps1 | 2 - scripts/Run-Rust-VisualBenchmark.ps1 | 2 - 166 files changed, 183 insertions(+), 45492 deletions(-) delete mode 100644 .github/workflows/crates-publish.yml delete mode 100644 .github/workflows/go-ci.yml delete mode 100644 .github/workflows/go-release.yml delete mode 100644 .github/workflows/java-ci.yml delete mode 100644 .github/workflows/java-publish.yml delete mode 100644 .github/workflows/node-ci.yml delete mode 100644 .github/workflows/npm-publish.yml delete mode 100644 .github/workflows/pypi-publish.yml delete mode 100644 .github/workflows/python-ci.yml delete mode 100644 .github/workflows/rust-ecosystem-release.yml delete mode 100644 minipdf-go/LICENSE delete mode 100644 minipdf-go/README.md delete mode 100644 minipdf-go/cmd/minipdf/main.go delete mode 100644 minipdf-go/cmd/minipdf/main_test.go delete mode 100644 minipdf-go/docx.go delete mode 100644 minipdf-go/docx_font.go delete mode 100644 minipdf-go/docx_render.go delete mode 100644 minipdf-go/docx_render_test.go delete mode 100644 minipdf-go/font.go delete mode 100644 minipdf-go/go.mod delete mode 100644 minipdf-go/go.sum delete mode 100644 minipdf-go/minipdf.go delete mode 100644 minipdf-go/minipdf_test.go delete mode 100644 minipdf-go/office.go delete mode 100644 minipdf-go/office_test.go delete mode 100644 minipdf-go/pdf.go delete mode 100644 minipdf-go/pdf_image.go delete mode 100644 minipdf-go/pdf_test.go delete mode 100644 minipdf-go/pptx.go delete mode 100644 minipdf-go/xlsx.go delete mode 100644 minipdf-go/xlsx_chart.go delete mode 100644 minipdf-go/xlsx_color.go delete mode 100644 minipdf-go/xlsx_color_test.go delete mode 100644 minipdf-go/xlsx_conditional.go delete mode 100644 minipdf-go/xlsx_conditional_test.go delete mode 100644 minipdf-go/xlsx_font.go delete mode 100644 minipdf-go/xlsx_footer.go delete mode 100644 minipdf-go/xlsx_layout_test.go delete mode 100644 minipdf-go/xlsx_number.go delete mode 100644 minipdf-go/xlsx_picture.go delete mode 100644 minipdf-go/xlsx_print.go delete mode 100644 minipdf-go/xlsx_print_test.go delete mode 100644 minipdf-go/xlsx_render.go delete mode 100644 minipdf-java/.mvn/wrapper/maven-wrapper.properties delete mode 100644 minipdf-java/README.md delete mode 100644 minipdf-java/minipdf-cli/pom.xml delete mode 100644 minipdf-java/minipdf-cli/src/main/java/io/github/minisoftware/minipdf/cli/MiniPdfCommand.java delete mode 100644 minipdf-java/minipdf-tests/pom.xml delete mode 100644 minipdf-java/minipdf-tests/src/test/java/io/github/minisoftware/minipdf/BasicOfficeConversionTest.java delete mode 100644 minipdf-java/minipdf-tests/src/test/java/io/github/minisoftware/minipdf/ClassicFixtureSmokeTest.java delete mode 100644 minipdf-java/minipdf-tests/src/test/java/io/github/minisoftware/minipdf/FontRegistrationTest.java delete mode 100644 minipdf-java/minipdf-tests/src/test/java/io/github/minisoftware/minipdf/OfficeFormatDetectionTest.java delete mode 100644 minipdf-java/minipdf-tests/src/test/java/io/github/minisoftware/minipdf/OoxmlSecurityTest.java delete mode 100644 minipdf-java/minipdf-tests/src/test/java/io/github/minisoftware/minipdf/PageSizeTest.java delete mode 100644 minipdf-java/minipdf-tests/src/test/java/io/github/minisoftware/minipdf/PdfDocumentTest.java delete mode 100644 minipdf-java/minipdf-tests/src/test/java/io/github/minisoftware/minipdf/cli/MiniPdfCommandTest.java delete mode 100644 minipdf-java/minipdf-tests/src/test/java/io/github/minisoftware/minipdf/internal/FontEmbeddingPolicyTest.java delete mode 100644 minipdf-java/minipdf-tests/src/test/java/io/github/minisoftware/minipdf/internal/docx/PoiDocxRendererTest.java delete mode 100644 minipdf-java/minipdf-tests/src/test/java/io/github/minisoftware/minipdf/internal/xlsx/PoiXlsxRendererTest.java delete mode 100644 minipdf-java/minipdf/pom.xml delete mode 100644 minipdf-java/minipdf/src/main/java/io/github/minisoftware/minipdf/ConversionOptions.java delete mode 100644 minipdf-java/minipdf/src/main/java/io/github/minisoftware/minipdf/MiniPdf.java delete mode 100644 minipdf-java/minipdf/src/main/java/io/github/minisoftware/minipdf/MiniPdfException.java delete mode 100644 minipdf-java/minipdf/src/main/java/io/github/minisoftware/minipdf/OfficeFormat.java delete mode 100644 minipdf-java/minipdf/src/main/java/io/github/minisoftware/minipdf/PageSize.java delete mode 100644 minipdf-java/minipdf/src/main/java/io/github/minisoftware/minipdf/PdfColor.java delete mode 100644 minipdf-java/minipdf/src/main/java/io/github/minisoftware/minipdf/PdfDocument.java delete mode 100644 minipdf-java/minipdf/src/main/java/io/github/minisoftware/minipdf/PdfPage.java delete mode 100644 minipdf-java/minipdf/src/main/java/io/github/minisoftware/minipdf/RegisteredFont.java delete mode 100644 minipdf-java/minipdf/src/main/java/io/github/minisoftware/minipdf/TrueTypeFontData.java delete mode 100644 minipdf-java/minipdf/src/main/java/io/github/minisoftware/minipdf/internal/FontEmbeddingPolicy.java delete mode 100644 minipdf-java/minipdf/src/main/java/io/github/minisoftware/minipdf/internal/OfficePackageDetector.java delete mode 100644 minipdf-java/minipdf/src/main/java/io/github/minisoftware/minipdf/internal/OoxmlPackage.java delete mode 100644 minipdf-java/minipdf/src/main/java/io/github/minisoftware/minipdf/internal/SecureXml.java delete mode 100644 minipdf-java/minipdf/src/main/java/io/github/minisoftware/minipdf/internal/SimplePdfTextRenderer.java delete mode 100644 minipdf-java/minipdf/src/main/java/io/github/minisoftware/minipdf/internal/docx/DocxConverter.java delete mode 100644 minipdf-java/minipdf/src/main/java/io/github/minisoftware/minipdf/internal/docx/PoiDocxRenderer.java delete mode 100644 minipdf-java/minipdf/src/main/java/io/github/minisoftware/minipdf/internal/pptx/PptxConverter.java delete mode 100644 minipdf-java/minipdf/src/main/java/io/github/minisoftware/minipdf/internal/xlsx/LegacyVmlPictureReader.java delete mode 100644 minipdf-java/minipdf/src/main/java/io/github/minisoftware/minipdf/internal/xlsx/PoiXlsxRenderer.java delete mode 100644 minipdf-java/minipdf/src/main/java/io/github/minisoftware/minipdf/internal/xlsx/XlsxConverter.java delete mode 100755 minipdf-java/mvnw delete mode 100644 minipdf-java/mvnw.cmd delete mode 100644 minipdf-java/pom.xml delete mode 100644 minipdf-node/Cargo.lock delete mode 100644 minipdf-node/Cargo.toml delete mode 100644 minipdf-node/LICENSE delete mode 100644 minipdf-node/README.md delete mode 100644 minipdf-node/build.rs delete mode 100644 minipdf-node/index.d.ts delete mode 100644 minipdf-node/index.js delete mode 100644 minipdf-node/lib/index.d.ts delete mode 100644 minipdf-node/lib/index.js delete mode 100644 minipdf-node/package-lock.json delete mode 100644 minipdf-node/package.json delete mode 100644 minipdf-node/scripts/postprocess-loader.js delete mode 100644 minipdf-node/scripts/prepare-release.js delete mode 100644 minipdf-node/src/lib.rs delete mode 100644 minipdf-node/test/index.test.js delete mode 100644 minipdf-python/LICENSE delete mode 100644 minipdf-python/README.md delete mode 100644 minipdf-python/native/Cargo.lock delete mode 100644 minipdf-python/native/Cargo.toml delete mode 100644 minipdf-python/native/src/lib.rs delete mode 100644 minipdf-python/pyproject.toml delete mode 100644 minipdf-python/src/minipdf/__init__.py delete mode 100644 minipdf-python/src/minipdf/__main__.py delete mode 100644 minipdf-python/src/minipdf/_native.pyi delete mode 100644 minipdf-python/src/minipdf/api.py delete mode 100644 minipdf-python/src/minipdf/cli.py delete mode 100644 minipdf-python/src/minipdf/docx.py delete mode 100644 minipdf-python/src/minipdf/errors.py delete mode 100644 minipdf-python/src/minipdf/office.py delete mode 100644 minipdf-python/src/minipdf/options.py delete mode 100644 minipdf-python/src/minipdf/pdf.py delete mode 100644 minipdf-python/src/minipdf/pptx.py delete mode 100644 minipdf-python/src/minipdf/xlsx.py delete mode 100644 minipdf-python/tests/helpers.py delete mode 100644 minipdf-python/tests/test_api.py delete mode 100644 minipdf-python/tests/test_cli.py delete mode 100644 minipdf-python/tests/test_docx.py delete mode 100644 minipdf-python/tests/test_options.py delete mode 100644 minipdf-rs/Cargo.lock delete mode 100644 minipdf-rs/Cargo.toml delete mode 100644 minipdf-rs/README.md delete mode 100644 minipdf-rs/crates/minipdf-cli/Cargo.toml delete mode 100644 minipdf-rs/crates/minipdf-cli/src/main.rs delete mode 100644 minipdf-rs/crates/minipdf/Cargo.toml delete mode 100644 minipdf-rs/crates/minipdf/src/docx.rs delete mode 100644 minipdf-rs/crates/minipdf/src/fonts.rs delete mode 100644 minipdf-rs/crates/minipdf/src/lib.rs delete mode 100644 minipdf-rs/crates/minipdf/src/office.rs delete mode 100644 minipdf-rs/crates/minipdf/src/pdf.rs delete mode 100644 minipdf-rs/crates/minipdf/src/pptx.rs delete mode 100644 minipdf-rs/crates/minipdf/src/xlsx.rs delete mode 100644 scripts/Build-Python-Native.ps1 delete mode 100644 scripts/Invoke-NpmStageRelease.ps1 delete mode 100644 scripts/Run-All-Language-VisualBenchmarks.ps1 delete mode 100644 scripts/Run-Go-VisualBenchmark.ps1 delete mode 100644 scripts/Run-Java-VisualBenchmark.ps1 delete mode 100644 scripts/Run-Node-VisualBenchmark.ps1 delete mode 100644 scripts/Run-Python-VisualBenchmark.ps1 delete mode 100644 scripts/Run-Rust-Benchmark-Matrix.ps1 delete mode 100644 scripts/Run-Rust-Benchmark.ps1 delete mode 100644 scripts/Run-Rust-VisualBenchmark.ps1 diff --git a/.claude/skills/minipdf-contribution/SKILL.md b/.claude/skills/minipdf-contribution/SKILL.md index 36632a86..5901a757 100644 --- a/.claude/skills/minipdf-contribution/SKILL.md +++ b/.claude/skills/minipdf-contribution/SKILL.md @@ -1,6 +1,6 @@ --- name: minipdf-contribution -description: "Guide a first-time MiniPdf contributor through choosing an implementation language, selecting a failing visual benchmark case, making a focused rendering fix, and validating the complete benchmark. Use when contributing rendering improvements to MiniPdf in .NET, Rust, Java, Go, Python, or Node.js." +description: "Guide a first-time MiniPdf contributor through selecting a failing .NET visual benchmark case, making a focused rendering fix, and validating the complete benchmark. Use when contributing rendering improvements to MiniPdf in .NET." compatibility: "Designed for Claude Code, Codex, and GitHub Copilot. Requires Git, PowerShell, the selected language toolchain, Python benchmark dependencies, an installed LibreOffice executable, and a LibreOffice core source checkout." --- @@ -21,20 +21,15 @@ If the source checkout is missing, tell the user it is required for renderer-beh If the LibreOffice executable is missing, explain that cloning the source does not install LibreOffice and ask the user how they want to install or provide the executable. Do not run visual benchmarks until both the executable and source checkout are available. -## 2. Choose an Implementation +## 2. Use the .NET Implementation -Ask which implementation language the user wants to improve and wait for an explicit answer: +This repository contains only .NET. For other implementations, use their independent PdfLibrarys repositories: | Choice | Repository path | Benchmark command | |---|---|---| | .NET | `src/` | `scripts/Run-DotNet-VisualBenchmark.ps1` | -| Rust | `minipdf-rs/` | `scripts/Run-Rust-VisualBenchmark.ps1` | -| Java | `minipdf-java/` | `scripts/Run-Java-VisualBenchmark.ps1` | -| Go | `minipdf-go/` | `scripts/Run-Go-VisualBenchmark.ps1` | -| Python | `minipdf-python/` | `scripts/Run-Python-VisualBenchmark.ps1` | -| Node.js | `minipdf-node/` | `scripts/Run-Node-VisualBenchmark.ps1` | -Do not choose a language on the user's behalf. +Use the .NET source and benchmark commands below. ## 3. Select a Failing Case @@ -44,10 +39,10 @@ Find the available reports for the selected language under: artifacts/-benchmark///report/comparison_report.md ``` -`` is `dotnet`, `rust`, `java`, `go`, `python`, or `node`; `` is `classic` or `issue`; and `` is `xlsx`, `docx`, or `pptx`. For example: +`` is `dotnet`; `` is `classic` or `issue`; and `` is `xlsx`, `docx`, or `pptx`. For example: ```text -artifacts/java-benchmark/issue/xlsx/report/comparison_report.md +artifacts/dotnet-benchmark/issue/xlsx/report/comparison_report.md ``` Inspect the report data and select one valid case whose overall score is below `0.95`. Prefer the lowest reproducible score across the available reports for that language. Exclude missing or invalid candidate/reference PDFs. If no current report exists for a suite and format, generate it with the corresponding full benchmark command before selecting a case. @@ -74,29 +69,24 @@ Compare the complete final report with the preserved baseline. Reject or revise Run the selected implementation's relevant unit tests and `git diff --check` after the full benchmark. Report the exact commands, before-and-after scores, page counts, image paths, and any remaining risk. -## Cross-Language Visual Benchmarks +## .NET Visual Benchmarks -Use the following form for .NET, Rust, Java, Go, Python, and Node: +Use the following form for .NET: ```powershell -scripts/Run--VisualBenchmark.ps1 -Suite -Format -MaxCases +scripts/Run-DotNet-VisualBenchmark.ps1 -Suite -Format -MaxCases ``` Supported commands: ```powershell scripts/Run-DotNet-VisualBenchmark.ps1 -Suite -Format -MaxCases -scripts/Run-Rust-VisualBenchmark.ps1 -Suite -Format -MaxCases -scripts/Run-Java-VisualBenchmark.ps1 -Suite -Format -MaxCases -scripts/Run-Go-VisualBenchmark.ps1 -Suite -Format -MaxCases -scripts/Run-Python-VisualBenchmark.ps1 -Suite -Format -MaxCases -scripts/Run-Node-VisualBenchmark.ps1 -Suite -Format -MaxCases ``` During diagnosis, add `-Filter ""` for a focused run. For final validation, omit both `-Filter` and `-MaxCases`: ```powershell -scripts/Run--VisualBenchmark.ps1 -Suite -Format +scripts/Run-DotNet-VisualBenchmark.ps1 -Suite -Format ``` Use only suite and format combinations supported by the benchmark runner. Keep generated PDFs, images, heatmaps, and full logs under `artifacts/`; summarize results in chat instead of embedding image data or complete reports. \ No newline at end of file diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.yml index a0e936f0..9ccb6f91 100644 --- a/.github/ISSUE_TEMPLATE/bug_report.yml +++ b/.github/ISSUE_TEMPLATE/bug_report.yml @@ -15,8 +15,6 @@ body: description: Which language implementation is affected? options: - .NET (C#) - - Rust - - Both / shared validations: required: true diff --git a/.github/ISSUE_TEMPLATE/conversion_quality.yml b/.github/ISSUE_TEMPLATE/conversion_quality.yml index 659c431b..060a57cc 100644 --- a/.github/ISSUE_TEMPLATE/conversion_quality.yml +++ b/.github/ISSUE_TEMPLATE/conversion_quality.yml @@ -15,8 +15,6 @@ body: description: Which language implementation is affected? options: - .NET (C#) - - Rust - - Both / shared validations: required: true diff --git a/.github/ISSUE_TEMPLATE/documentation.yml b/.github/ISSUE_TEMPLATE/documentation.yml index 3baed698..c7534c9c 100644 --- a/.github/ISSUE_TEMPLATE/documentation.yml +++ b/.github/ISSUE_TEMPLATE/documentation.yml @@ -10,8 +10,6 @@ body: description: Which language implementation does the documentation cover? options: - .NET (C#) - - Rust - - Both / shared - Not applicable validations: required: true diff --git a/.github/ISSUE_TEMPLATE/feature_request.yml b/.github/ISSUE_TEMPLATE/feature_request.yml index df57fc55..b8df2033 100644 --- a/.github/ISSUE_TEMPLATE/feature_request.yml +++ b/.github/ISSUE_TEMPLATE/feature_request.yml @@ -10,8 +10,6 @@ body: description: Which language implementation should this feature target? options: - .NET (C#) - - Rust - - Both / shared validations: required: true diff --git a/.github/ISSUE_TEMPLATE/question.yml b/.github/ISSUE_TEMPLATE/question.yml index 5b2527f9..bc0e1e94 100644 --- a/.github/ISSUE_TEMPLATE/question.yml +++ b/.github/ISSUE_TEMPLATE/question.yml @@ -15,8 +15,6 @@ body: description: Which language implementation is your question about? options: - .NET (C#) - - Rust - - Both / shared validations: required: true diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md index 44394a46..ebd7a909 100644 --- a/.github/PULL_REQUEST_TEMPLATE.md +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -12,7 +12,7 @@ scores or before-and-after images for rendering changes. - [ ] The change is focused and does not include unrelated formatting or generated files. - [ ] New or changed behavior has automated test coverage where practical. -- [ ] Relevant .NET and/or Rust checks pass. +- [ ] Relevant .NET checks pass. - [ ] Public API and compatibility effects are documented. - [ ] Security implications and untrusted-input behavior were considered. - [ ] I have the right to submit every added source file, fixture, font, image, and other asset under its stated license. diff --git a/.github/workflows/crates-publish.yml b/.github/workflows/crates-publish.yml deleted file mode 100644 index 43c7cd08..00000000 --- a/.github/workflows/crates-publish.yml +++ /dev/null @@ -1,81 +0,0 @@ -name: Crates.io Publish - -on: - release: - types: [published] - workflow_dispatch: - inputs: - version: - description: Cargo package version to publish (for example, 0.1.0) - required: true - type: string - -permissions: - contents: read - -jobs: - publish: - if: github.event_name == 'workflow_dispatch' || startsWith(github.ref_name, 'rust-v') - runs-on: ubuntu-latest - defaults: - run: - working-directory: minipdf-rs - env: - CARGO_REGISTRY_TOKEN: ${{ secrets.CARGO_REGISTRY_TOKEN }} - - steps: - - name: Checkout - uses: actions/checkout@v4 - - - name: Validate crates.io token - shell: bash - run: | - if [ -z "${CARGO_REGISTRY_TOKEN:-}" ]; then - echo "::error::CARGO_REGISTRY_TOKEN is not configured for this repository. Add it under Settings > Secrets and variables > Actions." - exit 1 - fi - - - name: Install Rust - uses: dtolnay/rust-toolchain@stable - with: - components: clippy, rustfmt - - - name: Validate release version - shell: bash - run: | - if [ "${{ github.event_name }}" = "workflow_dispatch" ]; then - TAG_VERSION="${{ inputs.version }}" - else - TAG_VERSION="${GITHUB_REF_NAME#rust-v}" - fi - CARGO_VERSION="$(sed -n 's/^version = "\([^"]*\)"/\1/p' Cargo.toml | head -n 1)" - if [ -z "$TAG_VERSION" ] || [ "$TAG_VERSION" != "$CARGO_VERSION" ]; then - echo "::error::Tag version '$TAG_VERSION' does not match Cargo version '$CARGO_VERSION'." - exit 1 - fi - - - name: Test - run: cargo test --workspace --locked - - - name: Lint - run: cargo clippy --workspace --all-targets --locked -- -D warnings - - - name: Verify packages - run: cargo publish -p minipdf --locked --dry-run - - - name: Publish library - run: cargo publish -p minipdf --locked - - - name: Publish CLI - shell: bash - run: | - for attempt in 1 2 3 4 5; do - if cargo publish -p minipdf-cli --locked --dry-run; then - cargo publish -p minipdf-cli --locked - exit $? - fi - if [ "$attempt" -eq 5 ]; then - exit 1 - fi - sleep 20 - done \ No newline at end of file diff --git a/.github/workflows/go-ci.yml b/.github/workflows/go-ci.yml deleted file mode 100644 index 9478cfe0..00000000 --- a/.github/workflows/go-ci.yml +++ /dev/null @@ -1,64 +0,0 @@ -name: Go CI - -on: - push: - branches: [main, master] - paths: - - 'minipdf-go/**' - - '.github/workflows/go-ci.yml' - - '.github/workflows/go-release.yml' - pull_request: - branches: [main, master] - paths: - - 'minipdf-go/**' - - '.github/workflows/go-ci.yml' - - '.github/workflows/go-release.yml' - -permissions: - contents: read - -jobs: - quality: - runs-on: ubuntu-latest - defaults: - run: - working-directory: minipdf-go - - steps: - - name: Checkout - uses: actions/checkout@v6 - - - name: Setup Go - uses: actions/setup-go@v6 - with: - go-version: '1.22.x' - cache: false - - - name: Check formatting - shell: bash - run: test -z "$(gofmt -l .)" - - - name: Vet - run: go vet ./... - - - name: Test - run: go test ./... - - windows-test: - runs-on: windows-latest - defaults: - run: - working-directory: minipdf-go - - steps: - - name: Checkout - uses: actions/checkout@v6 - - - name: Setup Go - uses: actions/setup-go@v6 - with: - go-version: '1.22.x' - cache: false - - - name: Test - run: go test ./... \ No newline at end of file diff --git a/.github/workflows/go-release.yml b/.github/workflows/go-release.yml deleted file mode 100644 index eb5ef871..00000000 --- a/.github/workflows/go-release.yml +++ /dev/null @@ -1,124 +0,0 @@ -name: Go Release - -on: - push: - tags: - - 'minipdf-go/v*' - workflow_dispatch: - inputs: - tag: - description: Existing Go module tag to release (for example, minipdf-go/v0.1.0) - required: true - type: string - -permissions: - contents: write - -concurrency: - group: go-release-${{ github.ref_name }}-${{ inputs.tag }} - cancel-in-progress: false - -jobs: - release: - runs-on: ubuntu-latest - defaults: - run: - working-directory: minipdf-go - env: - RELEASE_TAG: ${{ github.event_name == 'workflow_dispatch' && inputs.tag || github.ref_name }} - - steps: - - name: Checkout release tag - uses: actions/checkout@v6 - with: - ref: ${{ github.event_name == 'workflow_dispatch' && inputs.tag || github.ref }} - - - name: Setup Go - uses: actions/setup-go@v6 - with: - go-version: '1.22.x' - cache: false - - - name: Validate release tag - id: version - shell: bash - run: | - if [[ ! "$RELEASE_TAG" =~ ^minipdf-go/v[0-9]+\.[0-9]+\.[0-9]+([.-][0-9A-Za-z.-]+)?$ ]]; then - echo "::error::Tag '$RELEASE_TAG' must match minipdf-go/v." - exit 1 - fi - MODULE_PATH="$(go list -m -f '{{.Path}}')" - if [ "$MODULE_PATH" != "github.com/mini-software/MiniPdf/minipdf-go" ]; then - echo "::error::Unexpected Go module path '$MODULE_PATH'." - exit 1 - fi - VERSION="${RELEASE_TAG#minipdf-go/}" - echo "version=$VERSION" >> "$GITHUB_OUTPUT" - - - name: Check formatting - shell: bash - run: test -z "$(gofmt -l .)" - - - name: Vet - run: go vet ./... - - - name: Test - run: go test ./... - - - name: Build release archives - shell: bash - env: - VERSION: ${{ steps.version.outputs.version }} - run: | - mkdir -p dist - targets=( - windows/amd64 - windows/arm64 - linux/amd64 - linux/arm64 - darwin/amd64 - darwin/arm64 - ) - for target in "${targets[@]}"; do - IFS=/ read -r goos goarch <<< "$target" - archive="minipdf_${VERSION}_${goos}_${goarch}" - binary="minipdf" - if [ "$goos" = "windows" ]; then - binary="minipdf.exe" - fi - mkdir -p "dist/$archive" - CGO_ENABLED=0 GOOS="$goos" GOARCH="$goarch" go build \ - -trimpath \ - -ldflags="-s -w -X main.version=$VERSION" \ - -o "dist/$archive/$binary" \ - ./cmd/minipdf - if [ "$goos" = "windows" ]; then - (cd "dist/$archive" && zip -q "../$archive.zip" "$binary") - else - tar -C "dist/$archive" -czf "dist/$archive.tar.gz" "$binary" - fi - rm -rf "dist/$archive" - done - (cd dist && sha256sum minipdf_* > checksums.txt) - - - name: Verify embedded version - shell: bash - env: - VERSION: ${{ steps.version.outputs.version }} - run: | - actual="$(go run -ldflags="-X main.version=$VERSION" ./cmd/minipdf --version)" - if [ "$actual" != "minipdf $VERSION" ]; then - echo "::error::CLI reported '$actual'." - exit 1 - fi - - - name: Create GitHub release - uses: softprops/action-gh-release@v2 - with: - tag_name: ${{ env.RELEASE_TAG }} - name: MiniPdf Go ${{ steps.version.outputs.version }} - generate_release_notes: true - files: | - minipdf-go/dist/*.zip - minipdf-go/dist/*.tar.gz - minipdf-go/dist/checksums.txt \ No newline at end of file diff --git a/.github/workflows/java-ci.yml b/.github/workflows/java-ci.yml deleted file mode 100644 index 9f7a8eaf..00000000 --- a/.github/workflows/java-ci.yml +++ /dev/null @@ -1,102 +0,0 @@ -name: Java CI - -on: - push: - branches: [main, master] - paths: - - 'minipdf-java/**' - - '.github/workflows/java-ci.yml' - pull_request: - branches: [main, master] - paths: - - 'minipdf-java/**' - - '.github/workflows/java-ci.yml' - -permissions: - contents: read - -jobs: - test: - strategy: - fail-fast: false - matrix: - java-version: - - '8' - - '9' - - '10' - - '11' - - '12' - - '13' - - '14' - - '15' - - '16' - - '17' - - '18' - - '19' - - '20' - - '21' - - '22' - - '23' - - '24' - - '25' - runner: [ubuntu-latest] - exclude: - - java-version: '9' - runner: ubuntu-latest - - java-version: '10' - runner: ubuntu-latest - include: - - java-version: '9' - runner: ubuntu-22.04 - - java-version: '10' - runner: ubuntu-22.04 - runs-on: ${{ matrix.runner }} - defaults: - run: - working-directory: minipdf-java - - steps: - - name: Checkout - uses: actions/checkout@v6 - with: - persist-credentials: false - - - name: Setup Java ${{ matrix.java-version }} - uses: actions/setup-java@v6 - with: - distribution: zulu - java-version: ${{ matrix.java-version }} - cache: maven - cache-dependency-path: minipdf-java/pom.xml - - - name: Setup Maven runtime for JDK 10 - if: matrix.java-version == '10' - uses: actions/setup-java@v6 - with: - distribution: temurin - java-version: '17' - - - name: Install CJK fonts - run: sudo apt-get update && sudo apt-get install --yes fonts-noto-cjk fonts-unifont fonts-wqy-microhei - - - name: Test - if: matrix.java-version != '10' - run: ./mvnw -B -ntp verify - - - name: Test on JDK 10 - if: matrix.java-version == '10' - # HotSpot 10 intermittently exits in compiled mode on hosted runner - # CPUs. Keep Maven on JDK 17 and run only compatibility tests in the - # JDK 10 interpreter. - run: ./mvnw -B -ntp -Djvm="$JAVA_HOME_10_X64/bin/java" -DargLine="-Xint -XX:-UseContainerSupport" verify - - - name: Upload JDK 10 crash diagnostics - if: failure() && matrix.java-version == '10' - uses: actions/upload-artifact@v4 - with: - name: java-10-crash-diagnostics - path: | - minipdf-java/**/target/surefire-reports/** - minipdf-java/**/hs_err_pid*.log - if-no-files-found: warn - retention-days: 3 diff --git a/.github/workflows/java-publish.yml b/.github/workflows/java-publish.yml deleted file mode 100644 index 18ecffe1..00000000 --- a/.github/workflows/java-publish.yml +++ /dev/null @@ -1,122 +0,0 @@ -name: Maven Central Publish - -on: - release: - types: [published] - workflow_dispatch: - inputs: - version: - description: Maven package version to publish (for example, 0.2.0) - required: true - type: string - -permissions: - contents: read - -concurrency: - group: maven-central-publish - cancel-in-progress: false - -jobs: - publish: - if: github.event_name == 'workflow_dispatch' || startsWith(github.ref_name, 'java-v') - runs-on: ubuntu-latest - environment: - name: maven-central - url: https://central.sonatype.com/artifact/io.github.mini-software/minipdf - defaults: - run: - working-directory: minipdf-java - env: - MAVEN_USERNAME: ${{ secrets.MAVEN_CENTRAL_USERNAME }} - MAVEN_PASSWORD: ${{ secrets.MAVEN_CENTRAL_TOKEN }} - MAVEN_GPG_PASSPHRASE: ${{ secrets.GPG_PASSPHRASE }} - GPG_PRIVATE_KEY: ${{ secrets.GPG_PRIVATE_KEY }} - RELEASE_VERSION: ${{ github.event_name == 'workflow_dispatch' && inputs.version || github.ref_name }} - - steps: - - name: Checkout - uses: actions/checkout@v6 - with: - persist-credentials: false - - - name: Validate release credentials - shell: bash - run: | - missing=0 - for name in MAVEN_USERNAME MAVEN_PASSWORD MAVEN_GPG_PASSPHRASE GPG_PRIVATE_KEY; do - if [ -z "${!name:-}" ]; then - echo "::error::$name is not configured." - missing=1 - fi - done - exit "$missing" - - - name: Setup Java - uses: actions/setup-java@v6 - with: - distribution: temurin - java-version: '17' - cache: maven - cache-dependency-path: minipdf-java/**/pom.xml - server-id: central - server-username-env-var: MAVEN_USERNAME - server-password-env-var: MAVEN_PASSWORD - gpg-private-key: ${{ secrets.GPG_PRIVATE_KEY }} - gpg-passphrase-env-var: MAVEN_GPG_PASSPHRASE - - - name: Validate release version - id: version - shell: bash - run: | - VERSION="${RELEASE_VERSION#java-v}" - if [[ ! "$VERSION" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]]; then - echo "::error::Version '$VERSION' must use stable semantic version format." - exit 1 - fi - POM_VERSION="$(./mvnw -q -DforceStdout help:evaluate -Dexpression=project.version)" - if [ "$VERSION" != "$POM_VERSION" ]; then - echo "::error::Release version '$VERSION' does not match POM version '$POM_VERSION'." - exit 1 - fi - echo "version=$VERSION" >> "$GITHUB_OUTPUT" - - - name: Install CJK fonts - run: sudo apt-get update && sudo apt-get install --yes fonts-noto-cjk fonts-wqy-microhei - - - name: Test release candidate - run: ./mvnw -B -ntp clean verify - - - name: Verify Maven Central artifacts - shell: bash - run: | - ./mvnw -B -ntp -P release -DskipTests -Dgpg.skip=true -pl minipdf,minipdf-cli -am package - VERSION="${{ steps.version.outputs.version }}" - for artifact in \ - "minipdf/target/minipdf-$VERSION.jar" \ - "minipdf/target/minipdf-$VERSION-sources.jar" \ - "minipdf/target/minipdf-$VERSION-javadoc.jar" \ - "minipdf-cli/target/minipdf-cli-$VERSION.jar" \ - "minipdf-cli/target/minipdf-cli-$VERSION-sources.jar" \ - "minipdf-cli/target/minipdf-cli-$VERSION-javadoc.jar"; do - if [ ! -s "$artifact" ]; then - echo "::error::Missing release artifact: $artifact" - exit 1 - fi - done - CLI_VERSION="$(java -jar "minipdf-cli/target/minipdf-cli-$VERSION.jar" --version)" - if [ "$CLI_VERSION" != "minipdf-java $VERSION" ]; then - echo "::error::CLI reported '$CLI_VERSION'." - exit 1 - fi - - - name: Publish to Maven Central - run: ./mvnw -B -ntp -P release -DskipTests -pl minipdf,minipdf-cli -am deploy - - - name: Summarize publication - shell: bash - run: | - echo "### MiniPdf Java ${{ steps.version.outputs.version }} published" >> "$GITHUB_STEP_SUMMARY" - echo "Maven Central coordinates:" >> "$GITHUB_STEP_SUMMARY" - echo '- `io.github.mini-software:minipdf:${{ steps.version.outputs.version }}`' >> "$GITHUB_STEP_SUMMARY" - echo '- `io.github.mini-software:minipdf-cli:${{ steps.version.outputs.version }}`' >> "$GITHUB_STEP_SUMMARY" \ No newline at end of file diff --git a/.github/workflows/node-ci.yml b/.github/workflows/node-ci.yml deleted file mode 100644 index 7575701f..00000000 --- a/.github/workflows/node-ci.yml +++ /dev/null @@ -1,96 +0,0 @@ -name: Node.js CI - -on: - push: - branches: [main, master] - paths: - - 'minipdf-node/**' - - 'minipdf-rs/**' - - '.github/workflows/node-ci.yml' - pull_request: - branches: [main, master] - paths: - - 'minipdf-node/**' - - 'minipdf-rs/**' - - '.github/workflows/node-ci.yml' - -permissions: - contents: read - -jobs: - lint: - runs-on: ubuntu-latest - defaults: - run: - working-directory: minipdf-node - - steps: - - name: Checkout - uses: actions/checkout@v6 - with: - persist-credentials: false - - - name: Setup Node.js - uses: actions/setup-node@v6 - with: - node-version: '24' - cache: npm - cache-dependency-path: minipdf-node/package-lock.json - - - name: Install Rust - uses: dtolnay/rust-toolchain@stable - with: - components: clippy, rustfmt - - - name: Install dependencies - run: npm ci --ignore-scripts - - - name: Format - run: cargo fmt --check - - - name: Lint - run: cargo clippy --all-targets --locked -- -D warnings - - test: - strategy: - fail-fast: false - matrix: - include: - - os: ubuntu-latest - target: x86_64-unknown-linux-gnu - - os: windows-latest - target: x86_64-pc-windows-msvc - - os: macos-15-intel - target: x86_64-apple-darwin - runs-on: ${{ matrix.os }} - defaults: - run: - working-directory: minipdf-node - - steps: - - name: Checkout - uses: actions/checkout@v6 - with: - persist-credentials: false - - - name: Setup Node.js - uses: actions/setup-node@v6 - with: - node-version: '18' - cache: npm - cache-dependency-path: minipdf-node/package-lock.json - - - name: Install Rust - uses: dtolnay/rust-toolchain@stable - with: - targets: ${{ matrix.target }} - - - name: Install dependencies - run: npm ci --ignore-scripts - - - name: Build - shell: bash - run: npm run build -- --target ${{ matrix.target }} - - - name: Test - run: npm test diff --git a/.github/workflows/npm-publish.yml b/.github/workflows/npm-publish.yml deleted file mode 100644 index 7268fcb2..00000000 --- a/.github/workflows/npm-publish.yml +++ /dev/null @@ -1,230 +0,0 @@ -name: NPM Publish - -on: - release: - types: [published] - workflow_dispatch: - inputs: - version: - description: npm package version to publish (for example, 0.1.0) - required: true - type: string - mode: - description: Use initial only for the first publication; later releases are staged - required: true - default: dry-run - type: choice - options: - - dry-run - - initial - - stage - -permissions: - contents: read - -jobs: - build: - if: github.event_name == 'workflow_dispatch' || startsWith(github.ref_name, 'node-v') - strategy: - fail-fast: false - matrix: - include: - - runner: windows-latest - target: x86_64-pc-windows-msvc - zig: false - - runner: windows-11-arm - target: aarch64-pc-windows-msvc - zig: false - - runner: macos-15-intel - target: x86_64-apple-darwin - zig: false - - runner: macos-latest - target: aarch64-apple-darwin - zig: false - - runner: ubuntu-latest - target: x86_64-unknown-linux-gnu - zig: false - - runner: ubuntu-24.04-arm - target: aarch64-unknown-linux-gnu - zig: false - - runner: ubuntu-latest - target: x86_64-unknown-linux-musl - zig: true - - runner: ubuntu-24.04-arm - target: aarch64-unknown-linux-musl - zig: true - name: Build ${{ matrix.target }} - runs-on: ${{ matrix.runner }} - defaults: - run: - working-directory: minipdf-node - - steps: - - name: Checkout - uses: actions/checkout@v6 - - - name: Setup Node.js - uses: actions/setup-node@v6 - with: - node-version: '24' - cache: npm - cache-dependency-path: minipdf-node/package-lock.json - - - name: Install Rust - uses: dtolnay/rust-toolchain@stable - with: - toolchain: ${{ matrix.target == 'aarch64-unknown-linux-musl' && '1.97.1' || 'stable' }} - targets: ${{ matrix.target }} - - - name: Setup Zig - if: matrix.zig - uses: mlugg/setup-zig@v2 - - - name: Install cargo-zigbuild - if: matrix.zig - uses: taiki-e/install-action@v2 - with: - tool: cargo-zigbuild - - - name: Install dependencies - run: npm ci --ignore-scripts - - - name: Build - shell: bash - env: - BUILD_WITH_ZIG: ${{ matrix.zig }} - run: | - if [ "$BUILD_WITH_ZIG" = "true" ]; then - npm run build -- --target ${{ matrix.target }} --zig - else - npm run build -- --target ${{ matrix.target }} - fi - - - name: Upload native addon - uses: actions/upload-artifact@v4 - with: - name: binding-${{ matrix.target }} - path: minipdf-node/minipdf-node.*.node - if-no-files-found: error - - publish: - needs: build - runs-on: ubuntu-latest - permissions: - contents: read - id-token: write - defaults: - run: - working-directory: minipdf-node - env: - NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }} - PUBLISH_MODE: ${{ github.event_name == 'release' && 'stage' || inputs.mode }} - RELEASE_VERSION: ${{ github.event_name == 'release' && github.ref_name || inputs.version }} - - steps: - - name: Checkout - uses: actions/checkout@v6 - - - name: Setup Node.js - uses: actions/setup-node@v6 - with: - node-version: '24' - registry-url: https://registry.npmjs.org - - - name: Install current npm CLI - run: npm install --global npm@11.15.0 - - - name: Install dependencies - run: npm ci --ignore-scripts - - - name: Validate release version - shell: bash - run: | - TAG_VERSION="${RELEASE_VERSION#node-v}" - PACKAGE_VERSION="$(node -p "require('./package.json').version")" - if [ -z "$TAG_VERSION" ] || [ "$TAG_VERSION" != "$PACKAGE_VERSION" ]; then - echo "::error::Release version '$TAG_VERSION' does not match package version '$PACKAGE_VERSION'." - exit 1 - fi - - - name: Create platform packages - run: npm run create-npm-dir - - - name: Download native addons - uses: actions/download-artifact@v4 - with: - pattern: binding-* - path: minipdf-node/artifacts - merge-multiple: true - - - name: Assemble platform packages - shell: bash - run: | - npm run artifacts - npm run prepare-release - - - name: Verify package contents - shell: bash - run: | - expected="$(node -p "Object.keys(require('./package.json').optionalDependencies).length")" - actual="$(find npm -name '*.node' -type f | wc -l | tr -d ' ')" - if [ "$actual" != "$expected" ]; then - echo "::error::Expected $expected native addons but assembled $actual." - exit 1 - fi - for package_dir in npm/*; do - npm pack "./$package_dir" --dry-run - done - npm pack . --dry-run --ignore-scripts - - - name: Require token for initial publication - if: env.PUBLISH_MODE == 'initial' - shell: bash - run: | - if [ -z "${NODE_AUTH_TOKEN:-}" ]; then - echo "::error::Add a short-lived granular npm token as the NPM_TOKEN repository secret." - exit 1 - fi - - - name: Publish initial packages - if: env.PUBLISH_MODE == 'initial' - shell: bash - run: | - publish_if_missing() { - package_dir="$1" - package_name="$(node -p "require('./$package_dir/package.json').name")" - package_version="$(node -p "require('./$package_dir/package.json').version")" - if npm view "$package_name@$package_version" version >/dev/null 2>&1; then - echo "$package_name@$package_version already exists; skipping." - else - (cd "$package_dir" && npm publish --access public --provenance) - fi - } - for package_dir in npm/*; do - publish_if_missing "$package_dir" - done - if npm view "minipdf@$(node -p "require('./package.json').version")" version >/dev/null 2>&1; then - echo "minipdf@$(node -p "require('./package.json').version") already exists; skipping." - else - npm publish . --access public --provenance --ignore-scripts - fi - - - name: Stage packages for approval - if: env.PUBLISH_MODE == 'stage' - shell: bash - run: | - failures=0 - for package_dir in npm/*; do - if ! (cd "$package_dir" && npm stage publish); then - echo "::warning::Could not stage $package_dir; continuing with remaining packages." - failures=$((failures + 1)) - fi - done - if ! npm stage publish; then - echo "::warning::Could not stage the main package." - failures=$((failures + 1)) - fi - if [ "$failures" -ne 0 ]; then - echo "::error::$failures package publication attempts failed." - exit 1 - fi \ No newline at end of file diff --git a/.github/workflows/pypi-publish.yml b/.github/workflows/pypi-publish.yml deleted file mode 100644 index 4282852d..00000000 --- a/.github/workflows/pypi-publish.yml +++ /dev/null @@ -1,140 +0,0 @@ -name: PyPI Publish - -on: - release: - types: [published] - workflow_dispatch: - inputs: - version: - description: Python package version to publish (for example, 0.7.0) - required: true - type: string - -permissions: - contents: read - -jobs: - build: - if: github.event_name == 'workflow_dispatch' || startsWith(github.ref_name, 'python-v') - strategy: - fail-fast: false - matrix: - include: - - os: ubuntu-latest - - os: windows-latest - - os: macos-14 - - os: macos-15-intel - runs-on: ${{ matrix.os }} - defaults: - run: - working-directory: minipdf-python - steps: - - name: Checkout - uses: actions/checkout@v4 - - - name: Setup Python - uses: actions/setup-python@v5 - with: - python-version: '3.12' - - - name: Setup Rust - uses: dtolnay/rust-toolchain@stable - - - name: Install build tools - run: python -m pip install maturin - - - name: Build wheels - run: python -m maturin build --release --out dist - - - name: Upload wheels - uses: actions/upload-artifact@v4 - with: - name: wheels-${{ matrix.os }} - path: minipdf-python/dist/ - - sdist: - if: github.event_name == 'workflow_dispatch' || startsWith(github.ref_name, 'python-v') - runs-on: ubuntu-latest - defaults: - run: - working-directory: minipdf-python - steps: - - name: Checkout - uses: actions/checkout@v4 - - - name: Setup Python - uses: actions/setup-python@v5 - with: - python-version: '3.12' - - - name: Install build tools - run: python -m pip install maturin - - - name: Build sdist - run: python -m maturin sdist --out dist - - - name: Upload sdist - uses: actions/upload-artifact@v4 - with: - name: sdist - path: minipdf-python/dist/ - - publish: - if: github.event_name == 'workflow_dispatch' || startsWith(github.ref_name, 'python-v') - needs: [build, sdist] - runs-on: ubuntu-latest - environment: - name: pypi - url: https://pypi.org/project/minipdf/ - permissions: - contents: read - id-token: write - defaults: - run: - working-directory: minipdf-python - steps: - - name: Checkout - uses: actions/checkout@v4 - - - name: Download wheels - uses: actions/download-artifact@v4 - with: - pattern: wheels-* - path: minipdf-python/dist - merge-multiple: true - - - name: Download sdist - uses: actions/download-artifact@v4 - with: - name: sdist - path: minipdf-python/dist - - - name: Setup Python - uses: actions/setup-python@v5 - with: - python-version: '3.12' - - - name: Install build tools - run: python -m pip install twine - - - name: Validate release version - shell: bash - run: | - if [ "${{ github.event_name }}" = "workflow_dispatch" ]; then - TAG_VERSION="${{ inputs.version }}" - else - TAG_VERSION="${GITHUB_REF_NAME#python-v}" - fi - PACKAGE_VERSION="$(python -c 'import tomllib; print(tomllib.load(open("pyproject.toml", "rb"))["project"]["version"])')" - if [ -z "$TAG_VERSION" ] || [ "$TAG_VERSION" != "$PACKAGE_VERSION" ]; then - echo "::error::Release version '$TAG_VERSION' does not match package version '$PACKAGE_VERSION'." - exit 1 - fi - - - name: Check distributions - run: python -m twine check dist/* - - - name: Publish to PyPI - uses: pypa/gh-action-pypi-publish@release/v1 - with: - packages-dir: minipdf-python/dist/ \ No newline at end of file diff --git a/.github/workflows/python-ci.yml b/.github/workflows/python-ci.yml deleted file mode 100644 index 6358a125..00000000 --- a/.github/workflows/python-ci.yml +++ /dev/null @@ -1,59 +0,0 @@ -name: Python CI - -on: - push: - branches: [main, master] - paths: - - 'minipdf-python/**' - - '.github/workflows/python-ci.yml' - pull_request: - branches: [main, master] - paths: - - 'minipdf-python/**' - - '.github/workflows/python-ci.yml' - -permissions: - contents: read - -jobs: - test: - strategy: - matrix: - os: [ubuntu-latest, windows-latest] - python-version: ['3.10', '3.12', '3.13'] - runs-on: ${{ matrix.os }} - - steps: - - name: Checkout - uses: actions/checkout@v4 - - - name: Setup Python - uses: actions/setup-python@v5 - with: - python-version: ${{ matrix.python-version }} - cache: pip - cache-dependency-path: minipdf-python/pyproject.toml - - - name: Setup Rust - uses: dtolnay/rust-toolchain@stable - - - name: Install - run: python -m pip install -e "./minipdf-python[dev]" - - - name: Test - run: python -m pytest minipdf-python/tests -q - - - name: Lint - run: python -m ruff check minipdf-python - - - name: Format - run: python -m ruff format --check minipdf-python - - - name: Type check - run: python -m mypy minipdf-python/src minipdf-python/tests - - - name: Build - run: python -m build minipdf-python - - - name: Check distributions - run: python -m twine check minipdf-python/dist/* diff --git a/.github/workflows/rust-ecosystem-release.yml b/.github/workflows/rust-ecosystem-release.yml deleted file mode 100644 index 0d224073..00000000 --- a/.github/workflows/rust-ecosystem-release.yml +++ /dev/null @@ -1,69 +0,0 @@ -name: Rust Ecosystem Release - -on: - release: - types: [published] - workflow_dispatch: - inputs: - version: - description: Version shared by Rust, Node.js, and Python (for example, 0.7.0) - required: true - type: string - -permissions: - contents: read - actions: write - -jobs: - release: - if: github.event_name == 'workflow_dispatch' || startsWith(github.ref_name, 'rust-v') - runs-on: ubuntu-latest - env: - GH_TOKEN: ${{ github.token }} - steps: - - name: Checkout - uses: actions/checkout@v4 - - - name: Determine version - id: version - shell: bash - run: | - if [ "${{ github.event_name }}" = "workflow_dispatch" ]; then - VERSION="${{ inputs.version }}" - else - VERSION="${GITHUB_REF_NAME#rust-v}" - fi - echo "version=$VERSION" >> "$GITHUB_OUTPUT" - - - name: Validate aligned versions - shell: bash - run: | - VERSION="${{ steps.version.outputs.version }}" - CARGO_VERSION="$(sed -n 's/^version = "\([^"]*\)"/\1/p' minipdf-rs/Cargo.toml | head -n 1)" - NODE_VERSION="$(node -p "require('./minipdf-node/package.json').version")" - PYTHON_VERSION="$(sed -n 's/^version = "\([^"]*\)"/\1/p' minipdf-python/pyproject.toml | head -n 1)" - if [ "$CARGO_VERSION" != "$VERSION" ]; then - echo "::error::Rust workspace version '$CARGO_VERSION' does not match release version '$VERSION'. Update minipdf-rs/Cargo.toml before releasing." - exit 1 - fi - if [ "$NODE_VERSION" != "$VERSION" ]; then - echo "::error::npm package version '$NODE_VERSION' does not match release version '$VERSION'. Update minipdf-node/package.json and package-lock.json before releasing." - exit 1 - fi - if [ "$PYTHON_VERSION" != "$VERSION" ]; then - echo "::error::Python package version '$PYTHON_VERSION' does not match release version '$VERSION'. Update minipdf-python/pyproject.toml and src/minipdf/__init__.py before releasing." - exit 1 - fi - - - name: Dispatch NPM publish - shell: bash - run: | - gh workflow run npm-publish.yml --ref "$GITHUB_SHA" \ - -f version="${{ steps.version.outputs.version }}" \ - -f mode=stage - - - name: Dispatch PyPI publish - shell: bash - run: | - gh workflow run pypi-publish.yml --ref "$GITHUB_SHA" \ - -f version="${{ steps.version.outputs.version }}" diff --git a/.gitignore b/.gitignore index f84220f5..e21399fd 100644 --- a/.gitignore +++ b/.gitignore @@ -12,9 +12,6 @@ **/node_modules/ **/*.node **/*.tgz -minipdf-node/npm/ -minipdf-python/src/minipdf/_native.pyd -minipdf-python/src/minipdf/_native.abi3.so ## IDE .vs/ diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index be30813f..e5b8f21c 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -22,6 +22,9 @@ fixtures, images, fonts, or generated material and include their source and license. MiniPdf does not currently require a separate contributor license agreement. +Non-.NET implementations are maintained in their own [PdfLibrarys repositories](https://github.com/PdfLibrarys). +Use their development and release workflows rather than this repository's commands. + ## Development Setup Clone your fork and create a focused branch. Keep unrelated formatting, @@ -43,31 +46,6 @@ and a separate DOCX suite on Windows, where it verifies the required fonts before testing. Install these fonts through a licensed system/Office installation to run the font-dependent checks locally; do not add font binaries to the repository. -### Rust - -Install the stable Rust toolchain, then run: - -```powershell -Set-Location minipdf-rs -cargo fmt --check -cargo clippy --workspace --all-targets -- -D warnings -cargo test --workspace -``` - -### Python - -Install Python 3.10 or later, then run: - -```powershell -python -m pip install -e ".\minipdf-python[dev]" -python -m pytest minipdf-python/tests -python -m ruff check minipdf-python -python -m ruff format --check minipdf-python -python -m mypy minipdf-python/src minipdf-python/tests -python -m build minipdf-python -python -m twine check minipdf-python/dist/* -``` - ### Documentation Keep commands, APIs, benchmark results, and report links consistent. Changes to @@ -79,18 +57,23 @@ README files under `documents/`. 1. Reproduce the behavior with the smallest useful test or fixture. 2. Make one focused change at the owning implementation boundary. 3. Add or update automated tests for behavior changes. -4. Run the relevant .NET or Rust checks above. +4. Run the relevant .NET checks above. 5. For rendering changes, run the narrowest applicable visual benchmark. 6. Explain compatibility, security, provenance, and documentation effects in the pull request. +The shared visual evaluator is test tooling, not the Java implementation. +Install Java 11+ and Maven, build it with +`mvn -f tests/MiniPdf.Benchmark/pdfbox/pom.xml package`, and provide the Python +image dependencies and Microsoft 365/LibreOffice reference PDFs before running +visual comparisons. + Useful focused benchmark commands include: ```powershell scripts/Run-Benchmark.ps1 -Filter "border" scripts/Run-Benchmark_docx.ps1 -Filter "heading" scripts/Run-Benchmark_issues.ps1 -Filter "sa8000" -scripts/Run-Rust-Benchmark.ps1 -Filter "classic01" -MinimumScore 0.99 ``` Generated PDFs, PNGs, heatmaps, and reports should only be committed when they diff --git a/FEATURE_PARITY.md b/FEATURE_PARITY.md index 55a8f8e5..3479620b 100644 --- a/FEATURE_PARITY.md +++ b/FEATURE_PARITY.md @@ -1,6 +1,9 @@ # Cross-Language Feature Parity -Last verified: 2026-09-14 +Historical snapshot last verified: 2026-09-14 + +The non-.NET implementations now live in [PdfLibrarys](https://github.com/PdfLibrarys). +This snapshot is retained for reference; each repository owns its current capabilities and release process. This document tracks implementation gaps between MiniPdf for .NET, Rust, Java, Go, Python, and Node.js. It is an engineering backlog, not a claim of @@ -47,18 +50,11 @@ Notes: belong in `minipdf-rs`; Node-specific work should focus on API exposure, asynchronous execution, packaging, and binding tests. - Python renders through the Rust engine via the - [`minipdf._native`](minipdf-python/native/src/lib.rs) PyO3 extension built by + [`minipdf._native`](https://github.com/PdfLibrarys/minipdf-python/blob/main/native/src/lib.rs) PyO3 extension built by the package backend, falling back to the pure Python renderers only when the extension is not importable. The capability matrix below describes the pure Python fallback. -- Node.js and Python versions follow the Rust core version. A `rust-vX.Y.Z` - release dispatches the NPM and PyPI publish workflows with the same version - through - [`rust-ecosystem-release.yml`](.github/workflows/rust-ecosystem-release.yml). - When bumping the Rust version, update `minipdf-node/package.json` (and - `package-lock.json`), `minipdf-python/pyproject.toml`, - `minipdf-python/src/minipdf/__init__.py`, and - `minipdf-python/native/Cargo.toml` in the same change. +- Node.js and Python pin their Rust engine by immutable Git revision. Releases are managed independently in their own repositories; the former cross-repository release dispatcher has been removed. - `P` does not mean the same depth in every language. The detailed matrices below identify the important differences. - The public .NET page-size and margin overrides currently apply to DOCX. The @@ -91,16 +87,16 @@ print scale, rows-per-page, and culture-aware value formatting in Evidence: - Rust currently exposes only `page_size` in - [`ConversionOptions`](minipdf-rs/crates/minipdf/src/lib.rs). + [`ConversionOptions`](https://github.com/PdfLibrarys/minipdf-rs/blob/main/crates/minipdf/src/lib.rs). - Java currently exposes only `pageSize` in - [`ConversionOptions`](minipdf-java/minipdf/src/main/java/io/github/minisoftware/minipdf/ConversionOptions.java). + [`ConversionOptions`](https://github.com/PdfLibrarys/minipdf-java/blob/main/minipdf/src/main/java/io/github/minisoftware/minipdf/ConversionOptions.java). - Go currently exposes page size, DOCX margins, PDF compression, XLSX row and column limits, and XLSX orientation in - [`ConversionOptions`](minipdf-go/minipdf.go). + [`ConversionOptions`](https://github.com/PdfLibrarys/minipdf-go/blob/main/minipdf.go). - Python currently exposes only `page_size` in - [`ConversionOptions`](minipdf-python/src/minipdf/options.py). + [`ConversionOptions`](https://github.com/PdfLibrarys/minipdf-python/blob/main/src/minipdf/options.py). - Node.js exposes synchronous Rust conversion bindings in - [`lib.rs`](minipdf-node/src/lib.rs); callers must use a worker thread to avoid + [`lib.rs`](https://github.com/PdfLibrarys/minipdf-node/blob/main/src/lib.rs); callers must use a worker thread to avoid blocking the Node.js event loop. Go also provides bounded `io.Reader` input, `io.Writer` output, and complete @@ -135,10 +131,10 @@ Primary implementation evidence: - .NET: [`DocxReader.cs`](src/MiniPdf/DocxReader.cs) and [`DocxToPdfConverter.cs`](src/MiniPdf/DocxToPdfConverter.cs) -- Rust: [`docx.rs`](minipdf-rs/crates/minipdf/src/docx.rs) -- Java: [`DocxConverter.java`](minipdf-java/minipdf/src/main/java/io/github/minisoftware/minipdf/internal/docx/DocxConverter.java) -- Go: [`docx.go`](minipdf-go/docx.go) -- Python: [`docx.py`](minipdf-python/src/minipdf/docx.py) +- Rust: [`docx.rs`](https://github.com/PdfLibrarys/minipdf-rs/blob/main/crates/minipdf/src/docx.rs) +- Java: [`DocxConverter.java`](https://github.com/PdfLibrarys/minipdf-java/blob/main/minipdf/src/main/java/io/github/minisoftware/minipdf/internal/docx/DocxConverter.java) +- Go: [`docx.go`](https://github.com/PdfLibrarys/minipdf-go/blob/main/docx.go) +- Python: [`docx.py`](https://github.com/PdfLibrarys/minipdf-python/blob/main/src/minipdf/docx.py) .NET paragraph shading uses the paragraph line box rather than the text baseline, extends through spacing between consecutive borderless shaded @@ -191,12 +187,12 @@ Primary implementation evidence: - .NET: [`ExcelReader.cs`](src/MiniPdf/ExcelReader.cs) and [`ExcelToPdfConverter.cs`](src/MiniPdf/ExcelToPdfConverter.cs) -- Rust: [`xlsx.rs`](minipdf-rs/crates/minipdf/src/xlsx.rs) -- Java: [`PoiXlsxRenderer.java`](minipdf-java/minipdf/src/main/java/io/github/minisoftware/minipdf/internal/xlsx/PoiXlsxRenderer.java) -- Go: [`xlsx.go`](minipdf-go/xlsx.go) - and [`xlsx_print.go`](minipdf-go/xlsx_print.go); explicit print areas select +- Rust: [`xlsx.rs`](https://github.com/PdfLibrarys/minipdf-rs/blob/main/crates/minipdf/src/xlsx.rs) +- Java: [`PoiXlsxRenderer.java`](https://github.com/PdfLibrarys/minipdf-java/blob/main/minipdf/src/main/java/io/github/minisoftware/minipdf/internal/xlsx/PoiXlsxRenderer.java) +- Go: [`xlsx.go`](https://github.com/PdfLibrarys/minipdf-go/blob/main/xlsx.go) + and [`xlsx_print.go`](https://github.com/PdfLibrarys/minipdf-go/blob/main/xlsx_print.go); explicit print areas select grid rendering with repeated titles, hidden cells, scaling, and page breaks. -- Python: [`xlsx.py`](minipdf-python/src/minipdf/xlsx.py) +- Python: [`xlsx.py`](https://github.com/PdfLibrarys/minipdf-python/blob/main/src/minipdf/xlsx.py) .NET resolves unnamed XLSX font families from the workbook's minor theme font, falling back to the first style font when no theme font is available. Explicit @@ -241,10 +237,10 @@ Primary implementation evidence: - .NET: [`PptxReader.cs`](src/MiniPdf/PptxReader.cs) and [`PptxToPdfConverter.cs`](src/MiniPdf/PptxToPdfConverter.cs) -- Rust: [`pptx.rs`](minipdf-rs/crates/minipdf/src/pptx.rs) -- Java: [`PptxConverter.java`](minipdf-java/minipdf/src/main/java/io/github/minisoftware/minipdf/internal/pptx/PptxConverter.java) -- Go: [`pptx.go`](minipdf-go/pptx.go) -- Python: [`pptx.py`](minipdf-python/src/minipdf/pptx.py) +- Rust: [`pptx.rs`](https://github.com/PdfLibrarys/minipdf-rs/blob/main/crates/minipdf/src/pptx.rs) +- Java: [`PptxConverter.java`](https://github.com/PdfLibrarys/minipdf-java/blob/main/minipdf/src/main/java/io/github/minisoftware/minipdf/internal/pptx/PptxConverter.java) +- Go: [`pptx.go`](https://github.com/PdfLibrarys/minipdf-go/blob/main/pptx.go) +- Python: [`pptx.py`](https://github.com/PdfLibrarys/minipdf-python/blob/main/src/minipdf/pptx.py) ## Font, Image, and PDF Writer Gaps @@ -269,14 +265,14 @@ internal in the next breaking release. Java, Go, and Python now enforce explicit package-loading limits. Java rejects excessive entry counts, oversized or highly compressed entries, unsafe paths, duplicate entries, and XML external entities in -[`OoxmlPackage.java`](minipdf-java/minipdf/src/main/java/io/github/minisoftware/minipdf/internal/OoxmlPackage.java) +[`OoxmlPackage.java`](https://github.com/PdfLibrarys/minipdf-java/blob/main/minipdf/src/main/java/io/github/minisoftware/minipdf/internal/OoxmlPackage.java) and -[`SecureXml.java`](minipdf-java/minipdf/src/main/java/io/github/minisoftware/minipdf/internal/SecureXml.java). +[`SecureXml.java`](https://github.com/PdfLibrarys/minipdf-java/blob/main/minipdf/src/main/java/io/github/minisoftware/minipdf/internal/SecureXml.java). Python applies package limits and path checks in -[`office.py`](minipdf-python/src/minipdf/office.py). +[`office.py`](https://github.com/PdfLibrarys/minipdf-python/blob/main/src/minipdf/office.py). Go applies entry count, entry and total size, expansion ratio, encryption, duplicate path, and unsafe path checks in -[`office.go`](minipdf-go/office.go), exposed through `ErrInvalidPackage`. +[`office.go`](https://github.com/PdfLibrarys/minipdf-go/blob/main/office.go), exposed through `ErrInvalidPackage`. .NET, Rust, and therefore Node.js still need the same bounded OOXML package contract. Cross-language conformance fixtures must cover: @@ -386,8 +382,8 @@ present. Require a focused unit test plus a reproducible visual benchmark case. - [ ] Fix [`README.md`](README.md), which lists Python input as DOCX only even though the Python dispatcher supports XLSX and PPTX. - [ ] Align the Python package and runtime version declarations in - [`pyproject.toml`](minipdf-python/pyproject.toml) and - [`__init__.py`](minipdf-python/src/minipdf/__init__.py). + [`pyproject.toml`](https://github.com/PdfLibrarys/minipdf-python/blob/main/pyproject.toml) and + [`__init__.py`](https://github.com/PdfLibrarys/minipdf-python/blob/main/src/minipdf/__init__.py). ### P1: Rendering Conformance diff --git a/MAINTAINERS.md b/MAINTAINERS.md index f00901e3..886eb024 100644 --- a/MAINTAINERS.md +++ b/MAINTAINERS.md @@ -6,7 +6,7 @@ membership list. | Maintainer | Areas | Affiliation | |---|---|---| -| [@shps951023](https://github.com/shps951023) | Project-wide, .NET, Rust, releases | Not declared | +| [@shps951023](https://github.com/shps951023) | Project-wide, .NET, releases | Not declared | The project currently depends on one active maintainer. This is a known sustainability risk, not the desired long-term governance model. @@ -30,7 +30,7 @@ release verification, or community support. The process is defined in The project is actively seeking independent maintainers for these areas: - .NET document layout and PDF generation; -- Rust XLSX and DOCX rendering; +- .NET XLSX and DOCX rendering; - security and dependency review; - test corpus and visual benchmark maintenance; and - release preparation and independent verification. diff --git a/README.md b/README.md index cb9957b1..b7cc7237 100644 --- a/README.md +++ b/README.md @@ -1,14 +1,9 @@
-**Lightweight, fast and native Office-to-PDF libraries and command-line tools for Rust, .NET, Java, Python, JS, and Go.** +**Lightweight, fast and native Office-to-PDF library and command-line tools for .NET.**

NuGet -crates.io -Maven Central -PyPI -npm -Go Reference GitHub stars DOI License @@ -24,6 +19,10 @@ Your star or donation can make MiniPdf better

+This repository now maintains **MiniPdf for .NET** only. Rust, Java, Go, +Python, and Node.js have moved to their own [PdfLibrarys repositories](https://github.com/PdfLibrarys). +The implementation links below point to those independent repositories. + MiniPdf converts Office documents directly to PDF without Microsoft Office, LibreOffice, Adobe Acrobat, or COM automation at runtime. @@ -32,11 +31,11 @@ LibreOffice, Adobe Acrobat, or COM automation at runtime. | Implementation | Inputs | Interfaces | Maturity | Documentation | Visual results | |---|---|---|---|---|---| | .NET | XLSX, DOCX, PPTX | Library, CLI, Native AOT binaries | Stable | **[.NET guide](documents/README.nuget.md)** | **[XLSX](https://mini-software.github.io/minipdf-web-page/?language=dotnet&suite=classic&format=xlsx)**
**[DOCX](https://mini-software.github.io/minipdf-web-page/?language=dotnet&suite=classic&format=docx)**
**[PPTX](https://mini-software.github.io/minipdf-web-page/?language=dotnet&suite=issue&format=pptx)** | -| Rust | XLSX, DOCX, PPTX | Crate, CLI | Stable | **[Rust guide](minipdf-rs/README.md)** | **[XLSX](https://mini-software.github.io/minipdf-web-page/?language=rust&suite=classic&format=xlsx)**
**[DOCX](https://mini-software.github.io/minipdf-web-page/?language=rust&suite=classic&format=docx)** | -| Java | XLSX, DOCX, PPTX | Library, CLI | Experimental | **[Java source](minipdf-java/)** | **[XLSX](https://mini-software.github.io/minipdf-web-page/?language=java&suite=issue&format=xlsx)**
**[DOCX](https://mini-software.github.io/minipdf-web-page/?language=java&suite=issue&format=docx)** | -| Python | DOCX | Package, CLI | Stable | **[Python guide](minipdf-python/README.md)** | **[XLSX](https://mini-software.github.io/minipdf-web-page/?language=python&suite=issue&format=xlsx)**
**[DOCX](https://mini-software.github.io/minipdf-web-page/?language=python&suite=issue&format=docx)** | -| Node.js | XLSX, DOCX, PPTX | Native package | Stable | **[Node.js guide](minipdf-node/README.md)** | **[XLSX](https://mini-software.github.io/minipdf-web-page/?language=node&suite=issue&format=xlsx)**
**[DOCX](https://mini-software.github.io/minipdf-web-page/?language=node&suite=issue&format=docx)** | -| Go | XLSX, DOCX, PPTX | Package, CLI | Experimental | **[Go guide](minipdf-go/README.md)** | **[XLSX](https://mini-software.github.io/minipdf-web-page/?language=go&suite=issue&format=xlsx)** | +| Rust | XLSX, DOCX, PPTX | Crate, CLI | Stable | **[Rust guide](https://github.com/PdfLibrarys/minipdf-rs/blob/main/README.md)** | **[XLSX](https://mini-software.github.io/minipdf-web-page/?language=rust&suite=classic&format=xlsx)**
**[DOCX](https://mini-software.github.io/minipdf-web-page/?language=rust&suite=classic&format=docx)** | +| Java | XLSX, DOCX, PPTX | Library, CLI | Experimental | **[Java source](https://github.com/PdfLibrarys/minipdf-java)** | **[XLSX](https://mini-software.github.io/minipdf-web-page/?language=java&suite=issue&format=xlsx)**
**[DOCX](https://mini-software.github.io/minipdf-web-page/?language=java&suite=issue&format=docx)** | +| Python | DOCX | Package, CLI | Stable | **[Python guide](https://github.com/PdfLibrarys/minipdf-python/blob/main/README.md)** | **[XLSX](https://mini-software.github.io/minipdf-web-page/?language=python&suite=issue&format=xlsx)**
**[DOCX](https://mini-software.github.io/minipdf-web-page/?language=python&suite=issue&format=docx)** | +| Node.js | XLSX, DOCX, PPTX | Native package | Stable | **[Node.js guide](https://github.com/PdfLibrarys/minipdf-node/blob/main/README.md)** | **[XLSX](https://mini-software.github.io/minipdf-web-page/?language=node&suite=issue&format=xlsx)**
**[DOCX](https://mini-software.github.io/minipdf-web-page/?language=node&suite=issue&format=docx)** | +| Go | XLSX, DOCX, PPTX | Package, CLI | Experimental | **[Go guide](https://github.com/PdfLibrarys/minipdf-go/blob/main/README.md)** | **[XLSX](https://mini-software.github.io/minipdf-web-page/?language=go&suite=issue&format=xlsx)** | ## Quick start @@ -61,92 +60,11 @@ minipdf report.docx -o report.pdf See the [.NET guide](documents/README.nuget.md) for usage. -### Rust - -```bash -cargo add minipdf -cargo install minipdf-cli -``` - -```rust -minipdf::convert_to_pdf("report.docx", "report.pdf")?; -``` - -```bash -minipdf report.docx -o report.pdf -``` - -See the [Rust guide](minipdf-rs/README.md) for usage. - -### Java - -[Maven Central artifact](https://central.sonatype.com/artifact/io.github.mini-software/minipdf) - -```java -import io.github.minisoftware.minipdf.MiniPdf; -import java.nio.file.Files; -import java.nio.file.Path; - -try { - MiniPdf.registerFont( - "Noto Sans", - Files.readAllBytes(Path.of("fonts/NotoSans-Regular.ttf"))); - MiniPdf.convertToPdf(Path.of("report.docx"), Path.of("report.pdf")); -} finally { - MiniPdf.clearRegisteredFonts(); -} -``` - - -See the [Java guide](minipdf-java/README.md) for usage. - -### Python - -```python -import minipdf - -minipdf.convert_to_pdf("report.docx", "report.pdf") -``` - -See the [Python guide](minipdf-python/README.md) for usage. - -### Node.js - -```bash -npm install minipdf -``` - -```javascript -const minipdf = require('minipdf') - -minipdf.convertToPdf('report.docx', 'report.pdf') -``` - -See the [Node.js guide](minipdf-node/README.md) for usage. - -### Go - -```bash -go get github.com/mini-software/MiniPdf/minipdf-go@latest -``` - -```go -import minipdf "github.com/mini-software/MiniPdf/minipdf-go" - -if err := minipdf.ConvertToPDF("report.docx", "report.pdf"); err != nil { - panic(err) -} -``` - -See the [Go guide](minipdf-go/README.md) for usage. - ## Why MiniPdf - **No office suite required**: conversion runs inside your application or CLI. - **Small deployment surface**: minimal dependencies and no external process. - **Server and CI friendly**: works in containers, cloud services, and pipelines. -- **Multiple language options**: use MiniPdf from .NET, Rust, Java, Python, Node.js, or Go. -- **Native command-line options**: available for .NET, Rust, Java, Python, and Go. - **Open development**: Apache 2.0 licensed with reproducible visual benchmarks. MiniPdf targets practical document conversion, not complete Microsoft Office @@ -170,16 +88,13 @@ Run the minipdf-contribution skill. |---|---| | [Online demo](https://mini-software.github.io/MiniPdf/) | Try conversion in a browser | | [.NET documentation](documents/README.nuget.md) | Stable library and CLI usage | -| [Rust documentation](minipdf-rs/README.md) | Experimental crate and CLI usage | -| [Java implementation](minipdf-java/) | Experimental Maven library and CLI source | -| [Python documentation](minipdf-python/README.md) | Experimental package and CLI usage | -| [Node.js documentation](minipdf-node/README.md) | Experimental native package usage | -| [Go documentation](minipdf-go/README.md) | Experimental package and CLI usage | +| [Rust documentation](https://github.com/PdfLibrarys/minipdf-rs/blob/main/README.md) | Experimental crate and CLI usage | +| [Java implementation](https://github.com/PdfLibrarys/minipdf-java) | Experimental Maven library and CLI source | +| [Python documentation](https://github.com/PdfLibrarys/minipdf-python/blob/main/README.md) | Experimental package and CLI usage | +| [Node.js documentation](https://github.com/PdfLibrarys/minipdf-node/blob/main/README.md) | Experimental native package usage | +| [Go documentation](https://github.com/PdfLibrarys/minipdf-go/blob/main/README.md) | Experimental package and CLI usage | | [.NET XLSX benchmark](https://mini-software.github.io/minipdf-web-page/?language=dotnet&suite=classic&format=xlsx) | Visual comparison results for spreadsheets | | [.NET DOCX benchmark](https://mini-software.github.io/minipdf-web-page/?language=dotnet&suite=classic&format=docx) | Visual comparison results for documents | -| [Rust XLSX benchmark](https://mini-software.github.io/minipdf-web-page/?language=rust&suite=classic&format=xlsx) | Rust spreadsheet visual comparison results | -| [Rust DOCX benchmark](https://mini-software.github.io/minipdf-web-page/?language=rust&suite=classic&format=docx) | Rust document visual comparison results | -| [Rust benchmark workflow](scripts/Run-Rust-Benchmark.ps1) | Generate fixture coverage and comparison reports | | [Community governance](GOVERNANCE.md) | Decisions, roles, voting, and maintainer selection | | [Roadmap](ROADMAP.md) | Project scope, implementation status, and current priorities | | [Security](SECURITY.md) | Private vulnerability reporting and supported versions | diff --git a/ROADMAP.md b/ROADMAP.md index 75141d65..bb051653 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -22,15 +22,18 @@ that improves ownership, release clarity, or repository size. MiniExcel is a separate project and is not part of MiniPdf governance or any future MiniPdf incubation proposal. +This repository maintains the .NET implementation. Other language implementations +are maintained independently in [PdfLibrarys](https://github.com/PdfLibrarys). + ## Implementation Status -| Area | .NET | Rust | -|---|---|---| -| XLSX to PDF | Stable, with documented compatibility limits | Experimental | -| DOCX to PDF | Stable, with documented compatibility limits | Experimental | -| PPTX to PDF | Basic support | Unsupported | -| Library API | Stable release line | Experimental pre-1.0 release line | -| CLI | Supported | Experimental | +| Area | .NET | +|---|---| +| XLSX to PDF | Stable, with documented compatibility limits | +| DOCX to PDF | Stable, with documented compatibility limits | +| PPTX to PDF | Basic support | +| Library API | Stable release line | +| CLI | Supported | Stable means the implementation is released and covered by the project's normal compatibility process. It does not mean complete Microsoft Office layout @@ -69,7 +72,7 @@ gaps in their release notes. ### Maintainable Implementations -- Run .NET and Rust validation on every relevant pull request. +- Run .NET validation on every relevant pull request; other repositories own their language checks. - Maintain a versioned format and feature support matrix. - Use shared conformance fixtures where behavior should match while allowing implementation-specific architecture. diff --git a/SECURITY.md b/SECURITY.md index 4d82b0e2..f4d637d8 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -6,9 +6,10 @@ yet covered by an automated test. ## Supported Versions -Security fixes are provided for the latest published .NET release and the -latest published Rust release. Older versions may receive a fix when the impact -and backport risk justify it, but this is not guaranteed. +This repository provides security fixes for the latest published .NET release. +Report issues affecting other languages in their independent repositories. +Older versions may receive a fix when the impact and backport risk justify it, +but this is not guaranteed. ## Reporting a Vulnerability diff --git a/documents/README.fr.md b/documents/README.fr.md index 56c76cb0..3c5bded6 100644 --- a/documents/README.fr.md +++ b/documents/README.fr.md @@ -1,14 +1,9 @@
-**Bibliothèques et outils en ligne de commande Office-vers-PDF légers, rapides et natifs pour Rust, .NET, Java, Python, JS et Go.** +**Bibliothèques et outils en ligne de commande Office-vers-PDF légers, rapides et natifs pour .NET.**

NuGet -crates.io -Maven Central -PyPI -npm -Go Reference GitHub stars DOI License @@ -24,6 +19,10 @@ Votre étoile ou votre don peut améliorer MiniPdf.

+This repository now maintains **MiniPdf for .NET** only. Rust, Java, Go, +Python, and Node.js have moved to their own [PdfLibrarys repositories](https://github.com/PdfLibrarys). +The implementation links below point to those independent repositories. + MiniPdf convertit directement les documents Office en PDF sans nécessiter Microsoft Office, LibreOffice, Adobe Acrobat ni automatisation COM à l'exécution. ## Choisir une implémentation @@ -31,11 +30,11 @@ MiniPdf convertit directement les documents Office en PDF sans nécessiter Micro | Implémentation | Entrées | Interfaces | Maturité | Documentation | Résultats visuels | |---|---|---|---|---|---| | .NET | XLSX, DOCX, PPTX | Bibliothèque, CLI, binaires Native AOT | Stable | **[Guide .NET](README.nuget.md)** | **[XLSX](https://mini-software.github.io/minipdf-web-page/?language=dotnet&suite=classic&format=xlsx)**
**[DOCX](https://mini-software.github.io/minipdf-web-page/?language=dotnet&suite=classic&format=docx)**
**[PPTX](https://mini-software.github.io/minipdf-web-page/?language=dotnet&suite=issue&format=pptx)** | -| Rust | XLSX, DOCX, PPTX | Crate, CLI | Stable | **[Guide Rust](../minipdf-rs/README.md)** | **[XLSX](https://mini-software.github.io/minipdf-web-page/?language=rust&suite=classic&format=xlsx)**
**[DOCX](https://mini-software.github.io/minipdf-web-page/?language=rust&suite=classic&format=docx)** | -| Java | XLSX, DOCX, PPTX | Bibliothèque, CLI | Expérimental | **[Sources Java](../minipdf-java/)** | **[XLSX](https://mini-software.github.io/minipdf-web-page/?language=java&suite=issue&format=xlsx)**
**[DOCX](https://mini-software.github.io/minipdf-web-page/?language=java&suite=issue&format=docx)** | -| Python | DOCX | Paquet, CLI | Stable | **[Guide Python](../minipdf-python/README.md)** | **[XLSX](https://mini-software.github.io/minipdf-web-page/?language=python&suite=issue&format=xlsx)** | -| Node.js | XLSX, DOCX, PPTX | Paquet natif | Stable | **[Guide Node.js](../minipdf-node/README.md)** | **[XLSX](https://mini-software.github.io/minipdf-web-page/?language=node&suite=issue&format=xlsx)** | -| Go | XLSX, DOCX, PPTX | Paquet, CLI | Expérimental | **[Guide Go](../minipdf-go/README.md)** | **[XLSX](https://mini-software.github.io/minipdf-web-page/?language=go&suite=issue&format=xlsx)** | +| Rust | XLSX, DOCX, PPTX | Crate, CLI | Stable | **[Guide Rust](https://github.com/PdfLibrarys/minipdf-rs/blob/main/README.md)** | **[XLSX](https://mini-software.github.io/minipdf-web-page/?language=rust&suite=classic&format=xlsx)**
**[DOCX](https://mini-software.github.io/minipdf-web-page/?language=rust&suite=classic&format=docx)** | +| Java | XLSX, DOCX, PPTX | Bibliothèque, CLI | Expérimental | **[Sources Java](https://github.com/PdfLibrarys/minipdf-java)** | **[XLSX](https://mini-software.github.io/minipdf-web-page/?language=java&suite=issue&format=xlsx)**
**[DOCX](https://mini-software.github.io/minipdf-web-page/?language=java&suite=issue&format=docx)** | +| Python | DOCX | Paquet, CLI | Stable | **[Guide Python](https://github.com/PdfLibrarys/minipdf-python/blob/main/README.md)** | **[XLSX](https://mini-software.github.io/minipdf-web-page/?language=python&suite=issue&format=xlsx)** | +| Node.js | XLSX, DOCX, PPTX | Paquet natif | Stable | **[Guide Node.js](https://github.com/PdfLibrarys/minipdf-node/blob/main/README.md)** | **[XLSX](https://mini-software.github.io/minipdf-web-page/?language=node&suite=issue&format=xlsx)** | +| Go | XLSX, DOCX, PPTX | Paquet, CLI | Expérimental | **[Guide Go](https://github.com/PdfLibrarys/minipdf-go/blob/main/README.md)** | **[XLSX](https://mini-software.github.io/minipdf-web-page/?language=go&suite=issue&format=xlsx)** | ## Démarrage rapide @@ -60,95 +59,11 @@ minipdf report.docx -o report.pdf Pour l'utilisation, consultez le [guide .NET](README.nuget.md). -### Rust - -```bash -cargo add minipdf -cargo install minipdf-cli -``` - -```rust -minipdf::convert_to_pdf("report.docx", "report.pdf")?; -``` - -```bash -minipdf report.docx -o report.pdf -``` - -Pour l'utilisation, consultez le [guide Rust](../minipdf-rs/README.md). - -### Java - -[Maven Central artifact](https://central.sonatype.com/artifact/io.github.mini-software/minipdf) - -```java -import io.github.minisoftware.minipdf.MiniPdf; -import java.nio.file.Files; -import java.nio.file.Path; - -try { - MiniPdf.registerFont( - "Noto Sans", - Files.readAllBytes(Path.of("fonts/NotoSans-Regular.ttf"))); - MiniPdf.convertToPdf(Path.of("report.docx"), Path.of("report.pdf")); -} finally { - MiniPdf.clearRegisteredFonts(); -} -``` - -Pour l'utilisation, consultez le [guide Java](../minipdf-java/README.md). - -### Python - -```bash -pip install minipdf -``` - -```python -import minipdf - -minipdf.convert_to_pdf("report.docx", "report.pdf") -``` - -Pour l'utilisation, consultez le [guide Python](../minipdf-python/README.md). - -### Node.js - -```bash -npm install minipdf -``` - -```javascript -const minipdf = require('minipdf') - -minipdf.convertToPdf('report.docx', 'report.pdf') -``` - -Pour l'utilisation, consultez le [guide Node.js](../minipdf-node/README.md). - -### Go - -```bash -go get github.com/mini-software/MiniPdf/minipdf-go@latest -``` - -```go -import minipdf "github.com/mini-software/MiniPdf/minipdf-go" - -if err := minipdf.ConvertToPDF("report.docx", "report.pdf"); err != nil { - panic(err) -} -``` - -Pour l'utilisation, consultez le [guide Go](../minipdf-go/README.md). - ## Pourquoi MiniPdf - **Aucune suite Office requise** : la conversion s'exécute dans l'application ou la CLI. - **Déploiement réduit** : peu de dépendances et aucun processus externe. - **Adapté aux serveurs et à la CI** : fonctionne dans les conteneurs, services cloud et pipelines. -- **Plusieurs langages disponibles** : utilisez MiniPdf depuis .NET, Rust, Java, Python, Node.js ou Go. -- **Options natives en ligne de commande** : disponibles pour .NET, Rust, Java, Python et Go. MiniPdf vise une conversion pratique des documents, et non une compatibilité totale avec la mise en page de Microsoft Office. Les modèles complexes peuvent être rendus différemment ; utilisez la démo en ligne ou les rapports de benchmark pour évaluer des fichiers représentatifs. @@ -168,16 +83,16 @@ Run the minipdf-contribution skill. |---|---| | [Démo en ligne](https://mini-software.github.io/MiniPdf/) | Tester la conversion dans le navigateur | | [Documentation .NET](README.nuget.md) | Utilisation de la bibliothèque stable et de la CLI | -| [Documentation Rust](../minipdf-rs/README.md) | Utilisation du crate expérimental et de la CLI | -| [Implémentation Java](../minipdf-java/) | Sources de la bibliothèque Maven et de la CLI expérimentales | -| [Documentation Python](../minipdf-python/README.md) | Utilisation du paquet expérimental et de la CLI | -| [Documentation Node.js](../minipdf-node/README.md) | Utilisation du paquet natif expérimental | -| [Documentation Go](../minipdf-go/README.md) | Utilisation du paquet expérimental et de la CLI | +| [Documentation Rust](https://github.com/PdfLibrarys/minipdf-rs/blob/main/README.md) | Utilisation du crate expérimental et de la CLI | +| [Implémentation Java](https://github.com/PdfLibrarys/minipdf-java) | Sources de la bibliothèque Maven et de la CLI expérimentales | +| [Documentation Python](https://github.com/PdfLibrarys/minipdf-python/blob/main/README.md) | Utilisation du paquet expérimental et de la CLI | +| [Documentation Node.js](https://github.com/PdfLibrarys/minipdf-node/blob/main/README.md) | Utilisation du paquet natif expérimental | +| [Documentation Go](https://github.com/PdfLibrarys/minipdf-go/blob/main/README.md) | Utilisation du paquet expérimental et de la CLI | | [Benchmark XLSX .NET](https://mini-software.github.io/minipdf-web-page/?language=dotnet&suite=classic&format=xlsx) | Résultats visuels pour les feuilles de calcul | | [Benchmark DOCX .NET](https://mini-software.github.io/minipdf-web-page/?language=dotnet&suite=classic&format=docx) | Résultats visuels pour les documents | | [Benchmark XLSX Rust](https://mini-software.github.io/minipdf-web-page/?language=rust&suite=classic&format=xlsx) | Résultats de comparaison visuelle Rust des feuilles de calcul | | [Benchmark DOCX Rust](https://mini-software.github.io/minipdf-web-page/?language=rust&suite=classic&format=docx) | Résultats de comparaison visuelle Rust des documents | -| [Procédure de benchmark Rust](../scripts/Run-Rust-Benchmark.ps1) | Génère la couverture des tests et les rapports comparatifs | +| [Procédure de benchmark Rust](https://github.com/PdfLibrarys/minipdf-rs) | Génère la couverture des tests et les rapports comparatifs | | [Gouvernance communautaire](../GOVERNANCE.md) | Décisions, rôles, votes et sélection des mainteneurs | | [Feuille de route](../ROADMAP.md) | Périmètre du projet, état des implémentations et priorités | | [Sécurité](../SECURITY.md) | Signalement privé des vulnérabilités et versions prises en charge | diff --git a/documents/README.it.md b/documents/README.it.md index c3434466..dfda030c 100644 --- a/documents/README.it.md +++ b/documents/README.it.md @@ -1,14 +1,9 @@
-**Librerie e strumenti da riga di comando Office-to-PDF leggeri, veloci e nativi per Rust, .NET, Java, Python, JS e Go.** +**Librerie e strumenti da riga di comando Office-to-PDF leggeri, veloci e nativi per .NET.**

NuGet -crates.io -Maven Central -PyPI -npm -Go Reference GitHub stars DOI License @@ -24,6 +19,10 @@ La tua stella o donazione può rendere MiniPdf migliore.

+This repository now maintains **MiniPdf for .NET** only. Rust, Java, Go, +Python, and Node.js have moved to their own [PdfLibrarys repositories](https://github.com/PdfLibrarys). +The implementation links below point to those independent repositories. + MiniPdf converte direttamente i documenti Office in PDF senza richiedere Microsoft Office, LibreOffice, Adobe Acrobat o automazione COM durante l'esecuzione. ## Scegli un'implementazione @@ -31,11 +30,11 @@ MiniPdf converte direttamente i documenti Office in PDF senza richiedere Microso | Implementazione | Input | Interfacce | Maturità | Documentazione | Risultati visivi | |---|---|---|---|---|---| | .NET | XLSX, DOCX, PPTX | Libreria, CLI, binari Native AOT | Stabile | **[Guida .NET](README.nuget.md)** | **[XLSX](https://mini-software.github.io/minipdf-web-page/?language=dotnet&suite=classic&format=xlsx)**
**[DOCX](https://mini-software.github.io/minipdf-web-page/?language=dotnet&suite=classic&format=docx)**
**[PPTX](https://mini-software.github.io/minipdf-web-page/?language=dotnet&suite=issue&format=pptx)** | -| Rust | XLSX, DOCX, PPTX | Crate, CLI | Stabile | **[Guida Rust](../minipdf-rs/README.md)** | **[XLSX](https://mini-software.github.io/minipdf-web-page/?language=rust&suite=classic&format=xlsx)**
**[DOCX](https://mini-software.github.io/minipdf-web-page/?language=rust&suite=classic&format=docx)** | -| Java | XLSX, DOCX, PPTX | Libreria, CLI | Sperimentale | **[Sorgenti Java](../minipdf-java/)** | **[XLSX](https://mini-software.github.io/minipdf-web-page/?language=java&suite=issue&format=xlsx)**
**[DOCX](https://mini-software.github.io/minipdf-web-page/?language=java&suite=issue&format=docx)** | -| Python | DOCX | Pacchetto, CLI | Stabile | **[Guida Python](../minipdf-python/README.md)** | **[XLSX](https://mini-software.github.io/minipdf-web-page/?language=python&suite=issue&format=xlsx)** | -| Node.js | XLSX, DOCX, PPTX | Pacchetto nativo | Stabile | **[Guida Node.js](../minipdf-node/README.md)** | **[XLSX](https://mini-software.github.io/minipdf-web-page/?language=node&suite=issue&format=xlsx)** | -| Go | XLSX, DOCX, PPTX | Pacchetto, CLI | Sperimentale | **[Guida Go](../minipdf-go/README.md)** | **[XLSX](https://mini-software.github.io/minipdf-web-page/?language=go&suite=issue&format=xlsx)** | +| Rust | XLSX, DOCX, PPTX | Crate, CLI | Stabile | **[Guida Rust](https://github.com/PdfLibrarys/minipdf-rs/blob/main/README.md)** | **[XLSX](https://mini-software.github.io/minipdf-web-page/?language=rust&suite=classic&format=xlsx)**
**[DOCX](https://mini-software.github.io/minipdf-web-page/?language=rust&suite=classic&format=docx)** | +| Java | XLSX, DOCX, PPTX | Libreria, CLI | Sperimentale | **[Sorgenti Java](https://github.com/PdfLibrarys/minipdf-java)** | **[XLSX](https://mini-software.github.io/minipdf-web-page/?language=java&suite=issue&format=xlsx)**
**[DOCX](https://mini-software.github.io/minipdf-web-page/?language=java&suite=issue&format=docx)** | +| Python | DOCX | Pacchetto, CLI | Stabile | **[Guida Python](https://github.com/PdfLibrarys/minipdf-python/blob/main/README.md)** | **[XLSX](https://mini-software.github.io/minipdf-web-page/?language=python&suite=issue&format=xlsx)** | +| Node.js | XLSX, DOCX, PPTX | Pacchetto nativo | Stabile | **[Guida Node.js](https://github.com/PdfLibrarys/minipdf-node/blob/main/README.md)** | **[XLSX](https://mini-software.github.io/minipdf-web-page/?language=node&suite=issue&format=xlsx)** | +| Go | XLSX, DOCX, PPTX | Pacchetto, CLI | Sperimentale | **[Guida Go](https://github.com/PdfLibrarys/minipdf-go/blob/main/README.md)** | **[XLSX](https://mini-software.github.io/minipdf-web-page/?language=go&suite=issue&format=xlsx)** | ## Avvio rapido @@ -60,95 +59,11 @@ minipdf report.docx -o report.pdf Per l'uso, consulta la [guida .NET](README.nuget.md). -### Rust - -```bash -cargo add minipdf -cargo install minipdf-cli -``` - -```rust -minipdf::convert_to_pdf("report.docx", "report.pdf")?; -``` - -```bash -minipdf report.docx -o report.pdf -``` - -Per l'uso, consulta la [guida Rust](../minipdf-rs/README.md). - -### Java - -[Maven Central artifact](https://central.sonatype.com/artifact/io.github.mini-software/minipdf) - -```java -import io.github.minisoftware.minipdf.MiniPdf; -import java.nio.file.Files; -import java.nio.file.Path; - -try { - MiniPdf.registerFont( - "Noto Sans", - Files.readAllBytes(Path.of("fonts/NotoSans-Regular.ttf"))); - MiniPdf.convertToPdf(Path.of("report.docx"), Path.of("report.pdf")); -} finally { - MiniPdf.clearRegisteredFonts(); -} -``` - -Per l'uso, consulta la [guida Java](../minipdf-java/README.md). - -### Python - -```bash -pip install minipdf -``` - -```python -import minipdf - -minipdf.convert_to_pdf("report.docx", "report.pdf") -``` - -Per l'uso, consulta la [guida Python](../minipdf-python/README.md). - -### Node.js - -```bash -npm install minipdf -``` - -```javascript -const minipdf = require('minipdf') - -minipdf.convertToPdf('report.docx', 'report.pdf') -``` - -Per l'uso, consulta la [guida Node.js](../minipdf-node/README.md). - -### Go - -```bash -go get github.com/mini-software/MiniPdf/minipdf-go@latest -``` - -```go -import minipdf "github.com/mini-software/MiniPdf/minipdf-go" - -if err := minipdf.ConvertToPDF("report.docx", "report.pdf"); err != nil { - panic(err) -} -``` - -Per l'uso, consulta la [guida Go](../minipdf-go/README.md). - ## Perché MiniPdf - **Nessuna suite Office richiesta**: la conversione viene eseguita nell'applicazione o nella CLI. - **Distribuzione essenziale**: poche dipendenze e nessun processo esterno. - **Adatto a server e CI**: funziona in container, servizi cloud e pipeline. -- **Più linguaggi disponibili**: usa MiniPdf da .NET, Rust, Java, Python, Node.js o Go. -- **Opzioni native da riga di comando**: disponibili per .NET, Rust, Java, Python e Go. MiniPdf punta alla conversione pratica dei documenti, non alla compatibilità completa con il layout di Microsoft Office. I modelli complessi possono essere visualizzati diversamente; usa la demo online o i report di benchmark per valutare file rappresentativi. @@ -168,16 +83,16 @@ Run the minipdf-contribution skill. |---|---| | [Demo online](https://mini-software.github.io/MiniPdf/) | Prova la conversione nel browser | | [Documentazione .NET](README.nuget.md) | Uso della libreria stabile e della CLI | -| [Documentazione Rust](../minipdf-rs/README.md) | Uso del crate sperimentale e della CLI | -| [Implementazione Java](../minipdf-java/) | Sorgenti della libreria Maven e della CLI sperimentali | -| [Documentazione Python](../minipdf-python/README.md) | Uso del pacchetto sperimentale e della CLI | -| [Documentazione Node.js](../minipdf-node/README.md) | Uso del pacchetto nativo sperimentale | -| [Documentazione Go](../minipdf-go/README.md) | Uso del pacchetto sperimentale e della CLI | +| [Documentazione Rust](https://github.com/PdfLibrarys/minipdf-rs/blob/main/README.md) | Uso del crate sperimentale e della CLI | +| [Implementazione Java](https://github.com/PdfLibrarys/minipdf-java) | Sorgenti della libreria Maven e della CLI sperimentali | +| [Documentazione Python](https://github.com/PdfLibrarys/minipdf-python/blob/main/README.md) | Uso del pacchetto sperimentale e della CLI | +| [Documentazione Node.js](https://github.com/PdfLibrarys/minipdf-node/blob/main/README.md) | Uso del pacchetto nativo sperimentale | +| [Documentazione Go](https://github.com/PdfLibrarys/minipdf-go/blob/main/README.md) | Uso del pacchetto sperimentale e della CLI | | [Benchmark XLSX .NET](https://mini-software.github.io/minipdf-web-page/?language=dotnet&suite=classic&format=xlsx) | Risultati visivi per i fogli di calcolo | | [Benchmark DOCX .NET](https://mini-software.github.io/minipdf-web-page/?language=dotnet&suite=classic&format=docx) | Risultati visivi per i documenti | | [Benchmark XLSX Rust](https://mini-software.github.io/minipdf-web-page/?language=rust&suite=classic&format=xlsx) | Risultati del confronto visivo Rust per i fogli di calcolo | | [Benchmark DOCX Rust](https://mini-software.github.io/minipdf-web-page/?language=rust&suite=classic&format=docx) | Risultati del confronto visivo Rust per i documenti | -| [Flusso benchmark Rust](../scripts/Run-Rust-Benchmark.ps1) | Genera copertura dei test e report comparativi | +| [Flusso benchmark Rust](https://github.com/PdfLibrarys/minipdf-rs) | Genera copertura dei test e report comparativi | | [Governance della comunità](../GOVERNANCE.md) | Decisioni, ruoli, votazioni e selezione dei maintainer | | [Roadmap](../ROADMAP.md) | Ambito del progetto, stato delle implementazioni e priorità | | [Sicurezza](../SECURITY.md) | Segnalazione privata delle vulnerabilità e versioni supportate | diff --git a/documents/README.ja.md b/documents/README.ja.md index 89e5c5b4..354c0af5 100644 --- a/documents/README.ja.md +++ b/documents/README.ja.md @@ -1,14 +1,9 @@
-**Rust、.NET、Java、Python、JS、Go 向けの軽量・高速・ネイティブな Office-to-PDF ライブラリおよびコマンドラインツール。** +**.NET 向けの軽量・高速・ネイティブな Office-to-PDF ライブラリおよびコマンドラインツール。**

NuGet -crates.io -Maven Central -PyPI -npm -Go Reference GitHub stars DOI License @@ -24,6 +19,10 @@

+This repository now maintains **MiniPdf for .NET** only. Rust, Java, Go, +Python, and Node.js have moved to their own [PdfLibrarys repositories](https://github.com/PdfLibrarys). +The implementation links below point to those independent repositories. + MiniPdf は、実行時に Microsoft Office、LibreOffice、Adobe Acrobat、COM オートメーションを必要とせず、Office 文書を直接 PDF に変換します。 ## 実装を選ぶ @@ -31,11 +30,11 @@ MiniPdf は、実行時に Microsoft Office、LibreOffice、Adobe Acrobat、COM | 実装 | 入力 | インターフェイス | 成熟度 | ドキュメント | 視覚結果 | |---|---|---|---|---|---| | .NET | XLSX、DOCX、PPTX | ライブラリ、CLI、Native AOT バイナリ | 安定版 | **[.NET ガイド](README.nuget.md)** | **[XLSX](https://mini-software.github.io/minipdf-web-page/?language=dotnet&suite=classic&format=xlsx)**
**[DOCX](https://mini-software.github.io/minipdf-web-page/?language=dotnet&suite=classic&format=docx)**
**[PPTX](https://mini-software.github.io/minipdf-web-page/?language=dotnet&suite=issue&format=pptx)** | -| Rust | XLSX、DOCX、PPTX | Crate、CLI | 安定版 | **[Rust ガイド](../minipdf-rs/README.md)** | **[XLSX](https://mini-software.github.io/minipdf-web-page/?language=rust&suite=classic&format=xlsx)**
**[DOCX](https://mini-software.github.io/minipdf-web-page/?language=rust&suite=classic&format=docx)** | -| Java | XLSX、DOCX、PPTX | ライブラリ、CLI | 実験版 | **[Java ソース](../minipdf-java/)** | **[XLSX](https://mini-software.github.io/minipdf-web-page/?language=java&suite=issue&format=xlsx)**
**[DOCX](https://mini-software.github.io/minipdf-web-page/?language=java&suite=issue&format=docx)** | -| Python | DOCX | パッケージ、CLI | 安定版 | **[Python ガイド](../minipdf-python/README.md)** | **[XLSX](https://mini-software.github.io/minipdf-web-page/?language=python&suite=issue&format=xlsx)** | -| Node.js | XLSX、DOCX、PPTX | ネイティブパッケージ | 安定版 | **[Node.js ガイド](../minipdf-node/README.md)** | **[XLSX](https://mini-software.github.io/minipdf-web-page/?language=node&suite=issue&format=xlsx)** | -| Go | XLSX、DOCX、PPTX | パッケージ、CLI | 実験版 | **[Go ガイド](../minipdf-go/README.md)** | **[XLSX](https://mini-software.github.io/minipdf-web-page/?language=go&suite=issue&format=xlsx)** | +| Rust | XLSX、DOCX、PPTX | Crate、CLI | 安定版 | **[Rust ガイド](https://github.com/PdfLibrarys/minipdf-rs/blob/main/README.md)** | **[XLSX](https://mini-software.github.io/minipdf-web-page/?language=rust&suite=classic&format=xlsx)**
**[DOCX](https://mini-software.github.io/minipdf-web-page/?language=rust&suite=classic&format=docx)** | +| Java | XLSX、DOCX、PPTX | ライブラリ、CLI | 実験版 | **[Java ソース](https://github.com/PdfLibrarys/minipdf-java)** | **[XLSX](https://mini-software.github.io/minipdf-web-page/?language=java&suite=issue&format=xlsx)**
**[DOCX](https://mini-software.github.io/minipdf-web-page/?language=java&suite=issue&format=docx)** | +| Python | DOCX | パッケージ、CLI | 安定版 | **[Python ガイド](https://github.com/PdfLibrarys/minipdf-python/blob/main/README.md)** | **[XLSX](https://mini-software.github.io/minipdf-web-page/?language=python&suite=issue&format=xlsx)** | +| Node.js | XLSX、DOCX、PPTX | ネイティブパッケージ | 安定版 | **[Node.js ガイド](https://github.com/PdfLibrarys/minipdf-node/blob/main/README.md)** | **[XLSX](https://mini-software.github.io/minipdf-web-page/?language=node&suite=issue&format=xlsx)** | +| Go | XLSX、DOCX、PPTX | パッケージ、CLI | 実験版 | **[Go ガイド](https://github.com/PdfLibrarys/minipdf-go/blob/main/README.md)** | **[XLSX](https://mini-software.github.io/minipdf-web-page/?language=go&suite=issue&format=xlsx)** | ## クイックスタート @@ -60,95 +59,11 @@ minipdf report.docx -o report.pdf 使用方法については [.NET ガイド](README.nuget.md) をご覧ください。 -### Rust - -```bash -cargo add minipdf -cargo install minipdf-cli -``` - -```rust -minipdf::convert_to_pdf("report.docx", "report.pdf")?; -``` - -```bash -minipdf report.docx -o report.pdf -``` - -使用方法については [Rust ガイド](../minipdf-rs/README.md) をご覧ください。 - -### Java - -[Maven Central artifact](https://central.sonatype.com/artifact/io.github.mini-software/minipdf) - -```java -import io.github.minisoftware.minipdf.MiniPdf; -import java.nio.file.Files; -import java.nio.file.Path; - -try { - MiniPdf.registerFont( - "Noto Sans", - Files.readAllBytes(Path.of("fonts/NotoSans-Regular.ttf"))); - MiniPdf.convertToPdf(Path.of("report.docx"), Path.of("report.pdf")); -} finally { - MiniPdf.clearRegisteredFonts(); -} -``` - -使用方法については [Java ガイド](../minipdf-java/README.md) をご覧ください。 - -### Python - -```bash -pip install minipdf -``` - -```python -import minipdf - -minipdf.convert_to_pdf("report.docx", "report.pdf") -``` - -使用方法については [Python ガイド](../minipdf-python/README.md) をご覧ください。 - -### Node.js - -```bash -npm install minipdf -``` - -```javascript -const minipdf = require('minipdf') - -minipdf.convertToPdf('report.docx', 'report.pdf') -``` - -使用方法については [Node.js ガイド](../minipdf-node/README.md) をご覧ください。 - -### Go - -```bash -go get github.com/mini-software/MiniPdf/minipdf-go@latest -``` - -```go -import minipdf "github.com/mini-software/MiniPdf/minipdf-go" - -if err := minipdf.ConvertToPDF("report.docx", "report.pdf"); err != nil { - panic(err) -} -``` - -使用方法については [Go ガイド](../minipdf-go/README.md) をご覧ください。 - ## MiniPdf を選ぶ理由 - **Office スイート不要**:変換はアプリケーションまたは CLI 内で実行されます。 - **小さなデプロイ構成**:依存関係が少なく、外部プロセスも不要です。 - **サーバーと CI に対応**:コンテナー、クラウドサービス、パイプラインで利用できます。 -- **複数言語に対応**:.NET、Rust、Java、Python、Node.js、Go から MiniPdf を利用できます。 -- **ネイティブ CLI**:.NET、Rust、Java、Python、Go で利用できます。 MiniPdf は実用的な文書変換を目的としており、Microsoft Office のレイアウトを完全に再現するものではありません。複雑なテンプレートは表示が異なる場合があるため、オンラインデモやベンチマークレポートで代表的なファイルを評価してください。 @@ -168,16 +83,16 @@ Run the minipdf-contribution skill. |---|---| | [オンラインデモ](https://mini-software.github.io/MiniPdf/) | ブラウザーで変換を試す | | [.NET ドキュメント](README.nuget.md) | 安定版ライブラリと CLI の使用方法 | -| [Rust ドキュメント](../minipdf-rs/README.md) | 実験版 crate と CLI の使用方法 | -| [Java 実装](../minipdf-java/) | 実験版 Maven ライブラリと CLI のソース | -| [Python ドキュメント](../minipdf-python/README.md) | 実験版パッケージと CLI の使用方法 | -| [Node.js ドキュメント](../minipdf-node/README.md) | 実験版ネイティブパッケージの使用方法 | -| [Go ドキュメント](../minipdf-go/README.md) | 実験版パッケージと CLI の使用方法 | +| [Rust ドキュメント](https://github.com/PdfLibrarys/minipdf-rs/blob/main/README.md) | 実験版 crate と CLI の使用方法 | +| [Java 実装](https://github.com/PdfLibrarys/minipdf-java) | 実験版 Maven ライブラリと CLI のソース | +| [Python ドキュメント](https://github.com/PdfLibrarys/minipdf-python/blob/main/README.md) | 実験版パッケージと CLI の使用方法 | +| [Node.js ドキュメント](https://github.com/PdfLibrarys/minipdf-node/blob/main/README.md) | 実験版ネイティブパッケージの使用方法 | +| [Go ドキュメント](https://github.com/PdfLibrarys/minipdf-go/blob/main/README.md) | 実験版パッケージと CLI の使用方法 | | [.NET XLSX ベンチマーク](https://mini-software.github.io/minipdf-web-page/?language=dotnet&suite=classic&format=xlsx) | スプレッドシートの視覚比較結果 | | [.NET DOCX ベンチマーク](https://mini-software.github.io/minipdf-web-page/?language=dotnet&suite=classic&format=docx) | 文書の視覚比較結果 | | [Rust XLSX ベンチマーク](https://mini-software.github.io/minipdf-web-page/?language=rust&suite=classic&format=xlsx) | Rust スプレッドシートの視覚比較結果 | | [Rust DOCX ベンチマーク](https://mini-software.github.io/minipdf-web-page/?language=rust&suite=classic&format=docx) | Rust ドキュメントの視覚比較結果 | -| [Rust ベンチマーク手順](../scripts/Run-Rust-Benchmark.ps1) | フィクスチャ範囲と比較レポートを生成 | +| [Rust ベンチマーク手順](https://github.com/PdfLibrarys/minipdf-rs) | フィクスチャ範囲と比較レポートを生成 | | [コミュニティガバナンス](../GOVERNANCE.md) | 意思決定、役割、投票、メンテナー選出 | | [ロードマップ](../ROADMAP.md) | プロジェクト範囲、実装状況、現在の優先事項 | | [セキュリティ](../SECURITY.md) | 脆弱性の非公開報告とサポート対象バージョン | diff --git a/documents/README.ko.md b/documents/README.ko.md index b790e798..6de14b61 100644 --- a/documents/README.ko.md +++ b/documents/README.ko.md @@ -1,14 +1,9 @@
-**Rust, .NET, Java, Python, JS 및 Go용 경량·고속·네이티브 Office-to-PDF 라이브러리와 명령줄 도구입니다.** +**.NET용 경량·고속·네이티브 Office-to-PDF 라이브러리와 명령줄 도구입니다.**

NuGet -crates.io -Maven Central -PyPI -npm -Go Reference GitHub stars DOI License @@ -24,6 +19,10 @@

+This repository now maintains **MiniPdf for .NET** only. Rust, Java, Go, +Python, and Node.js have moved to their own [PdfLibrarys repositories](https://github.com/PdfLibrarys). +The implementation links below point to those independent repositories. + MiniPdf는 런타임에 Microsoft Office, LibreOffice, Adobe Acrobat 또는 COM 자동화 없이 Office 문서를 PDF로 직접 변환합니다. ## 구현 선택 @@ -31,11 +30,11 @@ MiniPdf는 런타임에 Microsoft Office, LibreOffice, Adobe Acrobat 또는 COM | 구현 | 입력 | 인터페이스 | 성숙도 | 문서 | 시각적 결과 | |---|---|---|---|---|---| | .NET | XLSX, DOCX, PPTX | 라이브러리, CLI, Native AOT 바이너리 | 안정 | **[.NET 가이드](README.nuget.md)** | **[XLSX](https://mini-software.github.io/minipdf-web-page/?language=dotnet&suite=classic&format=xlsx)**
**[DOCX](https://mini-software.github.io/minipdf-web-page/?language=dotnet&suite=classic&format=docx)**
**[PPTX](https://mini-software.github.io/minipdf-web-page/?language=dotnet&suite=issue&format=pptx)** | -| Rust | XLSX, DOCX, PPTX | Crate, CLI | 안정 | **[Rust 가이드](../minipdf-rs/README.md)** | **[XLSX](https://mini-software.github.io/minipdf-web-page/?language=rust&suite=classic&format=xlsx)**
**[DOCX](https://mini-software.github.io/minipdf-web-page/?language=rust&suite=classic&format=docx)** | -| Java | XLSX, DOCX, PPTX | 라이브러리, CLI | 실험적 | **[Java 소스](../minipdf-java/)** | **[XLSX](https://mini-software.github.io/minipdf-web-page/?language=java&suite=issue&format=xlsx)**
**[DOCX](https://mini-software.github.io/minipdf-web-page/?language=java&suite=issue&format=docx)** | -| Python | DOCX | 패키지, CLI | 안정 | **[Python 가이드](../minipdf-python/README.md)** | **[XLSX](https://mini-software.github.io/minipdf-web-page/?language=python&suite=issue&format=xlsx)** | -| Node.js | XLSX, DOCX, PPTX | 네이티브 패키지 | 안정 | **[Node.js 가이드](../minipdf-node/README.md)** | **[XLSX](https://mini-software.github.io/minipdf-web-page/?language=node&suite=issue&format=xlsx)** | -| Go | XLSX, DOCX, PPTX | 패키지, CLI | 실험적 | **[Go 가이드](../minipdf-go/README.md)** | **[XLSX](https://mini-software.github.io/minipdf-web-page/?language=go&suite=issue&format=xlsx)** | +| Rust | XLSX, DOCX, PPTX | Crate, CLI | 안정 | **[Rust 가이드](https://github.com/PdfLibrarys/minipdf-rs/blob/main/README.md)** | **[XLSX](https://mini-software.github.io/minipdf-web-page/?language=rust&suite=classic&format=xlsx)**
**[DOCX](https://mini-software.github.io/minipdf-web-page/?language=rust&suite=classic&format=docx)** | +| Java | XLSX, DOCX, PPTX | 라이브러리, CLI | 실험적 | **[Java 소스](https://github.com/PdfLibrarys/minipdf-java)** | **[XLSX](https://mini-software.github.io/minipdf-web-page/?language=java&suite=issue&format=xlsx)**
**[DOCX](https://mini-software.github.io/minipdf-web-page/?language=java&suite=issue&format=docx)** | +| Python | DOCX | 패키지, CLI | 안정 | **[Python 가이드](https://github.com/PdfLibrarys/minipdf-python/blob/main/README.md)** | **[XLSX](https://mini-software.github.io/minipdf-web-page/?language=python&suite=issue&format=xlsx)** | +| Node.js | XLSX, DOCX, PPTX | 네이티브 패키지 | 안정 | **[Node.js 가이드](https://github.com/PdfLibrarys/minipdf-node/blob/main/README.md)** | **[XLSX](https://mini-software.github.io/minipdf-web-page/?language=node&suite=issue&format=xlsx)** | +| Go | XLSX, DOCX, PPTX | 패키지, CLI | 실험적 | **[Go 가이드](https://github.com/PdfLibrarys/minipdf-go/blob/main/README.md)** | **[XLSX](https://mini-software.github.io/minipdf-web-page/?language=go&suite=issue&format=xlsx)** | ## 빠른 시작 @@ -60,95 +59,11 @@ minipdf report.docx -o report.pdf 사용 방법은 [.NET 가이드](README.nuget.md)를 참조하세요. -### Rust - -```bash -cargo add minipdf -cargo install minipdf-cli -``` - -```rust -minipdf::convert_to_pdf("report.docx", "report.pdf")?; -``` - -```bash -minipdf report.docx -o report.pdf -``` - -사용 방법은 [Rust 가이드](../minipdf-rs/README.md)를 참조하세요. - -### Java - -[Maven Central artifact](https://central.sonatype.com/artifact/io.github.mini-software/minipdf) - -```java -import io.github.minisoftware.minipdf.MiniPdf; -import java.nio.file.Files; -import java.nio.file.Path; - -try { - MiniPdf.registerFont( - "Noto Sans", - Files.readAllBytes(Path.of("fonts/NotoSans-Regular.ttf"))); - MiniPdf.convertToPdf(Path.of("report.docx"), Path.of("report.pdf")); -} finally { - MiniPdf.clearRegisteredFonts(); -} -``` - -사용 방법은 [Java 가이드](../minipdf-java/README.md)를 참조하세요. - -### Python - -```bash -pip install minipdf -``` - -```python -import minipdf - -minipdf.convert_to_pdf("report.docx", "report.pdf") -``` - -사용 방법은 [Python 가이드](../minipdf-python/README.md)를 참조하세요. - -### Node.js - -```bash -npm install minipdf -``` - -```javascript -const minipdf = require('minipdf') - -minipdf.convertToPdf('report.docx', 'report.pdf') -``` - -사용 방법은 [Node.js 가이드](../minipdf-node/README.md)를 참조하세요. - -### Go - -```bash -go get github.com/mini-software/MiniPdf/minipdf-go@latest -``` - -```go -import minipdf "github.com/mini-software/MiniPdf/minipdf-go" - -if err := minipdf.ConvertToPDF("report.docx", "report.pdf"); err != nil { - panic(err) -} -``` - -사용 방법은 [Go 가이드](../minipdf-go/README.md)를 참조하세요. - ## MiniPdf를 선택하는 이유 - **Office 제품군 불필요**: 애플리케이션 또는 CLI 내부에서 변환합니다. - **간결한 배포**: 의존성이 적고 외부 프로세스가 필요하지 않습니다. - **서버 및 CI 친화적**: 컨테이너, 클라우드 서비스 및 파이프라인에서 실행됩니다. -- **다양한 언어 선택**: .NET, Rust, Java, Python, Node.js 또는 Go에서 MiniPdf를 사용할 수 있습니다. -- **네이티브 명령줄 옵션**: .NET, Rust, Java, Python 및 Go에서 사용할 수 있습니다. MiniPdf는 실용적인 문서 변환을 목표로 하며 Microsoft Office 레이아웃을 완전히 재현하지는 않습니다. 복잡한 템플릿은 다르게 렌더링될 수 있으므로 온라인 데모나 벤치마크 보고서로 대표 파일을 평가하세요. @@ -168,16 +83,16 @@ Run the minipdf-contribution skill. |---|---| | [온라인 데모](https://mini-software.github.io/MiniPdf/) | 브라우저에서 변환 체험 | | [.NET 문서](README.nuget.md) | 안정 버전 라이브러리 및 CLI 사용법 | -| [Rust 문서](../minipdf-rs/README.md) | 실험 버전 crate 및 CLI 사용법 | -| [Java 구현](../minipdf-java/) | 실험적 Maven 라이브러리 및 CLI 소스 | -| [Python 문서](../minipdf-python/README.md) | 실험적 패키지 및 CLI 사용법 | -| [Node.js 문서](../minipdf-node/README.md) | 실험적 네이티브 패키지 사용법 | -| [Go 문서](../minipdf-go/README.md) | 실험적 패키지 및 CLI 사용법 | +| [Rust 문서](https://github.com/PdfLibrarys/minipdf-rs/blob/main/README.md) | 실험 버전 crate 및 CLI 사용법 | +| [Java 구현](https://github.com/PdfLibrarys/minipdf-java) | 실험적 Maven 라이브러리 및 CLI 소스 | +| [Python 문서](https://github.com/PdfLibrarys/minipdf-python/blob/main/README.md) | 실험적 패키지 및 CLI 사용법 | +| [Node.js 문서](https://github.com/PdfLibrarys/minipdf-node/blob/main/README.md) | 실험적 네이티브 패키지 사용법 | +| [Go 문서](https://github.com/PdfLibrarys/minipdf-go/blob/main/README.md) | 실험적 패키지 및 CLI 사용법 | | [.NET XLSX 벤치마크](https://mini-software.github.io/minipdf-web-page/?language=dotnet&suite=classic&format=xlsx) | 스프레드시트 시각 비교 결과 | | [.NET DOCX 벤치마크](https://mini-software.github.io/minipdf-web-page/?language=dotnet&suite=classic&format=docx) | 문서 시각 비교 결과 | | [Rust XLSX 벤치마크](https://mini-software.github.io/minipdf-web-page/?language=rust&suite=classic&format=xlsx) | Rust 스프레드시트 시각 비교 결과 | | [Rust DOCX 벤치마크](https://mini-software.github.io/minipdf-web-page/?language=rust&suite=classic&format=docx) | Rust 문서 시각 비교 결과 | -| [Rust 벤치마크 절차](../scripts/Run-Rust-Benchmark.ps1) | 픽스처 범위 및 비교 보고서 생성 | +| [Rust 벤치마크 절차](https://github.com/PdfLibrarys/minipdf-rs) | 픽스처 범위 및 비교 보고서 생성 | | [커뮤니티 거버넌스](../GOVERNANCE.md) | 의사 결정, 역할, 투표 및 메인테이너 선정 | | [로드맵](../ROADMAP.md) | 프로젝트 범위, 구현 상태 및 현재 우선순위 | | [보안](../SECURITY.md) | 비공개 취약점 신고 및 지원 버전 | diff --git a/documents/README.zh-CN.md b/documents/README.zh-CN.md index cfa262d2..f2c5f55e 100644 --- a/documents/README.zh-CN.md +++ b/documents/README.zh-CN.md @@ -1,14 +1,9 @@
-**轻量、快速且原生的 Office 转 PDF 库和命令行工具,支持 Rust、.NET、Java、Python、JS 与 Go。** +**轻量、快速且原生的 Office 转 PDF 库和命令行工具,支持 .NET。**

NuGet -crates.io -Maven Central -PyPI -npm -Go Reference GitHub stars DOI License @@ -24,6 +19,10 @@

+This repository now maintains **MiniPdf for .NET** only. Rust, Java, Go, +Python, and Node.js have moved to their own [PdfLibrarys repositories](https://github.com/PdfLibrarys). +The implementation links below point to those independent repositories. + MiniPdf 无需在运行时安装 Microsoft Office、LibreOffice、Adobe Acrobat 或使用 COM 自动化,即可将 Office 文档直接转换为 PDF。 ## 选择实现 @@ -31,11 +30,11 @@ MiniPdf 无需在运行时安装 Microsoft Office、LibreOffice、Adobe Acrobat | 实现 | 输入 | 接口 | 成熟度 | 文档 | 视觉结果 | |---|---|---|---|---|---| | .NET | XLSX、DOCX、PPTX | 库、CLI、Native AOT 二进制文件 | 稳定 | **[.NET 指南](README.nuget.md)** | **[XLSX](https://mini-software.github.io/minipdf-web-page/?language=dotnet&suite=classic&format=xlsx)**
**[DOCX](https://mini-software.github.io/minipdf-web-page/?language=dotnet&suite=classic&format=docx)**
**[PPTX](https://mini-software.github.io/minipdf-web-page/?language=dotnet&suite=issue&format=pptx)** | -| Rust | XLSX、DOCX、PPTX | Crate、CLI | 稳定 | **[Rust 指南](../minipdf-rs/README.md)** | **[XLSX](https://mini-software.github.io/minipdf-web-page/?language=rust&suite=classic&format=xlsx)**
**[DOCX](https://mini-software.github.io/minipdf-web-page/?language=rust&suite=classic&format=docx)** | -| Java | XLSX、DOCX、PPTX | 库、CLI | 实验性 | **[Java 源代码](../minipdf-java/)** | **[XLSX](https://mini-software.github.io/minipdf-web-page/?language=java&suite=issue&format=xlsx)**
**[DOCX](https://mini-software.github.io/minipdf-web-page/?language=java&suite=issue&format=docx)** | -| Python | DOCX | 包、CLI | 稳定 | **[Python 指南](../minipdf-python/README.md)** | **[XLSX](https://mini-software.github.io/minipdf-web-page/?language=python&suite=issue&format=xlsx)** | -| Node.js | XLSX、DOCX、PPTX | 原生包 | 稳定 | **[Node.js 指南](../minipdf-node/README.md)** | **[XLSX](https://mini-software.github.io/minipdf-web-page/?language=node&suite=issue&format=xlsx)** | -| Go | XLSX、DOCX、PPTX | 包、CLI | 实验性 | **[Go 指南](../minipdf-go/README.md)** | **[XLSX](https://mini-software.github.io/minipdf-web-page/?language=go&suite=issue&format=xlsx)** | +| Rust | XLSX、DOCX、PPTX | Crate、CLI | 稳定 | **[Rust 指南](https://github.com/PdfLibrarys/minipdf-rs/blob/main/README.md)** | **[XLSX](https://mini-software.github.io/minipdf-web-page/?language=rust&suite=classic&format=xlsx)**
**[DOCX](https://mini-software.github.io/minipdf-web-page/?language=rust&suite=classic&format=docx)** | +| Java | XLSX、DOCX、PPTX | 库、CLI | 实验性 | **[Java 源代码](https://github.com/PdfLibrarys/minipdf-java)** | **[XLSX](https://mini-software.github.io/minipdf-web-page/?language=java&suite=issue&format=xlsx)**
**[DOCX](https://mini-software.github.io/minipdf-web-page/?language=java&suite=issue&format=docx)** | +| Python | DOCX | 包、CLI | 稳定 | **[Python 指南](https://github.com/PdfLibrarys/minipdf-python/blob/main/README.md)** | **[XLSX](https://mini-software.github.io/minipdf-web-page/?language=python&suite=issue&format=xlsx)** | +| Node.js | XLSX、DOCX、PPTX | 原生包 | 稳定 | **[Node.js 指南](https://github.com/PdfLibrarys/minipdf-node/blob/main/README.md)** | **[XLSX](https://mini-software.github.io/minipdf-web-page/?language=node&suite=issue&format=xlsx)** | +| Go | XLSX、DOCX、PPTX | 包、CLI | 实验性 | **[Go 指南](https://github.com/PdfLibrarys/minipdf-go/blob/main/README.md)** | **[XLSX](https://mini-software.github.io/minipdf-web-page/?language=go&suite=issue&format=xlsx)** | ## 快速开始 @@ -60,95 +59,11 @@ minipdf report.docx -o report.pdf 使用方式请查看 [.NET 指南](README.nuget.md) -### Rust - -```bash -cargo add minipdf -cargo install minipdf-cli -``` - -```rust -minipdf::convert_to_pdf("report.docx", "report.pdf")?; -``` - -```bash -minipdf report.docx -o report.pdf -``` - -使用方式请查看 [Rust 指南](../minipdf-rs/README.md) - -### Java - -[Maven Central artifact](https://central.sonatype.com/artifact/io.github.mini-software/minipdf) - -```java -import io.github.minisoftware.minipdf.MiniPdf; -import java.nio.file.Files; -import java.nio.file.Path; - -try { - MiniPdf.registerFont( - "Noto Sans", - Files.readAllBytes(Path.of("fonts/NotoSans-Regular.ttf"))); - MiniPdf.convertToPdf(Path.of("report.docx"), Path.of("report.pdf")); -} finally { - MiniPdf.clearRegisteredFonts(); -} -``` - -使用方式请查看 [Java 指南](../minipdf-java/README.md) - -### Python - -```bash -pip install minipdf -``` - -```python -import minipdf - -minipdf.convert_to_pdf("report.docx", "report.pdf") -``` - -使用方式请查看 [Python 指南](../minipdf-python/README.md) - -### Node.js - -```bash -npm install minipdf -``` - -```javascript -const minipdf = require('minipdf') - -minipdf.convertToPdf('report.docx', 'report.pdf') -``` - -使用方式请查看 [Node.js 指南](../minipdf-node/README.md) - -### Go - -```bash -go get github.com/mini-software/MiniPdf/minipdf-go@latest -``` - -```go -import minipdf "github.com/mini-software/MiniPdf/minipdf-go" - -if err := minipdf.ConvertToPDF("report.docx", "report.pdf"); err != nil { - panic(err) -} -``` - -使用方式请查看 [Go 指南](../minipdf-go/README.md) - ## 为什么选择 MiniPdf - **无需 Office 套件**:转换直接在应用程序或 CLI 内运行。 - **部署精简**:依赖少,无需外部进程。 - **适合服务器与 CI**:可用于容器、云服务和流水线。 -- **多语言选择**:可从 .NET、Rust、Java、Python、Node.js 或 Go 使用 MiniPdf。 -- **原生命令行方案**:适用于 .NET、Rust、Java、Python 与 Go。 MiniPdf 专注于实用文档转换,不追求完全复制 Microsoft Office 版式。复杂模板的渲染可能有所不同,请使用在线演示或基准报告评估代表性文件。 @@ -168,16 +83,16 @@ Run the minipdf-contribution skill. |---|---| | [在线演示](https://mini-software.github.io/MiniPdf/) | 在浏览器中试用转换 | | [.NET 文档](README.nuget.md) | 稳定版库与 CLI 用法 | -| [Rust 文档](../minipdf-rs/README.md) | 实验版 crate 与 CLI 用法 | -| [Java 实现](../minipdf-java/) | 实验性 Maven 库与 CLI 源代码 | -| [Python 文档](../minipdf-python/README.md) | 实验性包与 CLI 用法 | -| [Node.js 文档](../minipdf-node/README.md) | 实验性原生包用法 | -| [Go 文档](../minipdf-go/README.md) | 实验性包与 CLI 用法 | +| [Rust 文档](https://github.com/PdfLibrarys/minipdf-rs/blob/main/README.md) | 实验版 crate 与 CLI 用法 | +| [Java 实现](https://github.com/PdfLibrarys/minipdf-java) | 实验性 Maven 库与 CLI 源代码 | +| [Python 文档](https://github.com/PdfLibrarys/minipdf-python/blob/main/README.md) | 实验性包与 CLI 用法 | +| [Node.js 文档](https://github.com/PdfLibrarys/minipdf-node/blob/main/README.md) | 实验性原生包用法 | +| [Go 文档](https://github.com/PdfLibrarys/minipdf-go/blob/main/README.md) | 实验性包与 CLI 用法 | | [.NET XLSX 基准](https://mini-software.github.io/minipdf-web-page/?language=dotnet&suite=classic&format=xlsx) | 电子表格视觉比较结果 | | [.NET DOCX 基准](https://mini-software.github.io/minipdf-web-page/?language=dotnet&suite=classic&format=docx) | 文档视觉比较结果 | | [Rust XLSX 基准](https://mini-software.github.io/minipdf-web-page/?language=rust&suite=classic&format=xlsx) | Rust 电子表格视觉比较结果 | | [Rust DOCX 基准](https://mini-software.github.io/minipdf-web-page/?language=rust&suite=classic&format=docx) | Rust 文档视觉比较结果 | -| [Rust 基准流程](../scripts/Run-Rust-Benchmark.ps1) | 生成测试覆盖与比较报告 | +| [Rust 基准流程](https://github.com/PdfLibrarys/minipdf-rs) | 生成测试覆盖与比较报告 | | [社区治理](../GOVERNANCE.md) | 决策、角色、投票和维护者选任 | | [路线图](../ROADMAP.md) | 项目范围、实现状态和当前优先事项 | | [安全政策](../SECURITY.md) | 私密漏洞报告和支持版本 | diff --git a/documents/README.zh-TW.md b/documents/README.zh-TW.md index 9f6add46..d98a4244 100644 --- a/documents/README.zh-TW.md +++ b/documents/README.zh-TW.md @@ -1,14 +1,9 @@
-**輕量、快速且原生的 Office 轉 PDF 程式庫與命令列工具,支援 Rust、.NET、Java、Python、JS 與 Go。** +**輕量、快速且原生的 Office 轉 PDF 程式庫與命令列工具,支援 .NET。**

NuGet -crates.io -Maven Central -PyPI -npm -Go Reference GitHub stars DOI License @@ -24,6 +19,10 @@

+This repository now maintains **MiniPdf for .NET** only. Rust, Java, Go, +Python, and Node.js have moved to their own [PdfLibrarys repositories](https://github.com/PdfLibrarys). +The implementation links below point to those independent repositories. + MiniPdf 不需要在執行階段安裝 Microsoft Office、LibreOffice、Adobe Acrobat 或使用 COM 自動化,即可直接將 Office 文件轉換為 PDF。 ## 選擇實作 @@ -31,11 +30,11 @@ MiniPdf 不需要在執行階段安裝 Microsoft Office、LibreOffice、Adobe Ac | 實作 | 輸入 | 介面 | 成熟度 | 文件 | 視覺結果 | |---|---|---|---|---|---| | .NET | XLSX、DOCX、PPTX | 程式庫、CLI、Native AOT 二進位檔 | 穩定 | **[.NET 指南](README.nuget.md)** | **[XLSX](https://mini-software.github.io/minipdf-web-page/?language=dotnet&suite=classic&format=xlsx)**
**[DOCX](https://mini-software.github.io/minipdf-web-page/?language=dotnet&suite=classic&format=docx)**
**[PPTX](https://mini-software.github.io/minipdf-web-page/?language=dotnet&suite=issue&format=pptx)** | -| Rust | XLSX、DOCX、PPTX | Crate、CLI | 穩定 | **[Rust 指南](../minipdf-rs/README.md)** | **[XLSX](https://mini-software.github.io/minipdf-web-page/?language=rust&suite=classic&format=xlsx)**
**[DOCX](https://mini-software.github.io/minipdf-web-page/?language=rust&suite=classic&format=docx)** | -| Java | XLSX、DOCX、PPTX | 程式庫、CLI | 實驗性 | **[Java 原始碼](../minipdf-java/)** | **[XLSX](https://mini-software.github.io/minipdf-web-page/?language=java&suite=issue&format=xlsx)**
**[DOCX](https://mini-software.github.io/minipdf-web-page/?language=java&suite=issue&format=docx)** | -| Python | DOCX | 套件、CLI | 穩定 | **[Python 指南](../minipdf-python/README.md)** | **[XLSX](https://mini-software.github.io/minipdf-web-page/?language=python&suite=issue&format=xlsx)** | -| Node.js | XLSX、DOCX、PPTX | 原生套件 | 穩定 | **[Node.js 指南](../minipdf-node/README.md)** | **[XLSX](https://mini-software.github.io/minipdf-web-page/?language=node&suite=issue&format=xlsx)** | -| Go | XLSX、DOCX、PPTX | 套件、CLI | 實驗性 | **[Go 指南](../minipdf-go/README.md)** | **[XLSX](https://mini-software.github.io/minipdf-web-page/?language=go&suite=issue&format=xlsx)** | +| Rust | XLSX、DOCX、PPTX | Crate、CLI | 穩定 | **[Rust 指南](https://github.com/PdfLibrarys/minipdf-rs/blob/main/README.md)** | **[XLSX](https://mini-software.github.io/minipdf-web-page/?language=rust&suite=classic&format=xlsx)**
**[DOCX](https://mini-software.github.io/minipdf-web-page/?language=rust&suite=classic&format=docx)** | +| Java | XLSX、DOCX、PPTX | 程式庫、CLI | 實驗性 | **[Java 原始碼](https://github.com/PdfLibrarys/minipdf-java)** | **[XLSX](https://mini-software.github.io/minipdf-web-page/?language=java&suite=issue&format=xlsx)**
**[DOCX](https://mini-software.github.io/minipdf-web-page/?language=java&suite=issue&format=docx)** | +| Python | DOCX | 套件、CLI | 穩定 | **[Python 指南](https://github.com/PdfLibrarys/minipdf-python/blob/main/README.md)** | **[XLSX](https://mini-software.github.io/minipdf-web-page/?language=python&suite=issue&format=xlsx)** | +| Node.js | XLSX、DOCX、PPTX | 原生套件 | 穩定 | **[Node.js 指南](https://github.com/PdfLibrarys/minipdf-node/blob/main/README.md)** | **[XLSX](https://mini-software.github.io/minipdf-web-page/?language=node&suite=issue&format=xlsx)** | +| Go | XLSX、DOCX、PPTX | 套件、CLI | 實驗性 | **[Go 指南](https://github.com/PdfLibrarys/minipdf-go/blob/main/README.md)** | **[XLSX](https://mini-software.github.io/minipdf-web-page/?language=go&suite=issue&format=xlsx)** | ## 快速開始 @@ -60,95 +59,11 @@ minipdf report.docx -o report.pdf 使用方式請參閱 [.NET 指南](README.nuget.md)。 -### Rust - -```bash -cargo add minipdf -cargo install minipdf-cli -``` - -```rust -minipdf::convert_to_pdf("report.docx", "report.pdf")?; -``` - -```bash -minipdf report.docx -o report.pdf -``` - -使用方式請參閱 [Rust 指南](../minipdf-rs/README.md)。 - -### Java - -[Maven Central artifact](https://central.sonatype.com/artifact/io.github.mini-software/minipdf) - -```java -import io.github.minisoftware.minipdf.MiniPdf; -import java.nio.file.Files; -import java.nio.file.Path; - -try { - MiniPdf.registerFont( - "Noto Sans", - Files.readAllBytes(Path.of("fonts/NotoSans-Regular.ttf"))); - MiniPdf.convertToPdf(Path.of("report.docx"), Path.of("report.pdf")); -} finally { - MiniPdf.clearRegisteredFonts(); -} -``` - -使用方式請參閱 [Java 指南](../minipdf-java/README.md)。 - -### Python - -```bash -pip install minipdf -``` - -```python -import minipdf - -minipdf.convert_to_pdf("report.docx", "report.pdf") -``` - -使用方式請參閱 [Python 指南](../minipdf-python/README.md)。 - -### Node.js - -```bash -npm install minipdf -``` - -```javascript -const minipdf = require('minipdf') - -minipdf.convertToPdf('report.docx', 'report.pdf') -``` - -使用方式請參閱 [Node.js 指南](../minipdf-node/README.md)。 - -### Go - -```bash -go get github.com/mini-software/MiniPdf/minipdf-go@latest -``` - -```go -import minipdf "github.com/mini-software/MiniPdf/minipdf-go" - -if err := minipdf.ConvertToPDF("report.docx", "report.pdf"); err != nil { - panic(err) -} -``` - -使用方式請參閱 [Go 指南](../minipdf-go/README.md)。 - ## 為什麼選擇 MiniPdf - **不需要 Office 套件**:轉換直接在應用程式或 CLI 內執行。 - **精簡部署**:相依套件少,不需要外部程序。 - **適合伺服器與 CI**:可用於容器、雲端服務與工作流程。 -- **多語言選擇**:可從 .NET、Rust、Java、Python、Node.js 或 Go 使用 MiniPdf。 -- **原生命令列選項**:適用於 .NET、Rust、Java、Python 與 Go。 MiniPdf 專注於實用文件轉換,不追求完整複製 Microsoft Office 版面。複雜範本的呈現可能不同,請使用線上展示或基準報告評估代表性檔案。 @@ -168,16 +83,16 @@ Run the minipdf-contribution skill. |---|---| | [線上展示](https://mini-software.github.io/MiniPdf/) | 在瀏覽器中試用轉換 | | [.NET 文件](README.nuget.md) | 穩定版程式庫與 CLI 用法 | -| [Rust 文件](../minipdf-rs/README.md) | 實驗版 crate 與 CLI 用法 | -| [Java 實作](../minipdf-java/) | 實驗性 Maven 程式庫與 CLI 原始碼 | -| [Python 文件](../minipdf-python/README.md) | 實驗性套件與 CLI 用法 | -| [Node.js 文件](../minipdf-node/README.md) | 實驗性原生套件用法 | -| [Go 文件](../minipdf-go/README.md) | 實驗性套件與 CLI 用法 | +| [Rust 文件](https://github.com/PdfLibrarys/minipdf-rs/blob/main/README.md) | 實驗版 crate 與 CLI 用法 | +| [Java 實作](https://github.com/PdfLibrarys/minipdf-java) | 實驗性 Maven 程式庫與 CLI 原始碼 | +| [Python 文件](https://github.com/PdfLibrarys/minipdf-python/blob/main/README.md) | 實驗性套件與 CLI 用法 | +| [Node.js 文件](https://github.com/PdfLibrarys/minipdf-node/blob/main/README.md) | 實驗性原生套件用法 | +| [Go 文件](https://github.com/PdfLibrarys/minipdf-go/blob/main/README.md) | 實驗性套件與 CLI 用法 | | [.NET XLSX 基準](https://mini-software.github.io/minipdf-web-page/?language=dotnet&suite=classic&format=xlsx) | 試算表視覺比較結果 | | [.NET DOCX 基準](https://mini-software.github.io/minipdf-web-page/?language=dotnet&suite=classic&format=docx) | 文件視覺比較結果 | | [Rust XLSX 基準](https://mini-software.github.io/minipdf-web-page/?language=rust&suite=classic&format=xlsx) | Rust 試算表視覺比較結果 | | [Rust DOCX 基準](https://mini-software.github.io/minipdf-web-page/?language=rust&suite=classic&format=docx) | Rust 文件視覺比較結果 | -| [Rust 基準流程](../scripts/Run-Rust-Benchmark.ps1) | 產生測試涵蓋率與比較報告 | +| [Rust 基準流程](https://github.com/PdfLibrarys/minipdf-rs) | 產生測試涵蓋率與比較報告 | | [社群治理](../GOVERNANCE.md) | 決策、角色、投票與維護者選任 | | [路線圖](../ROADMAP.md) | 專案範圍、實作狀態與目前優先事項 | | [安全政策](../SECURITY.md) | 私密漏洞回報與支援版本 | diff --git a/minipdf-go/LICENSE b/minipdf-go/LICENSE deleted file mode 100644 index 3cd81cec..00000000 --- a/minipdf-go/LICENSE +++ /dev/null @@ -1,200 +0,0 @@ - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship made available under - the License, as indicated by a copyright notice that is included in - or attached to the work (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright 2026 Wei Lin - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. \ No newline at end of file diff --git a/minipdf-go/README.md b/minipdf-go/README.md deleted file mode 100644 index 8b836be6..00000000 --- a/minipdf-go/README.md +++ /dev/null @@ -1,265 +0,0 @@ -# MiniPdf for Go - -The experimental native Go implementation of MiniPdf. It provides a reusable -`minipdf` package and a dependency-free command-line application. - -[Project portal](../README.md) | [Rust implementation](../minipdf-rs/README.md) | -[.NET implementation](../documents/README.nuget.md) - -> The Go implementation is an early foundation and is not feature-equivalent -> with MiniPdf for .NET or Rust. It currently renders basic text from XLSX, -> DOCX, and PPTX packages, and a supported subset of DOCX tables. Complex -> Office layout is not yet supported. - -## Requirements - -- Go 1.22 or later -- No Microsoft Office, LibreOffice, Adobe Acrobat, or .NET runtime at runtime - -## Library - -```go -package main - -import minipdf "github.com/mini-software/MiniPdf/minipdf-go" - -func main() { - if err := minipdf.ConvertToPDF("report.docx", "report.pdf"); err != nil { - panic(err) - } -} -``` - -Convert in-memory Office package bytes: - -```go -pdf, err := minipdf.ConvertBytesToPDF(input) -``` - -Compress PDF page content streams: - -```go -pdf, err := minipdf.ConvertBytesToPDFWithOptions(input, minipdf.ConversionOptions{ - Compress: true, -}) -``` - -Override DOCX page margins in PDF points: - -```go -margins, err := minipdf.NewMargins(36, 48, 36, 48) -if err != nil { - panic(err) -} -pdf, err := minipdf.ConvertBytesToPDFWithOptions(input, minipdf.ConversionOptions{ - Margins: &margins, -}) -``` - -Margin overrides are rejected for XLSX and PPTX input. - -Limit XLSX output or override worksheet orientation: - -```go -landscape := true -pdf, err := minipdf.ConvertBytesToPDFWithOptions(input, minipdf.ConversionOptions{ - MaxRows: 100, - MaxColumns: 12, - Landscape: &landscape, -}) -``` - -Convert between streams: - -```go -err := minipdf.ConvertReaderToWriter(input, output, minipdf.ConversionOptions{}) -``` - -Register a TrueType font before conversion when built-in PDF fonts do not cover -the document text: - -```go -fontData, err := os.ReadFile("fonts/NotoSans-Regular.ttf") -if err != nil { - panic(err) -} -minipdf.RegisterFont("Noto Sans", fontData) -defer minipdf.ClearRegisteredFonts() -``` - -Registered `.ttf` fonts are embedded as Type0/CID fonts with ToUnicode maps. -The structured DOCX table renderer also accepts registered TrueType collections -(the first face), and resolves selected installed Windows fonts, including -SimSun/SimHei and their Chinese family names. Collections are rebuilt as standalone -sfnt fonts before PDF embedding. Font subsetting and complex-script shaping are -not yet implemented. Font binaries are not distributed with MiniPdf. - -Override the output page size: - -```go -size, err := minipdf.NewPageSize(400, 500) -if err != nil { - panic(err) -} -pdf, err := minipdf.ConvertBytesToPDFWithOptions(input, minipdf.ConversionOptions{ - PageSize: &size, -}) -``` - -## Command Line - -```powershell -go install github.com/mini-software/MiniPdf/minipdf-go/cmd/minipdf@latest -minipdf report.docx -minipdf data.xlsx -o data.pdf -minipdf slides.pptx --paper-size a4 -minipdf convert report.docx --page-width 400 --page-height 500 -minipdf report.docx --fonts ./fonts -minipdf report.docx --compress -minipdf data.xlsx --max-rows 100 --max-columns 12 --landscape -``` - -## Current Scope - -| Capability | Go status | -|---|---| -| XLSX to PDF | Basic cell text and shared strings | -| DOCX to PDF | Basic text; supported table documents also preserve grid widths, horizontal/vertical merges, borders, fills, run fonts, highlights, paragraph spacing/alignment, and PNG/JPEG drawings | -| PPTX to PDF | Basic slide text | -| PDF output | Dependency-free PDF 1.4 writer | -| Page size | Office geometry, A4/Letter presets, or custom points | -| Fonts | Embedded registered TTF fonts with ToUnicode; printed XLSX grids can use installed Windows Calibri/Arial variants | -| Input safety | Bounded ZIP entry count, size, expansion ratio, encryption, and path validation | -| Interfaces | Go package with file, byte, and stream APIs; native CLI | - -Single-page DOCX documents with non-nested, non-floating table grids can use the -structured renderer. It resolves paragraph/style inheritance and theme fonts, uses glyph -metrics for wrapping, respects East Asian punctuation boundaries, and honors -Word's FE-layout CJK metric compatibility flag. Images use their package -relationships and DrawingML extents; simple VML text-box images use their margin -offsets and text-box insets. Image decoding is limited to 25 million pixels. -Missing or invalid embedded images produce errors rather than disappearing. - -Documents requiring unsupported section changes, numbering, anchored drawings, -text-bearing VML text boxes, omitted row grid columns (`gridBefore`/`gridAfter`), -exact-height rows, multi-page structured layout, or referenced EMF/WMF images -retain the existing text converter. If measured paragraph, inline-image, or -table flow would cross the first page's content boundary, the entire document -uses the text converter; structured pagination, keep rules, and row splitting -are not implemented. Tables extending beyond the physical page width also retain -text conversion. Metafile formats are checked before -structured rendering; malformed PNG/JPEG images still produce decoding errors. -Linked-only images and inline paragraphs mixing images with text, multiple images, -or explicit line breaks also retain text conversion. Single image-only paragraphs -honor alignment, indentation, and paragraph spacing. Line-grid snapping requires -`docGrid` type `lines` or `linesAndChars`; an omitted/default type does not snap. -Dashed borders use a single native PDF stroke, without retained segment expansion. -Images inside table cells, complex drawing geometry, conditional -table styles, headers/footers, and complex-script shaping remain unsupported. -Structured text uses matching registered fonts or selected licensed Windows -fonts, with Arial/SimSun glyph fallback when available. Requested bold/italic is -synthesized only when the loaded face lacks that emphasis. An unavailable host -font required for Unicode text retains legacy conversion; a present font with -missing glyphs still produces an explicit error on the structured path. Fonts are embedded without -subsetting, so large CJK fonts can substantially increase PDF size. - -XLSX text output skips entirely empty pages within worksheets containing text, -including empty horizontal column groups and pages from trailing formatted rows. -Blank rows within nonempty pages retain their spacing. Layout-only worksheets -keep their existing blank-page behavior. - -Worksheets with an explicit `_xlnm.Print_Area` use the grid renderer instead of -fixed-width text column groups. This path respects rectangular or whole-row/ -column print ranges, repeated print-title rows and columns, hidden rows and -columns, percentage scaling, fit-to-page mode, manual page breaks, and horizontal/ -vertical print centering. It keeps -formatted empty cells inside the print area, so printable template tables are -not discarded merely because they have no text. Sheets without a print area -retain their previous rendering path. - -Grid styles resolve RGB and workbook theme colors, including HSL luminance -tints, for fonts and solid fills. Printed grids also apply conditional solid -fills for text rules, `ISNUMBER(SEARCH(...))` expressions, and numeric `cellIs` -comparisons. Text searches are case-insensitive and support Excel wildcards; -sheet-local cell references respect relative/absolute addressing. Rule priority -and `stopIfTrue` are honored. - -Printed grids use matching registered font families/variants, or installed -Windows Calibri/Arial regular, bold, italic, and bold-italic TTF files when -available. Actual glyph advance widths and font ascent/descent are used for -alignment and shrink-to-fit. Missing/unrecognized font families keep the -built-in PDF font fallback; non-print-area worksheets retain their previous -font-rendering path. Register variant names such as `Calibri Bold Italic` for -portable source-font matching. Fonts are embedded without subsetting; no font -binaries are distributed with MiniPdf. - -Printed numeric cells support common fixed-decimal, grouped, percentage, General, -and day/month/year date formats, including custom escaped/quoted date literals. -The workbook's 1900/1904 date system is respected. Unsupported number-format -patterns keep the stored value. - -One-/two-cell anchored PNG/JPEG/GIF pictures support source cropping, print -scaling, and repetition inside print-title bands. Images are limited to -25 million pixels and transparency is composited onto white. Negative crops, -external image targets, and general vector drawings are not supported. - -Printed footers support left/center/right sections, font names/sizes, -bold/italic toggles, escaped ampersands, sheet names, and final document page -number/count fields. First/even/odd footer variants and `scaleWithDoc` are -respected. Footer placement currently uses worksheet page margins; separate -`alignWithMargins="0"` geometry and header content are not implemented. -Double cell borders retain their two separate strokes. - -Invalid or unsupported print-range expressions and invalid numeric print -settings return an explicit conversion error, as do invalid theme colors, -tints, conditional range/format metadata, corrupt pictures/fonts, and unsupported -footer control codes. Conditional rules outside the -supported subset retain base styling. Dynamic print-area formulas, general -conditional formulas, conditional font/border changes, table styles, indexed -colors, patterned/gradient fills, general drawings, complex text shaping, and -full Office font/layout fidelity are not supported. - -## Development - -```powershell -cd minipdf-go -go fmt ./... -go vet ./... -go test ./... -go run ./cmd/minipdf path\to\input.docx -``` - -## Publishing - -Go modules are published from Git tags rather than uploaded to a package -registry. Because this module is in the `minipdf-go` repository subdirectory, -its tags must include that prefix. - -After the release change has been merged to `main`, create and push a semantic -version tag from the release commit: - -```powershell -git tag minipdf-go/v -git push origin minipdf-go/v -``` - -The [Go Release workflow](../.github/workflows/go-release.yml) validates the -module, builds Windows, Linux, and macOS CLI archives for AMD64 and ARM64, -writes SHA-256 checksums, and creates the GitHub Release. No package registry -token is required. The public Go module proxy discovers the library from the -same tag. - -Verify the published module: - -```powershell -go list -m github.com/mini-software/MiniPdf/minipdf-go@v -go install github.com/mini-software/MiniPdf/minipdf-go/cmd/minipdf@v -minipdf --version -``` - -The workflow can also be run manually for an existing tag. It intentionally -does not create tags, so a manual run cannot publish an untagged Go module. - -## License - -[Apache License 2.0](../LICENSE). \ No newline at end of file diff --git a/minipdf-go/cmd/minipdf/main.go b/minipdf-go/cmd/minipdf/main.go deleted file mode 100644 index 18afc39e..00000000 --- a/minipdf-go/cmd/minipdf/main.go +++ /dev/null @@ -1,240 +0,0 @@ -package main - -import ( - "errors" - "fmt" - "os" - "path/filepath" - "strconv" - "strings" - - minipdf "github.com/mini-software/MiniPdf/minipdf-go" -) - -var ( - errHelp = errors.New("help requested") - errVersion = errors.New("version requested") - version = "dev" -) - -type cliOptions struct { - input string - output string - fontDirectory string - compress bool - maxRows int - maxColumns int - landscape *bool - paperSize string - pageWidth float64 - pageHeight float64 -} - -func main() { - options, err := parseArguments(os.Args[1:]) - if errors.Is(err, errHelp) { - printUsage() - return - } - if errors.Is(err, errVersion) { - fmt.Println("minipdf", version) - return - } - if err != nil { - fmt.Fprintln(os.Stderr, "Error:", err) - os.Exit(1) - } - if err := run(options); err != nil { - fmt.Fprintln(os.Stderr, "Error:", err) - os.Exit(1) - } -} - -func run(options cliOptions) error { - if _, err := os.Stat(options.input); err != nil { - return fmt.Errorf("input file: %w", err) - } - extension := strings.ToLower(filepath.Ext(options.input)) - if extension != ".docx" && extension != ".xlsx" && extension != ".pptx" { - return fmt.Errorf("unsupported file type %q; supported: .xlsx, .docx, .pptx", extension) - } - - conversionOptions, err := conversionOptions(options) - if err != nil { - return err - } - if err := registerFontsFromDirectory(options.fontDirectory); err != nil { - return err - } - output := options.output - if output == "" { - output = strings.TrimSuffix(options.input, filepath.Ext(options.input)) + ".pdf" - } - if err := minipdf.ConvertToPDFWithOptions(options.input, output, conversionOptions); err != nil { - return err - } - fmt.Println(output) - return nil -} - -func registerFontsFromDirectory(directory string) error { - if directory == "" { - return nil - } - entries, err := os.ReadDir(directory) - if err != nil { - return fmt.Errorf("read font directory %q: %w", directory, err) - } - for _, entry := range entries { - if entry.IsDir() || !strings.EqualFold(filepath.Ext(entry.Name()), ".ttf") { - continue - } - fontPath := filepath.Join(directory, entry.Name()) - fontData, err := os.ReadFile(fontPath) - if err != nil { - return fmt.Errorf("read font %q: %w", fontPath, err) - } - name := strings.TrimSuffix(entry.Name(), filepath.Ext(entry.Name())) - minipdf.RegisterFont(name, fontData) - } - return nil -} - -func conversionOptions(options cliOptions) (minipdf.ConversionOptions, error) { - customPageSize := options.pageWidth != 0 || options.pageHeight != 0 - if options.paperSize != "" && customPageSize { - return minipdf.ConversionOptions{}, errors.New("use either --paper-size or --page-width/--page-height, not both") - } - if (options.pageWidth == 0) != (options.pageHeight == 0) { - return minipdf.ConversionOptions{}, errors.New("--page-width and --page-height must be specified together") - } - var pageSize *minipdf.PageSize - switch strings.ToLower(options.paperSize) { - case "": - case "a4": - size := minipdf.PageSizeA4 - pageSize = &size - case "letter": - size := minipdf.PageSizeLetter - pageSize = &size - default: - return minipdf.ConversionOptions{}, fmt.Errorf("unknown paper size %q; supported: a4, letter", options.paperSize) - } - if customPageSize { - size, err := minipdf.NewPageSize(options.pageWidth, options.pageHeight) - if err != nil { - return minipdf.ConversionOptions{}, err - } - pageSize = &size - } - return minipdf.ConversionOptions{ - PageSize: pageSize, Compress: options.compress, - MaxRows: options.maxRows, MaxColumns: options.maxColumns, Landscape: options.landscape, - }, nil -} - -func parseArguments(arguments []string) (cliOptions, error) { - if len(arguments) > 0 && arguments[0] == "convert" { - arguments = arguments[1:] - } - var options cliOptions - for index := 0; index < len(arguments); index++ { - argument := arguments[index] - if argument == "-h" || argument == "--help" { - return cliOptions{}, errHelp - } - if argument == "--version" { - return cliOptions{}, errVersion - } - if argument == "--compress" { - options.compress = true - continue - } - if argument == "--landscape" || argument == "--portrait" { - landscape := argument == "--landscape" - if options.landscape != nil && *options.landscape != landscape { - return cliOptions{}, errors.New("use either --landscape or --portrait, not both") - } - options.landscape = &landscape - continue - } - name, inlineValue, hasInlineValue := strings.Cut(argument, "=") - switch name { - case "-o", "--output", "--fonts", "--paper-size", "--page-width", "--page-height", "--max-rows", "--max-columns": - value := inlineValue - if !hasInlineValue { - index++ - if index >= len(arguments) { - return cliOptions{}, fmt.Errorf("%s requires a value", name) - } - value = arguments[index] - } - switch name { - case "-o", "--output": - options.output = value - case "--fonts": - options.fontDirectory = value - case "--paper-size": - options.paperSize = value - case "--page-width": - width, err := strconv.ParseFloat(value, 64) - if err != nil { - return cliOptions{}, fmt.Errorf("invalid page width %q", value) - } - options.pageWidth = width - case "--page-height": - height, err := strconv.ParseFloat(value, 64) - if err != nil { - return cliOptions{}, fmt.Errorf("invalid page height %q", value) - } - options.pageHeight = height - case "--max-rows": - maximum, err := strconv.Atoi(value) - if err != nil || maximum <= 0 { - return cliOptions{}, fmt.Errorf("invalid maximum row count %q", value) - } - options.maxRows = maximum - case "--max-columns": - maximum, err := strconv.Atoi(value) - if err != nil || maximum <= 0 { - return cliOptions{}, fmt.Errorf("invalid maximum column count %q", value) - } - options.maxColumns = maximum - } - default: - if strings.HasPrefix(argument, "-") { - return cliOptions{}, fmt.Errorf("unknown option %q", argument) - } - if options.input != "" { - return cliOptions{}, errors.New("only one input file can be converted at a time") - } - options.input = argument - } - } - if options.input == "" { - return cliOptions{}, errors.New("input file is required; use --help for usage") - } - return options, nil -} - -func printUsage() { - fmt.Println(`MiniPdf for Go - -Usage: - minipdf INPUT [options] - minipdf convert INPUT [options] - -Options: - -o, --output PATH Output PDF path - --fonts DIR Register .ttf fonts from a directory - --compress Compress PDF page content streams - --max-rows COUNT Maximum XLSX rows to render - --max-columns COUNT Maximum XLSX columns to render - --landscape Render XLSX pages in landscape - --portrait Render XLSX pages in portrait - --paper-size SIZE a4 or letter - --page-width POINTS Custom page width - --page-height POINTS Custom page height - --version Show the build version - -h, --help Show this help`) -} diff --git a/minipdf-go/cmd/minipdf/main_test.go b/minipdf-go/cmd/minipdf/main_test.go deleted file mode 100644 index 138d37ff..00000000 --- a/minipdf-go/cmd/minipdf/main_test.go +++ /dev/null @@ -1,96 +0,0 @@ -package main - -import ( - "bytes" - "errors" - "os" - "path/filepath" - "testing" - - minipdf "github.com/mini-software/MiniPdf/minipdf-go" -) - -func TestParseArgumentsAcceptsVersionWithoutInput(t *testing.T) { - _, err := parseArguments([]string{"--version"}) - if !errors.Is(err, errVersion) { - t.Fatalf("parseArguments() error = %v, want errVersion", err) - } -} - -func TestConversionOptionsRejectsMixedPageSizes(t *testing.T) { - _, err := conversionOptions(cliOptions{paperSize: "a4", pageWidth: 300, pageHeight: 400}) - if err == nil { - t.Fatal("conversionOptions() accepted preset and custom page sizes") - } -} - -func TestParseArgumentsAcceptsFontDirectory(t *testing.T) { - options, err := parseArguments([]string{"report.docx", "--fonts", "fonts"}) - if err != nil { - t.Fatal(err) - } - if options.fontDirectory != "fonts" { - t.Fatalf("fontDirectory = %q, want %q", options.fontDirectory, "fonts") - } -} - -func TestParseArgumentsAcceptsCompression(t *testing.T) { - options, err := parseArguments([]string{"report.docx", "--compress"}) - if err != nil { - t.Fatal(err) - } - if !options.compress { - t.Fatal("compress = false, want true") - } - conversion, err := conversionOptions(options) - if err != nil { - t.Fatal(err) - } - if !conversion.Compress { - t.Fatal("ConversionOptions.Compress = false, want true") - } -} - -func TestParseArgumentsAcceptsXLSXControls(t *testing.T) { - options, err := parseArguments([]string{ - "report.xlsx", "--max-rows", "10", "--max-columns", "4", "--landscape", - }) - if err != nil { - t.Fatal(err) - } - conversion, err := conversionOptions(options) - if err != nil { - t.Fatal(err) - } - if conversion.MaxRows != 10 || conversion.MaxColumns != 4 || conversion.Landscape == nil || !*conversion.Landscape { - t.Fatalf("conversion options = %#v", conversion) - } -} - -func TestParseArgumentsRejectsConflictingOrientation(t *testing.T) { - _, err := parseArguments([]string{"report.xlsx", "--landscape", "--portrait"}) - if err == nil { - t.Fatal("parseArguments() accepted conflicting orientation flags") - } -} - -func TestRegisterFontsFromDirectory(t *testing.T) { - minipdf.ClearRegisteredFonts() - t.Cleanup(minipdf.ClearRegisteredFonts) - directory := t.TempDir() - fontData := []byte("test font") - if err := os.WriteFile(filepath.Join(directory, "Example.TTF"), fontData, 0o600); err != nil { - t.Fatal(err) - } - if err := os.WriteFile(filepath.Join(directory, "ignored.txt"), []byte("ignored"), 0o600); err != nil { - t.Fatal(err) - } - - if err := registerFontsFromDirectory(directory); err != nil { - t.Fatal(err) - } - fonts := minipdf.RegisteredFonts() - if len(fonts) != 1 || fonts[0].Name != "Example" || !bytes.Equal(fonts[0].Data, fontData) { - t.Fatalf("registered fonts = %#v", fonts) - } -} diff --git a/minipdf-go/docx.go b/minipdf-go/docx.go deleted file mode 100644 index 9e859415..00000000 --- a/minipdf-go/docx.go +++ /dev/null @@ -1,131 +0,0 @@ -package minipdf - -import ( - "bytes" - "encoding/xml" - "fmt" - "strconv" - "strings" -) - -func convertDOCX(input []byte, options ConversionOptions) ([]byte, error) { - files, err := openOfficePackage(input) - if err != nil { - return nil, err - } - documentXML, err := files.read("word/document.xml") - if err != nil { - return nil, err - } - pages, pageSize, margins, err := extractDOCX(documentXML) - if err != nil { - return nil, fmt.Errorf("parse word/document.xml: %w", err) - } - effectivePageSize := pageSize - if options.PageSize != nil { - effectivePageSize = *options.PageSize - } - effectiveMargins := margins - if options.Margins != nil { - effectiveMargins = *options.Margins - } - if err := validateDOCXLayout(effectivePageSize, effectiveMargins); err != nil { - return nil, err - } - if rendered, supported, err := renderDOCXTables(files, documentXML, effectivePageSize, effectiveMargins, options); supported || err != nil { - return rendered, err - } - textPages := make([]textPage, len(pages)) - for index, lines := range pages { - textPages[index] = textPage{lines: lines, size: pageSize, margins: margins} - } - return renderTextPages(textPages, options), nil -} - -func validateDOCXLayout(pageSize PageSize, margins Margins) error { - if _, err := NewPageSize(pageSize.Width, pageSize.Height); err != nil { - return err - } - if _, err := NewMargins(margins.Left, margins.Top, margins.Right, margins.Bottom); err != nil { - return err - } - if margins.Left+margins.Right >= pageSize.Width || margins.Top+margins.Bottom >= pageSize.Height { - return fmt.Errorf("%w: margins must leave positive page content dimensions", ErrInvalidInput) - } - return nil -} - -func extractDOCX(data []byte) ([][]string, PageSize, Margins, error) { - decoder := xml.NewDecoder(bytes.NewReader(data)) - pageSize := PageSizeA4 - margins := Margins{Left: 54, Top: 54, Right: 54, Bottom: 54} - pages := [][]string{{}} - var paragraph strings.Builder - paragraphDepth := 0 - - for { - token, err := decoder.Token() - if err != nil { - if err.Error() == "EOF" { - break - } - return nil, PageSize{}, Margins{}, err - } - switch element := token.(type) { - case xml.StartElement: - switch element.Name.Local { - case "p": - paragraphDepth++ - case "t": - var text string - if err := decoder.DecodeElement(&text, &element); err != nil { - return nil, PageSize{}, Margins{}, err - } - paragraph.WriteString(text) - case "tab": - paragraph.WriteByte('\t') - case "br": - if attrValue(element, "type") == "page" { - appendDOCXParagraph(&pages[len(pages)-1], paragraph.String()) - paragraph.Reset() - pages = append(pages, []string{}) - } else { - paragraph.WriteByte('\n') - } - case "pgSz": - width, widthErr := strconv.ParseFloat(attrValue(element, "w"), 64) - height, heightErr := strconv.ParseFloat(attrValue(element, "h"), 64) - if widthErr == nil && heightErr == nil && width > 0 && height > 0 { - pageSize = PageSize{Width: width / 20, Height: height / 20} - } - case "pgMar": - left, leftErr := strconv.ParseFloat(attrValue(element, "left"), 64) - top, topErr := strconv.ParseFloat(attrValue(element, "top"), 64) - right, rightErr := strconv.ParseFloat(attrValue(element, "right"), 64) - bottom, bottomErr := strconv.ParseFloat(attrValue(element, "bottom"), 64) - if leftErr == nil && topErr == nil && rightErr == nil && bottomErr == nil && left >= 0 && top >= 0 && right >= 0 && bottom >= 0 { - margins = Margins{Left: left / 20, Top: top / 20, Right: right / 20, Bottom: bottom / 20} - } - } - case xml.EndElement: - if element.Name.Local == "p" && paragraphDepth > 0 { - paragraphDepth-- - if paragraphDepth == 0 { - appendDOCXParagraph(&pages[len(pages)-1], paragraph.String()) - paragraph.Reset() - } - } - } - } - if paragraph.Len() > 0 { - appendDOCXParagraph(&pages[len(pages)-1], paragraph.String()) - } - if len(pages) == 1 && len(pages[0]) == 0 { - pages[0] = append(pages[0], "Empty DOCX document") - } - return pages, pageSize, margins, nil -} - -func appendDOCXParagraph(lines *[]string, paragraph string) { - *lines = append(*lines, strings.Split(paragraph, "\n")...) -} diff --git a/minipdf-go/docx_font.go b/minipdf-go/docx_font.go deleted file mode 100644 index 40ce4420..00000000 --- a/minipdf-go/docx_font.go +++ /dev/null @@ -1,214 +0,0 @@ -package minipdf - -import ( - "encoding/binary" - "fmt" - "os" - "path/filepath" - "runtime" - "strings" - - "golang.org/x/image/font" - "golang.org/x/image/font/sfnt" - "golang.org/x/image/math/fixed" -) - -// A PDF FontFile2 contains a single sfnt, not the enclosing TTC. Rebuild its -// directory because offsets inside a collection are relative to the TTC file. -func docxCollectionFont(data []byte, index int) ([]byte, error) { - if len(data) < 12 || string(data[:4]) != "ttcf" { - if index == 0 { - return data, nil - } - return nil, fmt.Errorf("font is not a collection") - } - count := int(binary.BigEndian.Uint32(data[8:12])) - if index < 0 || index >= count || count > (len(data)-12)/4 { - return nil, fmt.Errorf("invalid font collection directory") - } - offset := int(binary.BigEndian.Uint32(data[12+index*4 : 16+index*4])) - if offset < 0 || offset > len(data)-12 { - return nil, fmt.Errorf("invalid font collection offset") - } - n := int(binary.BigEndian.Uint16(data[offset+4 : offset+6])) - if n > (len(data)-offset-12)/16 { - return nil, fmt.Errorf("invalid sfnt directory") - } - out := append([]byte(nil), data[offset:offset+12+n*16]...) - for i := 0; i < n; i++ { - record := out[12+i*16 : 28+i*16] - start := int(binary.BigEndian.Uint32(record[8:12])) - length := int(binary.BigEndian.Uint32(record[12:16])) - if start < 0 || length < 0 || start > len(data) || length > len(data)-start { - return nil, fmt.Errorf("invalid sfnt table bounds") - } - binary.BigEndian.PutUint32(record[8:12], uint32(len(out))) - out = append(out, data[start:start+length]...) - for len(out)%4 != 0 { - out = append(out, 0) - } - } - // checkSumAdjustment is defined for the standalone font, not its collection. - for i := 0; i < n; i++ { - r := out[12+i*16 : 28+i*16] - if string(r[:4]) == "head" { - o := int(binary.BigEndian.Uint32(r[8:12])) - if int(binary.BigEndian.Uint32(r[12:16])) < 12 { - return nil, fmt.Errorf("invalid head table") - } - binary.BigEndian.PutUint32(out[o+8:o+12], 0) - var sum uint32 - for j := 0; j < len(out); j += 4 { - sum += binary.BigEndian.Uint32(out[j : j+4]) - } - binary.BigEndian.PutUint32(out[o+8:o+12], 0xB1B0AFBA-sum) - } - } - return out, nil -} - -func loadDOCXFont(name string, bold, italic bool) (*embeddedFont, error) { - variant := name - if bold { - variant += " Bold" - } - if italic { - variant += " Italic" - } - var data []byte - for _, registered := range RegisteredFonts() { - if strings.EqualFold(registered.Name, variant) { - data = registered.Data - break - } - } - if data == nil && (bold || italic) { - for _, registered := range RegisteredFonts() { - if strings.EqualFold(registered.Name, name) { - data = registered.Data - break - } - } - } - if data == nil && runtime.GOOS == "windows" { - var file string - switch strings.ToLower(name) { - case "宋体", "simsun": - file = "simsun.ttc" - case "黑体", "simhei": - file = "simhei.ttf" - case "楷体", "kaiti": - file = "simkai.ttf" - case "仿宋", "fangsong": - file = "simfang.ttf" - case "times new roman": - file = "times.ttf" - if bold { - file = "timesbd.ttf" - } - if italic { - file = "timesi.ttf" - if bold { - file = "timesbi.ttf" - } - } - default: - f, err := readXLSXFont(name, bold, italic) - if err == nil && f == nil && (bold || italic) { - f, err = readXLSXFont(name, false, false) - } - if f != nil { - f.nativeBold, f.nativeItalic = docxFontEmphasis(f.data) - } - return f, err - } - if root := os.Getenv("WINDIR"); root != "" { - var err error - data, err = os.ReadFile(filepath.Join(root, "Fonts", file)) - if os.IsNotExist(err) { - return nil, nil - } - if err != nil { - return nil, err - } - } - } - if data == nil { - return nil, nil - } - data, err := docxCollectionFont(data, 0) - if err != nil { - return nil, fmt.Errorf("DOCX font %q: %w", name, err) - } - parsed, err := sfnt.Parse(data) - if err != nil { - return nil, fmt.Errorf("DOCX font %q: %w", name, err) - } - if postscript, err := parsed.Name(nil, sfnt.NameIDPostScript); err == nil && postscript != "" { - variant = postscript - } - ppem := fixed.Int26_6(parsed.UnitsPerEm()) - metrics, err := parsed.Metrics(nil, ppem, font.HintingNone) - if err != nil { - return nil, err - } - result := &embeddedFont{name: sanitizePDFFontName(variant), data: data, font: parsed, runeToGlyph: make(map[rune]sfnt.GlyphIndex), glyphToRune: make(map[sfnt.GlyphIndex]rune), advances: make([]float64, parsed.NumGlyphs()), ascent: float64(metrics.Ascent) / float64(ppem), descent: float64(metrics.Descent) / float64(ppem)} - result.nativeBold, result.nativeItalic = docxFontEmphasis(data) - for i := range result.advances { - a, err := parsed.GlyphAdvance(nil, sfnt.GlyphIndex(i), ppem, font.HintingNone) - if err != nil { - return nil, err - } - result.advances[i] = float64(a) / float64(ppem) - } - return result, nil -} - -func docxFontEmphasis(data []byte) (bold, italic bool) { - if len(data) < 12 { - return - } - n := int(binary.BigEndian.Uint16(data[4:6])) - if n > (len(data)-12)/16 { - return - } - for i := 0; i < n; i++ { - r := data[12+i*16 : 28+i*16] - o, length := int(binary.BigEndian.Uint32(r[8:12])), int(binary.BigEndian.Uint32(r[12:16])) - if o < 0 || length < 0 || o > len(data)-length { - continue - } - if string(r[:4]) == "OS/2" && length >= 64 { - flags := binary.BigEndian.Uint16(data[o+62 : o+64]) - return flags&(1<<5) != 0, flags&1 != 0 - } - if string(r[:4]) == "head" && length >= 46 { - flags := binary.BigEndian.Uint16(data[o+44 : o+46]) - bold, italic = flags&1 != 0, flags&2 != 0 - } - } - return -} - -func docxFontCJK(data []byte) bool { - if len(data) < 12 { - return false - } - n := int(binary.BigEndian.Uint16(data[4:6])) - if n > (len(data)-12)/16 { - return false - } - for i := 0; i < n; i++ { - r := data[12+i*16 : 28+i*16] - if string(r[:4]) != "OS/2" { - continue - } - o := int(binary.BigEndian.Uint32(r[8:12])) - length := int(binary.BigEndian.Uint32(r[12:16])) - if length < 86 || o < 0 || o > len(data)-length { - return false - } - return binary.BigEndian.Uint32(data[o+78:o+82])&(0xf<<17) != 0 - } - return false -} diff --git a/minipdf-go/docx_render.go b/minipdf-go/docx_render.go deleted file mode 100644 index b08241be..00000000 --- a/minipdf-go/docx_render.go +++ /dev/null @@ -1,1227 +0,0 @@ -package minipdf - -import ( - "bytes" - "encoding/xml" - "errors" - "fmt" - "image" - _ "image/jpeg" - _ "image/png" - "io" - "math" - "path" - "strconv" - "strings" - "unicode" -) - -var errDOCXFontUnavailable = errors.New("DOCX font unavailable") -var errDOCXTableLayoutUnsupported = errors.New("DOCX table layout unsupported") - -type docxNode struct { - name string - attrs map[string]string - children []*docxNode - text string -} - -func parseDOCXNode(data []byte) (*docxNode, error) { - root := &docxNode{} - stack := []*docxNode{root} - dec := xml.NewDecoder(bytes.NewReader(data)) - for { - token, err := dec.Token() - if err == io.EOF { - break - } - if err != nil { - return nil, err - } - switch t := token.(type) { - case xml.StartElement: - n := &docxNode{name: t.Name.Local, attrs: map[string]string{}} - for _, a := range t.Attr { - n.attrs[a.Name.Local] = a.Value - } - p := stack[len(stack)-1] - p.children = append(p.children, n) - stack = append(stack, n) - case xml.EndElement: - stack = stack[:len(stack)-1] - case xml.CharData: - stack[len(stack)-1].text += string(t) - } - } - if len(root.children) == 0 { - return nil, fmt.Errorf("empty DOCX XML") - } - return root.children[0], nil -} -func (n *docxNode) child(name string) *docxNode { - if n != nil { - for _, c := range n.children { - if c.name == name { - return c - } - } - } - return nil -} -func (n *docxNode) attr(key string) string { - if n == nil { - return "" - } - return n.attrs[key] -} -func (n *docxNode) value(name string) string { return n.child(name).attr("val") } -func (n *docxNode) descendants(name string) []*docxNode { - var out []*docxNode - if n != nil { - for _, c := range n.children { - if c.name == name { - out = append(out, c) - } - out = append(out, c.descendants(name)...) - } - } - return out -} -func docxNumber(s string) float64 { - v, _ := strconv.ParseFloat(s, 64) - if math.IsNaN(v) || math.IsInf(v, 0) { - return 0 - } - return v -} -func docxOn(n *docxNode) bool { - return n != nil && n.attr("val") != "0" && n.attr("val") != "false" && n.attr("val") != "off" -} - -type docxRunStyle struct { - size float64 - fonts map[string]string - bold, italic bool - color PDFColor - highlight *PDFColor - lang string -} -type docxParagraphStyle struct { - run docxRunStyle - before, after, line float64 - lineRule, align string - left, right, first float64 - snap bool -} -type docxStyles struct { - nodes map[string]*docxNode - defaults docxParagraphStyle - theme map[string]string - fonts map[string]*embeddedFont - cjkMetrics bool -} - -func (s *docxStyles) applyRun(style docxRunStyle, n *docxNode) docxRunStyle { - f := map[string]string{} - for k, v := range style.fonts { - f[k] = v - } - style.fonts = f - if n == nil { - return style - } - if sz := n.child("sz"); sz != nil && docxNumber(sz.attr("val")) > 0 { - style.size = docxNumber(sz.attr("val")) / 2 - } - if fonts := n.child("rFonts"); fonts != nil { - for _, key := range []string{"ascii", "hAnsi", "eastAsia", "cs"} { - if v := fonts.attr(key); v != "" { - style.fonts[key] = v - delete(style.fonts, key+"Theme") - } - if v := fonts.attr(key + "Theme"); v != "" { - style.fonts[key+"Theme"] = v - delete(style.fonts, key) - } - } - } - if n.child("b") != nil { - style.bold = docxOn(n.child("b")) - } - if n.child("i") != nil { - style.italic = docxOn(n.child("i")) - } - if lang := n.child("lang").attr("eastAsia"); lang != "" { - style.lang = lang - } - if c := n.child("color"); c != nil { - style.color = docxColor(c.attr("val")) - } - if h := n.child("highlight"); h != nil { - style.highlight = nil - colors := map[string]string{"yellow": "FFFF00", "green": "00FF00", "cyan": "00FFFF", "magenta": "FF00FF", "blue": "0000FF", "red": "FF0000", "darkYellow": "808000"} - if v, ok := colors[h.attr("val")]; ok { - c := docxColor(v) - style.highlight = &c - } - } - return style -} -func (s *docxStyles) applyParagraph(style docxParagraphStyle, n *docxNode) docxParagraphStyle { - if n == nil { - return style - } - style.run = s.applyRun(style.run, n.child("rPr")) - if p := n.child("spacing"); p != nil { - for _, item := range []struct { - key string - out *float64 - }{{"before", &style.before}, {"after", &style.after}, {"line", &style.line}} { - if v, ok := p.attrs[item.key]; ok { - *item.out = docxNumber(v) / 20 - } - } - if p.attr("lineRule") != "" { - style.lineRule = p.attr("lineRule") - } - } - if p := n.child("jc"); p != nil { - style.align = p.attr("val") - } - if p := n.child("ind"); p != nil { - for _, item := range []struct { - key string - out *float64 - }{{"left", &style.left}, {"right", &style.right}, {"firstLine", &style.first}} { - if v, ok := p.attrs[item.key]; ok { - *item.out = docxNumber(v) / 20 - } - } - if v, ok := p.attrs["hanging"]; ok { - style.first = -docxNumber(v) / 20 - } - } - if p := n.child("snapToGrid"); p != nil { - style.snap = docxOn(p) - } - return style -} -func (s *docxStyles) inherit(style docxParagraphStyle, id string, seen map[string]bool) docxParagraphStyle { - if seen[id] { - return style - } - seen[id] = true - n := s.nodes[id] - if n == nil { - return style - } - style = s.inherit(style, n.value("basedOn"), seen) - style = s.applyParagraph(style, n.child("pPr")) - style.run = s.applyRun(style.run, n.child("rPr")) - return style -} -func (s *docxStyles) paragraph(n *docxNode) docxParagraphStyle { - style := s.defaults - pr := n.child("pPr") - style = s.inherit(style, pr.value("pStyle"), map[string]bool{}) - return s.applyParagraph(style, pr) -} -func docxColor(value string) PDFColor { - v, err := strconv.ParseUint(value, 16, 24) - if err != nil { - return PDFColorBlack - } - return PDFColor{Red: float64(v>>16) / 255, Green: float64((v>>8)&255) / 255, Blue: float64(v&255) / 255} -} - -func readDOCXStyles(files officePackage) (*docxStyles, error) { - s := &docxStyles{nodes: map[string]*docxNode{}, theme: map[string]string{}, fonts: map[string]*embeddedFont{}, defaults: docxParagraphStyle{run: docxRunStyle{size: 12, fonts: map[string]string{"ascii": "Arial", "eastAsia": "SimSun"}}, snap: true}} - if _, ok := files["word/settings.xml"]; ok { - data, err := files.read("word/settings.xml") - if err != nil { - return nil, err - } - root, err := parseDOCXNode(data) - if err != nil { - return nil, err - } - s.cjkMetrics = docxOn(root.child("compat").child("useFELayout")) - } - if _, ok := files["word/theme/theme1.xml"]; ok { - data, err := files.read("word/theme/theme1.xml") - if err != nil { - return nil, err - } - root, err := parseDOCXNode(data) - if err != nil { - return nil, err - } - for _, group := range []string{"major", "minor"} { - for _, n := range root.descendants(group + "Font") { - s.theme[group+"HAnsi"] = n.child("latin").attr("typeface") - s.theme[group+"Ascii"] = s.theme[group+"HAnsi"] - s.theme[group+"EastAsia"] = n.child("ea").attr("typeface") - for _, f := range n.children { - if f.name == "font" { - s.theme[group+":"+f.attr("script")] = f.attr("typeface") - } - } - } - } - } - if _, ok := files["word/styles.xml"]; ok { - data, err := files.read("word/styles.xml") - if err != nil { - return nil, err - } - root, err := parseDOCXNode(data) - if err != nil { - return nil, err - } - d := root.child("docDefaults") - s.defaults.run = s.applyRun(s.defaults.run, d.child("rPrDefault").child("rPr")) - s.defaults = s.applyParagraph(s.defaults, d.child("pPrDefault").child("pPr")) - normal := "" - for _, n := range root.children { - if n.name == "style" { - s.nodes[n.attr("styleId")] = n - if n.attr("type") == "paragraph" && n.attr("default") == "1" { - normal = n.attr("styleId") - } - } - } - s.defaults = s.inherit(s.defaults, normal, map[string]bool{}) - } - return s, nil -} -func (s *docxStyles) font(style docxRunStyle, r rune) (*embeddedFont, error) { - key := "ascii" - if r > 127 { - key = "hAnsi" - } - if docxAsian(r) { - key = "eastAsia" - } - name := style.fonts[key] - if theme := style.fonts[key+"Theme"]; theme != "" { - name = s.theme[theme] - if strings.HasSuffix(theme, "EastAsia") && name == "" { - script := "Hans" - if strings.HasPrefix(style.lang, "ja") { - script = "Jpan" - } - if strings.HasPrefix(style.lang, "ko") { - script = "Hang" - } - if style.lang == "zh-TW" || style.lang == "zh-HK" { - script = "Hant" - } - name = s.theme[strings.TrimSuffix(theme, "EastAsia")+":"+script] - } - } - if name == "" { - name = "Arial" - if docxAsian(r) { - name = "SimSun" - } - } - cache := fmt.Sprintf("%s/%t/%t", name, style.bold, style.italic) - f, ok := s.fonts[cache] - if !ok { - var err error - f, err = loadDOCXFont(name, style.bold, style.italic) - if err != nil { - return nil, err - } - s.fonts[cache] = f - } - if r > 127 && (f == nil || !f.canEncode(string(r))) { - fallback := "Arial" - if docxAsian(r) { - fallback = "SimSun" - } - fallbackKey := fmt.Sprintf("%s/%t/%t", fallback, style.bold, style.italic) - if fallbackKey != cache { - fallbackFont, ok := s.fonts[fallbackKey] - if !ok { - var err error - fallbackFont, err = loadDOCXFont(fallback, style.bold, style.italic) - if err != nil { - return nil, err - } - s.fonts[fallbackKey] = fallbackFont - } - if fallbackFont != nil && fallbackFont.canEncode(string(r)) { - return fallbackFont, nil - } - } - } - return f, nil -} -func docxAsian(r rune) bool { - return unicode.Is(unicode.Han, r) || unicode.Is(unicode.Hangul, r) || unicode.Is(unicode.Hiragana, r) || unicode.Is(unicode.Katakana, r) || r >= 0x3000 && r <= 0x303f || r >= 0xff00 && r <= 0xffef || r == 0x25a1 -} - -type docxGlyph struct { - r rune - style docxRunStyle - font *embeddedFont - width, ascent, descent float64 -} -type docxLine struct { - glyphs []docxGlyph - width, height, ascent float64 -} -type docxParagraph struct { - style docxParagraphStyle - lines []docxLine - height float64 -} -type docxImage struct { - op imageOperation - floating bool - left, top float64 -} - -func (s *docxStyles) layoutParagraph(n *docxNode, width, grid float64) (docxParagraph, error) { - p := docxParagraph{style: s.paragraph(n)} - var glyphs []docxGlyph - var visit func(*docxNode, docxRunStyle) error - visit = func(n *docxNode, style docxRunStyle) error { - if n.name == "pPr" || n.name == "rPr" || n.name == "pict" || n.name == "drawing" { - return nil - } - if n.name == "r" { - if id := n.child("rPr").value("rStyle"); id != "" { - inherited := s.inherit(docxParagraphStyle{run: style}, id, map[string]bool{}) - style = inherited.run - } - style = s.applyRun(style, n.child("rPr")) - } - text := "" - if n.name == "t" { - text = n.text - } - if n.name == "tab" { - text = " " - } - if n.name == "br" || n.name == "cr" { - text = "\n" - } - for _, r := range text { - if r == '\n' { - glyphs = append(glyphs, docxGlyph{r: r}) - continue - } - f, err := s.font(style, r) - if err != nil { - return err - } - g := docxGlyph{r: r, style: style, font: f, width: style.size * .5, ascent: style.size * .9, descent: style.size * .25} - if docxAsian(r) { - g.width = style.size - } - if f != nil { - if !f.canEncode(string(r)) { - return fmt.Errorf("DOCX font %q has no glyph for U+%04X", f.name, r) - } - g.width = measureXLSXFont(string(r), style.size, f) - g.ascent = f.ascent * style.size - g.descent = f.descent * style.size - // Writer fntcache.cxx, lcl_ApplyCjkHeightAdjustment: Word's - // FE layout scales metrics for fonts advertising CJK code pages. - if s.cjkMetrics && grid == 0 && docxFontCJK(f.data) { - g.ascent *= 1.27 - g.descent *= 1.27 - } - } else if r > 127 { - return fmt.Errorf("DOCX character U+%04X requires an installed or registered font: %w", r, errDOCXFontUnavailable) - } - glyphs = append(glyphs, g) - } - for _, c := range n.children { - if err := visit(c, style); err != nil { - return err - } - } - return nil - } - if err := visit(n, p.style.run); err != nil { - return p, err - } - emptyFont, err := s.font(p.style.run, ' ') - if err != nil { - return p, err - } - // Word's automatic East Asian/Latin spacing is a quarter-em at script boundaries. - for i := 1; i < len(glyphs); i++ { - a, b := glyphs[i-1].r, glyphs[i].r - if (unicode.Is(unicode.Han, a) && docxLatin(b)) || (docxLatin(a) && unicode.Is(unicode.Han, b)) { - glyphs[i-1].width += math.Min(glyphs[i-1].style.size, glyphs[i].style.size) / 4 - } - } - available := math.Max(1, width-p.style.left-p.style.right) - var line docxLine - flush := func() { - if len(line.glyphs) == 0 { - f := emptyFont - line.ascent = p.style.run.size * .9 - line.height = p.style.run.size * 1.3 - if f != nil { - line.ascent = f.ascent * p.style.run.size - line.height = (f.ascent + f.descent) * p.style.run.size - if s.cjkMetrics && grid == 0 && docxFontCJK(f.data) { - line.ascent *= 1.27 - line.height *= 1.27 - } - } - } - line.height = math.Max(line.height, line.ascent) - if grid > 0 && p.style.snap { - h := math.Ceil((line.height-.001)/grid) * grid - line.ascent += (h - line.height) / 2 - line.height = h - } - if p.style.line > 0 { - if p.style.lineRule == "exact" { - line.height = p.style.line - line.ascent = math.Min(line.ascent, line.height*.8) - } else if p.style.lineRule == "atLeast" { - line.height = math.Max(line.height, p.style.line) - } else { - h := line.height * p.style.line / 12 - if grid > 0 && p.style.snap { - h = math.Ceil((h-.001)/grid) * grid - } - line.ascent += (h - line.height) / 2 - line.height = h - } - } - p.height += line.height - p.lines = append(p.lines, line) - line = docxLine{} - } - for i := 0; i < len(glyphs); i++ { - g := glyphs[i] - if g.r == '\n' { - flush() - continue - } - limit := available - if len(p.lines) == 0 { - limit -= p.style.first - } - if line.width+g.width > limit+.01 && len(line.glyphs) > 0 && !(len(line.glyphs) == 1 && (strings.ContainsRune("(([【《「『", line.glyphs[0].r) || strings.ContainsRune("),。!?、;:)]】》」』", g.r))) { - var carry []docxGlyph - last := line.glyphs[len(line.glyphs)-1] - if strings.ContainsRune("(([【《「『", last.r) || strings.ContainsRune("),。!?、;:)]】》」』", g.r) { - carry = []docxGlyph{last} - line.glyphs = line.glyphs[:len(line.glyphs)-1] - line.width -= last.width - } else if docxLatin(g.r) && docxLatin(last.r) { - for j := len(line.glyphs) - 1; j >= 0; j-- { - if unicode.IsSpace(line.glyphs[j].r) { - carry = append(carry, line.glyphs[j+1:]...) - line.glyphs = line.glyphs[:j+1] - line.width = 0 - for _, c := range line.glyphs { - line.width += c.width - } - break - } - } - } - flush() - for _, c := range carry { - line.glyphs = append(line.glyphs, c) - line.width += c.width - line.ascent = math.Max(line.ascent, c.ascent) - line.height = math.Max(line.height, c.ascent+c.descent) - } - } - line.glyphs = append(line.glyphs, g) - line.width += g.width - line.ascent = math.Max(line.ascent, g.ascent) - line.height = math.Max(line.height, g.ascent+g.descent) - } - flush() - p.height += p.style.before + p.style.after - return p, nil -} -func docxLatin(r rune) bool { return r < 128 && (unicode.IsLetter(r) || unicode.IsDigit(r)) } - -func drawDOCXParagraph(page *PDFPage, p docxParagraph, x, top, width float64) { - top += p.style.before - for i, line := range p.lines { - left := x + p.style.left - if i == 0 { - left += p.style.first - } - switch p.style.align { - case "center": - left += (width - p.style.left - p.style.right - line.width) / 2 - case "right": - left += width - p.style.left - p.style.right - line.width - } - baseline := page.Height - top - line.ascent - for _, g := range line.glyphs { - if g.style.highlight != nil { - page.AddRect(left, page.Height-top-line.height, g.width, line.height, *g.style.highlight) - } - page.operations = append(page.operations, textOperation{text: string(g.r), x: left, y: baseline, fontSize: g.style.size, horizontalScale: 100, color: g.style.color, bold: g.style.bold, italic: g.style.italic, embedded: g.font, synthesize: true}) - left += g.width - } - top += line.height - } -} - -type docxBorder struct { - style string - width float64 - color PDFColor -} - -func readDOCXBorder(n *docxNode) docxBorder { - if n == nil { - return docxBorder{} - } - return docxBorder{style: n.attr("val"), width: docxNumber(n.attr("sz")) / 8, color: docxColor(n.attr("color"))} -} -func docxBorders(n *docxNode, inherited map[string]docxBorder) map[string]docxBorder { - b := map[string]docxBorder{} - for k, v := range inherited { - b[k] = v - } - if n != nil { - for _, c := range n.children { - b[c.name] = readDOCXBorder(c) - } - } - return b -} - -type docxCell struct { - column, span, row, rowSpan int - continuation bool - width float64 - paras []docxParagraph - contentHeight float64 - margins Margins - borders map[string]docxBorder - align string - fill *PDFColor -} -type docxTable struct { - cells []*docxCell - columns, rows []float64 - width float64 - align string - indent float64 -} - -func (s *docxStyles) table(n *docxNode, available float64) (docxTable, error) { - t := docxTable{align: n.child("tblPr").value("jc")} - pr := n.child("tblPr") - var inherited map[string]docxBorder - tm := Margins{Left: 5.4, Right: 5.4} - var styleChain func(string, map[string]bool) - styleChain = func(id string, seen map[string]bool) { - if seen[id] { - return - } - seen[id] = true - if st := s.nodes[id]; st != nil { - styleChain(st.value("basedOn"), seen) - inherited = docxBorders(st.child("tblPr").child("tblBorders"), inherited) - tm = docxCellMargins(st.child("tblPr").child("tblCellMar"), tm) - } - } - styleChain(pr.value("tblStyle"), map[string]bool{}) - inherited = docxBorders(pr.child("tblBorders"), inherited) - tm = docxCellMargins(pr.child("tblCellMar"), tm) - t.indent = docxNumber(pr.child("tblInd").attr("w")) / 20 - for _, col := range n.child("tblGrid").children { - if col.name == "gridCol" { - t.columns = append(t.columns, docxNumber(col.attr("w"))/20) - } - } - for _, w := range t.columns { - t.width += w - } - if w := pr.child("tblW"); w.attr("type") == "dxa" && docxNumber(w.attr("w")) > 0 { - t.width = docxNumber(w.attr("w")) / 20 - } - if w := pr.child("tblW"); w.attr("type") == "pct" { - t.width = available * docxNumber(w.attr("w")) / 5000 - } - gridWidth := 0.0 - for _, w := range t.columns { - gridWidth += w - } - if gridWidth <= 0 || t.width <= 0 { - return t, fmt.Errorf("DOCX table has no positive grid") - } - for i := range t.columns { - t.columns[i] *= t.width / gridWidth - } - active := map[int]*docxCell{} - rowCount := 0 - for _, row := range n.children { - if row.name == "tr" { - rowCount++ - } - } - for _, row := range n.children { - if row.name != "tr" { - continue - } - ri := len(t.rows) - height := docxNumber(row.child("trPr").child("trHeight").attr("val")) / 20 - t.rows = append(t.rows, height) - column := 0 - for _, node := range row.children { - if node.name != "tc" { - continue - } - cp := node.child("tcPr") - span := int(docxNumber(cp.child("gridSpan").attr("val"))) - if span < 1 { - span = 1 - } - if column+span > len(t.columns) { - return t, fmt.Errorf("DOCX cell span exceeds table grid: %w", errDOCXTableLayoutUnsupported) - } - cell := &docxCell{column: column, span: span, row: ri, rowSpan: 1, margins: docxCellMargins(cp.child("tcMar"), tm), align: cp.value("vAlign"), borders: map[string]docxBorder{}} - for i := column; i < column+span; i++ { - cell.width += t.columns[i] - } - for _, edge := range []string{"top", "left", "bottom", "right"} { - key := edge - if edge == "top" && ri > 0 { - key = "insideH" - } - if edge == "bottom" && ri < rowCount-1 { - key = "insideH" - } - if edge == "left" && column > 0 { - key = "insideV" - } - if edge == "right" && column+span < len(t.columns) { - key = "insideV" - } - cell.borders[edge] = inherited[key] - } - cell.borders = docxBorders(cp.child("tcBorders"), cell.borders) - if shd := cp.child("shd"); shd != nil && shd.attr("fill") != "" && shd.attr("fill") != "auto" { - c := docxColor(shd.attr("fill")) - cell.fill = &c - } - if merge := cp.child("vMerge"); merge != nil { - if merge.attr("val") == "restart" { - active[column] = cell - } else if start := active[column]; start != nil && start.span == span { - start.rowSpan++ - cell.continuation = true - start.borders["bottom"] = cell.borders["bottom"] - } else { - return t, fmt.Errorf("DOCX vertical merge has no matching start: %w", errDOCXTableLayoutUnsupported) - } - } else { - delete(active, column) - } - if !cell.continuation { - for _, pn := range node.children { - if pn.name == "p" { - p, err := s.layoutParagraph(pn, math.Max(1, cell.width-cell.margins.Left-cell.margins.Right), 0) - if err != nil { - return t, err - } - cell.paras = append(cell.paras, p) - cell.contentHeight += p.height - } - } - } - t.cells = append(t.cells, cell) - column += span - } - if column != len(t.columns) { - return t, fmt.Errorf("DOCX row does not cover table grid: %w", errDOCXTableLayoutUnsupported) - } - } - for _, c := range t.cells { - if c.continuation || c.rowSpan > 1 { - continue - } - needed := c.contentHeight + c.margins.Top + c.margins.Bottom + docxBorderWidth(c.borders["top"]) + docxBorderWidth(c.borders["bottom"]) - t.rows[c.row] = math.Max(t.rows[c.row], needed) - } - for _, c := range t.cells { - if c.continuation || c.rowSpan == 1 { - continue - } - height := 0.0 - for i := c.row; i < c.row+c.rowSpan; i++ { - height += t.rows[i] - } - needed := c.contentHeight + c.margins.Top + c.margins.Bottom + docxBorderWidth(c.borders["top"]) + docxBorderWidth(c.borders["bottom"]) - if needed > height { - extra := (needed - height) / float64(c.rowSpan) - for i := c.row; i < c.row+c.rowSpan; i++ { - t.rows[i] += extra - } - } - } - return t, nil -} -func docxCellMargins(n *docxNode, m Margins) Margins { - for _, item := range []struct { - key string - out *float64 - }{{"left", &m.Left}, {"right", &m.Right}, {"top", &m.Top}, {"bottom", &m.Bottom}} { - if p := n.child(item.key); p != nil { - *item.out = docxNumber(p.attr("w")) / 20 - } - } - return m -} -func docxBorderWidth(b docxBorder) float64 { - if b.style == "" || b.style == "nil" || b.style == "none" { - return 0 - } - return math.Max(.25, b.width) -} -func drawDOCXBorder(page *PDFPage, b docxBorder, x1, y1, x2, y2 float64) { - w := docxBorderWidth(b) - if w == 0 { - return - } - if b.style == "dotted" || b.style == "dotDash" || b.style == "dashed" { - dash := w * 2 - if b.style == "dashed" { - dash = w * 6 - } - page.operations = append(page.operations, lineOperation{x1: x1, y1: y1, x2: x2, y2: y2, color: b.color, width: w, dash: []float64{dash, w * 2}}) - return - } - page.AddLine(x1, y1, x2, y2, b.color, w) -} -func drawDOCXTable(page *PDFPage, t docxTable, x, top float64) { - xs := []float64{x} - ys := []float64{top} - for _, w := range t.columns { - xs = append(xs, xs[len(xs)-1]+w) - } - for _, h := range t.rows { - ys = append(ys, ys[len(ys)-1]+h) - } - for _, c := range t.cells { - if c.continuation { - continue - } - left, right := xs[c.column], xs[c.column+c.span] - upper, lower := ys[c.row], ys[c.row+c.rowSpan] - if c.fill != nil { - page.AddRect(left, page.Height-lower, right-left, lower-upper, *c.fill) - } - drawDOCXBorder(page, c.borders["top"], left, page.Height-upper, right, page.Height-upper) - drawDOCXBorder(page, c.borders["bottom"], left, page.Height-lower, right, page.Height-lower) - drawDOCXBorder(page, c.borders["left"], left, page.Height-upper, left, page.Height-lower) - drawDOCXBorder(page, c.borders["right"], right, page.Height-upper, right, page.Height-lower) - contentTop := upper + c.margins.Top + docxBorderWidth(c.borders["top"]) - space := lower - upper - c.margins.Top - c.margins.Bottom - docxBorderWidth(c.borders["top"]) - docxBorderWidth(c.borders["bottom"]) - c.contentHeight - if c.align == "center" { - contentTop += space / 2 - } - if c.align == "bottom" { - contentTop += space - } - for _, p := range c.paras { - drawDOCXParagraph(page, p, left+c.margins.Left, contentTop, c.width-c.margins.Left-c.margins.Right) - contentTop += p.height - } - } -} - -func readDOCXImages(files officePackage, n *docxNode) ([]docxImage, error) { - if len(n.descendants("blip")) == 0 { - return nil, nil - } - data, err := files.read("word/_rels/document.xml.rels") - if err != nil { - return nil, err - } - rels, err := parseDOCXNode(data) - if err != nil { - return nil, err - } - targets := map[string]string{} - for _, r := range rels.children { - if r.attr("TargetMode") != "External" { - targets[r.attr("Id")] = r.attr("Target") - } - } - var out []docxImage - var visit func(*docxNode, *docxNode) error - visit = func(n, shape *docxNode) error { - if n.name == "shape" { - shape = n - } - if n.name == "drawing" { - blips := n.descendants("blip") - extents := n.descendants("extent") - if len(blips) == 0 || len(extents) == 0 { - return fmt.Errorf("unsupported DOCX drawing") - } - target, ok := targets[blips[0].attr("embed")] - if !ok { - return fmt.Errorf("DOCX drawing image relationship is missing") - } - name := xlsxResolveRelationshipTarget("word/document.xml", target) - data, err := files.read(name) - if err != nil { - return err - } - config, _, err := image.DecodeConfig(bytes.NewReader(data)) - if err != nil { - return fmt.Errorf("read DOCX image %s: %w", name, err) - } - if config.Width <= 0 || config.Height <= 0 || int64(config.Width) > 25000000/int64(config.Height) { - return fmt.Errorf("DOCX image exceeds 25 million pixels") - } - source, _, err := image.Decode(bytes.NewReader(data)) - if err != nil { - return fmt.Errorf("decode DOCX image %s: %w", name, err) - } - op, err := newPDFImage(source, source.Bounds()) - if err != nil { - return err - } - op.width = docxNumber(extents[0].attr("cx")) / 12700 - op.height = docxNumber(extents[0].attr("cy")) / 12700 - if op.width <= 0 || op.height <= 0 { - return fmt.Errorf("DOCX image has invalid extent") - } - picture := docxImage{op: op} - if shape != nil { - picture.floating = true - props := map[string]string{} - for _, v := range strings.Split(shape.attr("style"), ";") { - kv := strings.SplitN(v, ":", 2) - if len(kv) == 2 { - props[strings.TrimSpace(kv[0])] = strings.TrimSpace(kv[1]) - } - } - left, err := docxVMLLength(props["margin-left"]) - if err != nil { - return err - } - top, err := docxVMLLength(props["margin-top"]) - if err != nil { - return err - } - insetLeft, insetTop := 7.2, 3.6 - if inset := shape.child("textbox").attr("inset"); inset != "" { - parts := strings.Split(inset, ",") - if len(parts) != 4 { - return fmt.Errorf("invalid DOCX text-box inset") - } - insetLeft, err = docxVMLLength(parts[0]) - if err != nil { - return err - } - insetTop, err = docxVMLLength(parts[1]) - if err != nil { - return err - } - } - picture.left = left + insetLeft - picture.top = top + insetTop - } - out = append(out, picture) - return nil - } - for _, c := range n.children { - if err := visit(c, shape); err != nil { - return err - } - } - return nil - } - if err := visit(n, nil); err != nil { - return nil, err - } - return out, nil -} - -func docxUnsupportedMetafiles(files officePackage, body *docxNode) (bool, error) { - blips := body.descendants("blip") - if len(blips) == 0 { - return false, nil - } - data, err := files.read("word/_rels/document.xml.rels") - if err != nil { - return false, err - } - rels, err := parseDOCXNode(data) - if err != nil { - return false, err - } - targets := map[string]string{} - for _, rel := range rels.children { - if rel.attr("TargetMode") != "External" { - targets[rel.attr("Id")] = rel.attr("Target") - } - } - unsupported := false - for _, blip := range blips { - if blip.attr("embed") == "" && blip.attr("link") != "" { - unsupported = true - continue - } - target, ok := targets[blip.attr("embed")] - if !ok { - return false, fmt.Errorf("DOCX drawing image relationship is missing") - } - name := xlsxResolveRelationshipTarget("word/document.xml", target) - if _, ok := files[name]; !ok { - return false, fmt.Errorf("Office package part %q is missing", name) - } - switch strings.ToLower(path.Ext(target)) { - case ".emf", ".wmf": - unsupported = true - case ".png", ".jpg", ".jpeg": - data, err := files.read(name) - if err != nil { - return false, err - } - if _, _, err := image.DecodeConfig(bytes.NewReader(data)); err != nil { - return false, fmt.Errorf("read DOCX image %s: %w", name, err) - } - } - } - return unsupported, nil -} - -func docxVMLLength(value string) (float64, error) { - value = strings.TrimSpace(value) - if value == "" { - return 0, nil - } - for _, unit := range []struct { - name string - scale float64 - }{{"pt", 1}, {"in", 72}, {"cm", 72 / 2.54}, {"mm", 72 / 25.4}, {"px", 72.0 / 96}} { - if strings.HasSuffix(value, unit.name) { - n, err := strconv.ParseFloat(strings.TrimSuffix(value, unit.name), 64) - if err != nil || math.IsNaN(n) || math.IsInf(n, 0) { - return 0, fmt.Errorf("invalid DOCX VML length %q", value) - } - return n * unit.scale, nil - } - } - if value == "0" { - return 0, nil - } - return 0, fmt.Errorf("unsupported DOCX VML length %q", value) -} - -// This structured renderer supports single-page table layouts. Page breaking, -// paragraph keep rules, and row splitting remain on the existing text path. -func renderDOCXTables(files officePackage, data []byte, size PageSize, margins Margins, options ConversionOptions) ([]byte, bool, error) { - root, err := parseDOCXNode(data) - if err != nil { - return nil, false, err - } - body := root.child("body") - if body == nil { - return nil, false, nil - } - if len(body.descendants("numPr")) > 0 || len(body.descendants("anchor")) > 0 || len(body.descendants("pageBreakBefore")) > 0 { - return nil, false, nil - } - if len(body.descendants("gridBefore")) > 0 || len(body.descendants("gridAfter")) > 0 { - return nil, false, nil - } - for _, box := range body.descendants("txbxContent") { - for _, text := range box.descendants("t") { - if text.text != "" { - return nil, false, nil - } - } - } - for _, br := range body.descendants("br") { - if br.attr("type") == "page" { - return nil, false, nil - } - } - for _, height := range body.descendants("trHeight") { - if height.attr("hRule") == "exact" { - return nil, false, nil - } - } - for _, border := range append(body.descendants("tcBorders"), body.descendants("tblBorders")...) { - for _, edge := range border.children { - switch edge.attr("val") { - case "", "nil", "none", "single", "dotted", "dotDash", "dashed": - default: - return nil, false, nil - } - } - } - hasTable := false - for _, n := range body.children { - if n.name != "p" && n.name != "tbl" && n.name != "sectPr" && n.name != "bookmarkStart" && n.name != "bookmarkEnd" { - return nil, false, nil - } - if n.name == "tbl" { - hasTable = true - if len(n.descendants("tbl")) > 0 || len(n.descendants("drawing")) > 0 || n.child("tblPr").child("tblpPr") != nil || n.child("tblGrid") == nil { - return nil, false, nil - } - for _, c := range n.child("tblGrid").children { - if c.name == "gridCol" && docxNumber(c.attr("w")) <= 0 { - return nil, false, nil - } - } - } - if n.name == "p" && (n.child("pPr").child("sectPr") != nil || len(n.descendants("numPr")) > 0) { - return nil, false, nil - } - } - if !hasTable { - return nil, false, nil - } - unsupportedImages, err := docxUnsupportedMetafiles(files, body) - if err != nil { - return nil, true, err - } - if unsupportedImages { - return nil, false, nil - } - if docxUnsupportedInlineFlow(body) { - return nil, false, nil - } - s, err := readDOCXStyles(files) - if err != nil { - return nil, true, err - } - grid := 0.0 - if g := body.child("sectPr").child("docGrid"); g.attr("type") == "lines" || g.attr("type") == "linesAndChars" { - grid = docxNumber(g.attr("linePitch")) / 20 - } - doc := NewPDFDocument() - page := doc.AddPage(size.Width, size.Height) - top := margins.Top - previousAfter := 0.0 - available := size.Width - margins.Left - margins.Right - for _, n := range body.children { - switch n.name { - case "p": - p, err := s.layoutParagraph(n, available, grid) - if err != nil { - if errors.Is(err, errDOCXFontUnavailable) { - return nil, false, nil - } - return nil, true, err - } - p.style.before = math.Max(0, p.style.before-previousAfter) - p.height -= math.Min(previousAfter, s.paragraph(n).before) - if top+p.height > size.Height-margins.Bottom { - return nil, false, nil - } - drawDOCXParagraph(page, p, margins.Left, top, available) - pictures, err := readDOCXImages(files, n) - if err != nil { - return nil, true, err - } - for _, picture := range pictures { - op := picture.op - op.x = margins.Left + picture.left - op.y = size.Height - top - picture.top - op.height - if !picture.floating { - contentWidth := available - p.style.left - p.style.right - p.style.first - if op.width > contentWidth { - return nil, false, nil - } - op.x = margins.Left + p.style.left + p.style.first - if p.style.align == "center" { - op.x += (contentWidth - op.width) / 2 - } else if p.style.align == "right" { - op.x += contentWidth - op.width - } - op.y = size.Height - top - p.style.before - op.height - p.height = p.style.before + math.Max(p.height-p.style.before-p.style.after, op.height) + p.style.after - } - page.operations = append(page.operations, op) - } - if top+p.height > size.Height-margins.Bottom { - return nil, false, nil - } - top += p.height - previousAfter = p.style.after - case "tbl": - t, err := s.table(n, available) - if err != nil { - if errors.Is(err, errDOCXFontUnavailable) || errors.Is(err, errDOCXTableLayoutUnsupported) { - return nil, false, nil - } - return nil, true, err - } - height := 0.0 - for _, h := range t.rows { - height += h - } - if top+height > size.Height-margins.Bottom { - return nil, false, nil - } - left := margins.Left + t.indent - if t.align == "center" { - left = margins.Left + (available-t.width)/2 - } - if t.align == "right" { - left = size.Width - margins.Right - t.width - } - if left < 0 || left+t.width > size.Width { - return nil, false, nil - } - drawDOCXTable(page, t, left, top) - top += height - previousAfter = 0 - } - } - return doc.BytesWithOptions(PDFSaveOptions{Compress: options.Compress}), true, nil -} - -func docxUnsupportedInlineFlow(body *docxNode) bool { - for _, p := range body.descendants("p") { - inlineCount := 0 - var countInline func(*docxNode) - countInline = func(n *docxNode) { - // VML pictures have floating placement, not paragraph inline flow. - if n.name == "pict" { - return - } - if n.name == "drawing" && n.child("inline") != nil { - inlineCount++ - } - for _, c := range n.children { - countInline(c) - } - } - countInline(p) - if inlineCount > 1 { - return true - } - if inlineCount == 1 { - if len(p.descendants("br")) > 0 || len(p.descendants("cr")) > 0 || len(p.descendants("tab")) > 0 { - return true - } - for _, text := range p.descendants("t") { - if text.text != "" { - return true - } - } - } - } - return false -} diff --git a/minipdf-go/docx_render_test.go b/minipdf-go/docx_render_test.go deleted file mode 100644 index f2c7f5d1..00000000 --- a/minipdf-go/docx_render_test.go +++ /dev/null @@ -1,640 +0,0 @@ -package minipdf - -import ( - "bytes" - "encoding/binary" - "errors" - "fmt" - "image" - "image/png" - "math" - "strings" - "testing" - - "golang.org/x/image/font/gofont/gobolditalic" - "golang.org/x/image/font/gofont/goregular" - "golang.org/x/image/font/sfnt" -) - -func docxTestStyles(t *testing.T, styles string) *docxStyles { - t.Helper() - ClearRegisteredFonts() - t.Cleanup(ClearRegisteredFonts) - RegisterFont("Portable Test", goregular.TTF) - files, err := openOfficePackage(officePackageBytes(t, map[string]string{"word/styles.xml": styles})) - if err != nil { - t.Fatal(err) - } - s, err := readDOCXStyles(files) - if err != nil { - t.Fatal(err) - } - return s -} - -func TestDOCXTableGridMergedCellsAndInheritedStyles(t *testing.T) { - s := docxTestStyles(t, ``) - n, err := parseDOCXNode([]byte(`

Merged

Wide

Left

Right

`)) - if err != nil { - t.Fatal(err) - } - table, err := s.table(n, 300) - if err != nil { - t.Fatal(err) - } - if table.width != 240 || table.cells[0].rowSpan != 2 || !table.cells[2].continuation || table.cells[1].width != 180 { - t.Fatalf("incorrect table geometry: %+v", table) - } - page := NewPDFDocument().AddPage(400, 500) - drawDOCXTable(page, table, 30, 50) - var merged []textOperation - var highlighted bool - for _, op := range page.operations { - switch op := op.(type) { - case textOperation: - if op.text == "M" { - merged = append(merged, op) - } - case rectOperation: - highlighted = highlighted || op.color == (PDFColor{Red: 1, Green: 1}) - } - } - if len(merged) != 1 || merged[0].x != 30 || merged[0].y >= 450 || merged[0].y <= 410 || !highlighted { - t.Fatalf("merged text or highlight not rendered: %+v, highlight=%t", merged, highlighted) - } - if table.cells[0].borders["left"].width != 1 { - t.Fatal("table style border was lost") - } -} - -func TestDOCXRunFontAndParagraphInheritance(t *testing.T) { - s := docxTestStyles(t, ``) - n, err := parseDOCXNode([]byte(`

AΩ

`)) - if err != nil { - t.Fatal(err) - } - - p, err := s.layoutParagraph(n, 200, 0) - if err != nil { - t.Fatal(err) - } - if p.style.before != 2 || p.style.after != 4 || p.style.align != "center" { - t.Fatalf("paragraph inheritance lost: %+v", p.style) - } - g := p.lines[0].glyphs - if len(g) != 2 || g[0].style.size != 14 || g[1].style.size != 9 || g[1].font == nil || g[0].style.color.Red != 1 || g[1].style.color.Blue != 1 { - t.Fatalf("run inheritance lost: %+v", g) - } - if math.Abs(p.lines[0].width-(measureXLSXFont("A", 14, g[0].font)+measureXLSXFont("Ω", 9, g[1].font))) > .001 { - t.Fatal("layout did not use glyph advances") - } -} - -func TestDOCXWrappingKeepsLatinWordsTogether(t *testing.T) { - s := docxTestStyles(t, ``) - n, err := parseDOCXNode([]byte(`

alpha beta

`)) - if err != nil { - t.Fatal(err) - } - f, err := s.font(s.defaults.run, 'a') - if err != nil { - t.Fatal(err) - } - p, err := s.layoutParagraph(n, measureXLSXFont("alpha be", 10, f), 0) - if err != nil { - t.Fatal(err) - } - var lines []string - for _, line := range p.lines { - var text strings.Builder - for _, g := range line.glyphs { - text.WriteRune(g.r) - } - lines = append(lines, text.String()) - } - if strings.Join(lines, "|") != "alpha |beta" { - t.Fatalf("Latin word split at arbitrary glyph: %v", lines) - } -} - -func TestDOCXCollectionFontRebasesTables(t *testing.T) { - collection := make([]byte, 16+len(goregular.TTF)) - copy(collection, "ttcf") - binary.BigEndian.PutUint32(collection[4:8], 0x10000) - binary.BigEndian.PutUint32(collection[8:12], 1) - binary.BigEndian.PutUint32(collection[12:16], 16) - copy(collection[16:], goregular.TTF) - n := int(binary.BigEndian.Uint16(collection[20:22])) - for i := 0; i < n; i++ { - r := collection[28+i*16 : 44+i*16] - binary.BigEndian.PutUint32(r[8:12], binary.BigEndian.Uint32(r[8:12])+16) - } - standalone, err := docxCollectionFont(collection, 0) - if err != nil { - t.Fatal(err) - } - f, err := sfnt.Parse(standalone) - if err != nil { - t.Fatal(err) - } - glyph, err := f.GlyphIndex(nil, 'Ω') - if err != nil || glyph == 0 { - t.Fatalf("collection glyph lost: %d %v", glyph, err) - } - if _, err = docxCollectionFont(collection, 1); err == nil { - t.Fatal("out-of-range collection index accepted") - } - broken := bytes.Clone(collection) - binary.BigEndian.PutUint32(broken[12:16], uint32(len(broken))) - if _, err = docxCollectionFont(broken, 0); err == nil { - t.Fatal("invalid collection offset accepted") - } -} - -func TestDOCXEquivalentFontInstancesUseCanonicalPDFResource(t *testing.T) { - ClearRegisteredFonts() - t.Cleanup(ClearRegisteredFonts) - RegisterFont("Portable Test", goregular.TTF) - a, err := loadDOCXFont("Portable Test", false, false) - if err != nil { - t.Fatal(err) - } - b, err := loadDOCXFont("Portable Test", false, false) - if err != nil { - t.Fatal(err) - } - d := NewPDFDocument() - p := d.AddPage(200, 200) - p.operations = append(p.operations, textOperation{text: "A", x: 10, y: 100, fontSize: 12, embedded: a}, textOperation{text: "Ω", x: 30, y: 100, fontSize: 12, embedded: b}) - pdf := d.Bytes() - if a.resource == "" || b.resource != a.resource || bytes.Count(pdf, []byte("/Subtype /Type0")) != 1 || bytes.Contains(pdf, []byte("BT / ")) { - t.Fatal("equivalent font instances have unresolved PDF resources") - } - encoded, ok := b.encode("Ω") - if !ok || !bytes.Contains(pdf, []byte("BT /"+a.resource+" 12 Tf 0 0 0 rg 30 100 Td <"+encoded+"> Tj")) || bytes.Contains(pdf, []byte("30 100 Td (?)")) { - t.Fatal("alias Unicode text did not use the canonical embedded glyph resource") - } -} - -func TestDOCXMissingImageRelationshipReturnsError(t *testing.T) { - n, err := parseDOCXNode([]byte(`

`)) - if err != nil { - t.Fatal(err) - } - files, err := openOfficePackage(officePackageBytes(t, map[string]string{"word/_rels/document.xml.rels": ""})) - if err != nil { - t.Fatal(err) - } - _, err = readDOCXImages(files, n) - if err == nil || !strings.Contains(err.Error(), "relationship") { - t.Fatalf("missing image was silently discarded: %v", err) - } -} - -func TestDOCXPackagePictureExtentAndTextBoxInsets(t *testing.T) { - var encoded bytes.Buffer - if err := png.Encode(&encoded, image.NewRGBA(image.Rect(0, 0, 2, 3))); err != nil { - t.Fatal(err) - } - files, err := openOfficePackage(officePackageBytes(t, map[string]string{"word/_rels/document.xml.rels": ``, "word/media/picture.png": encoded.String()})) - if err != nil { - t.Fatal(err) - } - n, err := parseDOCXNode([]byte(`

`)) - if err != nil { - t.Fatal(err) - } - images, err := readDOCXImages(files, n) - if err != nil { - t.Fatal(err) - } - if len(images) != 1 || !images[0].floating || images[0].left != 75 || images[0].top != 6 || images[0].op.width != 20 || images[0].op.height != 30 || images[0].op.pixelWidth != 2 { - t.Fatalf("picture geometry lost: %+v", images) - } -} - -func TestDOCXFELayoutScalesCJKCapableFontMetrics(t *testing.T) { - data := bytes.Clone(goregular.TTF) - n := int(binary.BigEndian.Uint16(data[4:6])) - found := false - for i := 0; i < n; i++ { - r := data[12+i*16 : 28+i*16] - if string(r[:4]) == "OS/2" { - o := int(binary.BigEndian.Uint32(r[8:12])) - if binary.BigEndian.Uint32(r[12:16]) < 86 { - t.Skip("portable test font has no code-page capabilities") - } - binary.BigEndian.PutUint32(data[o+78:o+82], 1<<18) - found = true - } - } - if !found { - t.Fatal("test font has no OS/2 table") - } - ClearRegisteredFonts() - t.Cleanup(ClearRegisteredFonts) - RegisterFont("CJK capable", data) - s := &docxStyles{nodes: map[string]*docxNode{}, fonts: map[string]*embeddedFont{}, theme: map[string]string{}, defaults: docxParagraphStyle{run: docxRunStyle{size: 10, fonts: map[string]string{"ascii": "CJK capable"}}}} - root, err := parseDOCXNode([]byte(`

A

`)) - if err != nil { - t.Fatal(err) - } - plain, err := s.layoutParagraph(root, 100, 0) - if err != nil { - t.Fatal(err) - } - s.cjkMetrics = true - adjusted, err := s.layoutParagraph(root, 100, 0) - if err != nil { - t.Fatal(err) - } - if math.Abs(adjusted.lines[0].height/plain.lines[0].height-1.27) > .001 || adjusted.lines[0].width != plain.lines[0].width { - t.Fatal("FE compatibility did not scale vertical metrics independently of glyph width") - } -} - -func TestDOCXEastAsianPunctuationDoesNotStartOrEndWrappedLine(t *testing.T) { - ClearRegisteredFonts() - t.Cleanup(ClearRegisteredFonts) - f, err := loadDOCXFont("SimSun", false, false) - if err != nil { - t.Fatal(err) - } - if f == nil { - t.Skip("requires licensed installed SimSun") - } - s := &docxStyles{nodes: map[string]*docxNode{}, fonts: map[string]*embeddedFont{"SimSun/false/false": f}, theme: map[string]string{}, defaults: docxParagraphStyle{run: docxRunStyle{size: 8, fonts: map[string]string{"eastAsia": "SimSun"}}}} - n, err := parseDOCXNode([]byte(`

机房(扶梯上机舱)

`)) - if err != nil { - t.Fatal(err) - } - p, err := s.layoutParagraph(n, 24.9, 0) - if err != nil { - t.Fatal(err) - } - var lines []string - for _, line := range p.lines { - var text strings.Builder - for _, g := range line.glyphs { - text.WriteRune(g.r) - } - lines = append(lines, text.String()) - } - if strings.Join(lines, "|") != "机房|(扶梯|上机|舱)" { - t.Fatalf("invalid East Asian punctuation break: %v", lines) - } -} - -func TestDOCXUnsupportedMetafilesRetainLegacyConversion(t *testing.T) { - document := `

Text preserved

Cell preserved

` - for _, extension := range []string{"emf", "WMF", "png", "jpeg"} { - t.Run(extension, func(t *testing.T) { - name := "word/media/image." + extension - input := officePackageBytes(t, map[string]string{ - "word/document.xml": document, - "word/_rels/document.xml.rels": ``, - name: "not a raster image", - }) - files, err := openOfficePackage(input) - if err != nil { - t.Fatal(err) - } - _, supported, err := renderDOCXTables(files, []byte(document), PageSizeA4, Margins{Left: 40, Top: 40, Right: 40, Bottom: 40}, ConversionOptions{}) - if extension == "png" || extension == "jpeg" { - if !supported || err == nil || !strings.Contains(err.Error(), "DOCX image") { - t.Fatalf("malformed raster image was swallowed: supported=%t, err=%v", supported, err) - } - return - } - if supported || err != nil { - t.Fatalf("metafile should retain legacy conversion: supported=%t, err=%v", supported, err) - } - pdf, err := ConvertBytesToPDF(input) - assertPDFContains(t, pdf, err, "Text preserved", "Cell preserved") - }) - } -} - -func TestDOCXStructuredPaginationRetainsLegacyConversion(t *testing.T) { - ClearRegisteredFonts() - t.Cleanup(ClearRegisteredFonts) - RegisterFont("Portable Test", goregular.TTF) - const table = `

Table

` - for _, test := range []struct { - name, tail string - supported bool - }{ - {"table overflow", table, false}, - {"paragraph overflow", `

Tail

`, false}, - {"single-page flow", `

Tail

`, true}, - } { - t.Run(test.name, func(t *testing.T) { - data := []byte(`` + table + test.tail + ``) - input := officePackageBytes(t, map[string]string{ - "word/document.xml": string(data), - "word/styles.xml": ``, - }) - files, err := openOfficePackage(input) - if err != nil { - t.Fatal(err) - } - size := PageSize{Width: 200, Height: 100} - margins := Margins{Left: 10, Top: 10, Right: 10, Bottom: 10} - options := ConversionOptions{PageSize: &size, Margins: &margins} - _, supported, err := renderDOCXTables(files, data, size, margins, options) - if err != nil || supported != test.supported { - t.Fatalf("single-page capability: supported=%t, err=%v", supported, err) - } - if test.supported { - return - } - pages, sourceSize, sourceMargins, err := extractDOCX(data) - if err != nil { - t.Fatal(err) - } - var textPages []textPage - for _, lines := range pages { - textPages = append(textPages, textPage{lines: lines, size: sourceSize, margins: sourceMargins}) - } - want := renderTextPages(textPages, options) - got, err := ConvertBytesToPDFWithOptions(input, options) - if err != nil || !bytes.Equal(got, want) { - t.Fatalf("pagination fallback changed legacy PDF: %v", err) - } - }) - } -} - -func TestDOCXUnsupportedLayoutKeepsTextConverter(t *testing.T) { - data := []byte(`

First
Second

`) - _, supported, err := renderDOCXTables(nil, data, PageSizeA4, Margins{Left: 40, Right: 40, Top: 40, Bottom: 40}, ConversionOptions{}) - if err != nil || supported { - t.Fatalf("unsupported explicit pagination was not retained on legacy path: %t, %v", supported, err) - } -} - -func TestDOCXDashRenderingHasBoundedOperations(t *testing.T) { - for _, style := range []string{"dotted", "dotDash", "dashed"} { - page := NewPDFDocument().AddPage(612, 792) - drawDOCXBorder(page, docxBorder{style: style, width: .25}, 10, 10, float64(2147483647)/20, 10) - if len(page.operations) != 1 { - t.Fatalf("%s retained %d operations for off-page geometry", style, len(page.operations)) - } - var stream bytes.Buffer - page.operations[0].appendPDF(&stream, nil) - if !strings.Contains(stream.String(), "] 0 d ") || bytes.Count(stream.Bytes(), []byte(" l S")) != 1 || !strings.HasSuffix(stream.String(), "Q\n") { - t.Fatalf("dash stroke is not a single isolated native PDF operation: %s", &stream) - } - } - s := docxTestStyles(t, docxReviewStyles) - data := []byte(`

`) - files, err := openOfficePackage(officePackageBytes(t, map[string]string{"word/styles.xml": docxReviewStyles})) - if err != nil { - t.Fatal(err) - } - root, err := parseDOCXNode(data) - if err != nil { - t.Fatal(err) - } - table, err := s.table(root.child("body").child("tbl"), 500) - if err != nil { - t.Fatal(err) - } - page := NewPDFDocument().AddPage(612, 792) - drawDOCXTable(page, table, 40, 40) - if len(page.operations) != 1 { - t.Fatalf("full extreme-grid table retained %d operations", len(page.operations)) - } - _, supported, err := renderDOCXTables(files, data, PageSizeA4, Margins{Left: 40, Right: 40, Top: 40, Bottom: 40}, ConversionOptions{}) - if supported || err != nil { - t.Fatalf("table outside physical page did not decline native layout: %t %v", supported, err) - } -} - -func TestDOCXSynthesizesOnlyMissingFontEmphasis(t *testing.T) { - ClearRegisteredFonts() - t.Cleanup(ClearRegisteredFonts) - RegisterFont("Portable Test", goregular.TTF) - for _, native := range []bool{false, true} { - if native { - RegisterFont("Portable Test Bold Italic", gobolditalic.TTF) - } - f, err := loadDOCXFont("Portable Test", true, true) - if err != nil || f == nil { - t.Fatalf("styled registered font unavailable: %v", err) - } - if f.nativeBold != native || f.nativeItalic != native { - t.Fatalf("native emphasis incorrectly identified: %+v", f) - } - f.collect("Ω") - f.resource = "FU1" - var stream bytes.Buffer - op := textOperation{text: "Ω", x: 10, y: 20, fontSize: 12, bold: true, italic: true, color: PDFColor{Red: 1}, embedded: f, synthesize: true} - op.appendPDF(&stream, nil) - if !strings.Contains(stream.String(), "/FU1 12 Tf") || strings.Contains(stream.String(), "(?)") { - t.Fatal("emphasis lost Unicode embedding") - } - if native { - if strings.Contains(stream.String(), "2 Tr") || strings.Contains(stream.String(), " Tm") { - t.Fatal("native bold italic face was double-synthesized") - } - } else if !strings.Contains(stream.String(), "2 Tr") || !strings.Contains(stream.String(), "0.21256 1 10 20 Tm") || !strings.Contains(stream.String(), "1 0 0 RG") || !strings.HasSuffix(stream.String(), "Q\n") { - t.Fatalf("missing face was not synthesized with isolated stroke/slant: %s", &stream) - } - } -} - -func TestDOCXHangulUsesEastAsianAndKoreanThemeFonts(t *testing.T) { - data := bytes.Clone(goregular.TTF) - original, err := sfnt.Parse(data) - if err != nil { - t.Fatal(err) - } - glyph, err := original.GlyphIndex(nil, 'Ω') - if err != nil { - t.Fatal(err) - } - // Supply a synthetic cmap for the portable font; no host Korean font is required. - cmap := make([]byte, 40) - binary.BigEndian.PutUint16(cmap[2:4], 1) - binary.BigEndian.PutUint16(cmap[4:6], 3) - binary.BigEndian.PutUint16(cmap[6:8], 10) - binary.BigEndian.PutUint32(cmap[8:12], 12) - binary.BigEndian.PutUint16(cmap[12:14], 12) - binary.BigEndian.PutUint32(cmap[16:20], 28) - binary.BigEndian.PutUint32(cmap[24:28], 1) - binary.BigEndian.PutUint32(cmap[28:32], 0xac00) - binary.BigEndian.PutUint32(cmap[32:36], 0xac00) - binary.BigEndian.PutUint32(cmap[36:40], uint32(glyph)) - for i, n := 0, int(binary.BigEndian.Uint16(data[4:6])); i < n; i++ { - r := data[12+i*16 : 28+i*16] - if string(r[:4]) == "cmap" { - binary.BigEndian.PutUint32(r[8:12], uint32(len(data))) - binary.BigEndian.PutUint32(r[12:16], uint32(len(cmap))) - } - } - data = append(data, cmap...) - ClearRegisteredFonts() - t.Cleanup(ClearRegisteredFonts) - RegisterFont("Korean Test", data) - s := &docxStyles{fonts: map[string]*embeddedFont{}, theme: map[string]string{"minor:Hang": "Korean Test"}} - for _, fonts := range []map[string]string{{"eastAsia": "Korean Test", "hAnsi": "Wrong font"}, {"eastAsiaTheme": "minorEastAsia", "hAnsi": "Wrong font"}} { - f, err := s.font(docxRunStyle{fonts: fonts, lang: "ko-KR"}, '가') - if err != nil || f == nil || !bytes.Equal(f.data, data) || !f.canEncode("가") { - t.Fatalf("Hangul did not select the East Asian Korean font: %v", err) - } - } -} - -func TestDOCXInteriorBottomBordersAndMergeFinalEdge(t *testing.T) { - s := docxTestStyles(t, ``) - for _, inside := range []string{"none", "dashed"} { - xml := `

` - n, err := parseDOCXNode([]byte(xml)) - if err != nil { - t.Fatal(err) - } - table, err := s.table(n, 300) - if err != nil { - t.Fatal(err) - } - if table.cells[1].borders["bottom"].style != inside || table.cells[0].borders["bottom"].style != "single" || table.cells[3].borders["bottom"].width != 2 || table.cells[3].borders["top"].style != "dotted" { - t.Fatalf("interior/outer/override/merge edges lost for %s", inside) - } - } -} - -const docxReviewTable = `

Cell

` -const docxReviewStyles = `` - -func docxReviewPackage(t *testing.T, body string, parts map[string]string) (officePackage, []byte, []byte) { - t.Helper() - if parts == nil { - parts = map[string]string{} - } - data := []byte(`` + body + ``) - parts["word/document.xml"] = string(data) - parts["word/styles.xml"] = docxReviewStyles - input := officePackageBytes(t, parts) - files, err := openOfficePackage(input) - if err != nil { - t.Fatal(err) - } - return files, data, input -} - -func TestDOCXUnsupportedReviewLayoutsRetainLegacy(t *testing.T) { - ClearRegisteredFonts() - t.Cleanup(ClearRegisteredFonts) - RegisterFont("Portable Test", goregular.TTF) - var encoded bytes.Buffer - if err := png.Encode(&encoded, image.NewRGBA(image.Rect(0, 0, 2, 3))); err != nil { - t.Fatal(err) - } - picture := `` - for _, test := range []struct{ name, body string }{ - {"gridBefore", strings.Replace(docxReviewTable, "", ``, 1)}, - {"gridAfter", strings.Replace(docxReviewTable, "", ``, 1)}, - {"span", strings.Replace(docxReviewTable, "", ``, 1)}, - {"merge", strings.Replace(docxReviewTable, "", ``, 1)}, - {"text box", `

Box text

` + docxReviewTable}, - {"mixed inline text", `

Before` + picture + `

` + docxReviewTable}, - {"multiple inline images", `

` + picture + picture + `

` + docxReviewTable}, - {"inline break", `


` + picture + `

` + docxReviewTable}, - {"linked image", `

` + strings.Replace(picture, `embed="picture"`, `link="external"`, 1) + `

` + docxReviewTable}, - } { - t.Run(test.name, func(t *testing.T) { - files, data, input := docxReviewPackage(t, test.body, map[string]string{"word/_rels/document.xml.rels": ``, "word/media/image.png": encoded.String()}) - _, supported, err := renderDOCXTables(files, data, PageSizeA4, Margins{Left: 40, Top: 40, Right: 40, Bottom: 40}, ConversionOptions{}) - if supported || err != nil { - t.Fatalf("layout did not fall back: supported=%t err=%v", supported, err) - } - pdf, err := ConvertBytesToPDF(input) - if err != nil { - t.Fatal(err) - } - pages, size, margins, err := extractDOCX(data) - if err != nil { - t.Fatal(err) - } - var legacy []textPage - var text []string - for _, lines := range pages { - legacy = append(legacy, textPage{lines: lines, size: size, margins: margins}) - text = append(text, lines...) - } - if !bytes.Equal(pdf, renderTextPages(legacy, ConversionOptions{})) || !strings.Contains(strings.Join(text, "\n"), "Cell") { - t.Fatal("fallback changed legacy text conversion") - } - if test.name == "text box" && !strings.Contains(strings.Join(text, "\n"), "Box text") { - t.Fatal("fallback lost text-box text") - } - }) - } -} - -func TestDOCXImageOnlyAlignmentAndAbsoluteTargets(t *testing.T) { - ClearRegisteredFonts() - t.Cleanup(ClearRegisteredFonts) - RegisterFont("Portable Test", goregular.TTF) - var encoded bytes.Buffer - if err := png.Encode(&encoded, image.NewRGBA(image.Rect(0, 0, 2, 3))); err != nil { - t.Fatal(err) - } - for _, test := range []struct { - align string - x float64 - }{{"left", 40}, {"center", 90}, {"right", 140}} { - body := `

` + docxReviewTable - files, data, _ := docxReviewPackage(t, body, map[string]string{"word/_rels/document.xml.rels": ``, "word/media/image.png": encoded.String()}) - pdf, supported, err := renderDOCXTables(files, data, PageSize{Width: 200, Height: 300}, Margins{Left: 40, Top: 40, Right: 40, Bottom: 40}, ConversionOptions{}) - if err != nil || !supported || !bytes.Contains(pdf, []byte(fmt.Sprintf("20 0 0 30 %s 225 cm", pdfNumber(test.x)))) { - t.Fatalf("%s image lost absolute target/spacing/alignment: supported=%t err=%v", test.align, supported, err) - } - } -} - -func TestDOCXGridTypeControlsLineSnapping(t *testing.T) { - ClearRegisteredFonts() - t.Cleanup(ClearRegisteredFonts) - RegisterFont("Portable Test", goregular.TTF) - var plain []byte - for _, typ := range []string{"", "default", "snapToChars", "lines", "linesAndChars"} { - files, data, _ := docxReviewPackage(t, `

Text

`+docxReviewTable+``, nil) - pdf, supported, err := renderDOCXTables(files, data, PageSizeA4, Margins{Left: 40, Top: 40, Right: 40, Bottom: 40}, ConversionOptions{}) - if err != nil || !supported { - t.Fatalf("grid %s failed: %v", typ, err) - } - if typ == "" { - plain = pdf - } - if (typ == "default" || typ == "snapToChars") && !bytes.Equal(pdf, plain) { - t.Fatalf("inactive grid %s altered paragraph layout", typ) - } - if (typ == "lines" || typ == "linesAndChars") && bytes.Equal(pdf, plain) { - t.Fatalf("active grid %s did not snap lines", typ) - } - } -} - -func TestDOCXUnavailableFontsFallbackButMissingGlyphsFail(t *testing.T) { - ClearRegisteredFonts() - t.Cleanup(ClearRegisteredFonts) - t.Setenv("WINDIR", "") - for _, body := range []string{`

é

` + docxReviewTable, strings.Replace(docxReviewTable, "Cell", "é", 1)} { - files, data, input := docxReviewPackage(t, body, nil) - _, supported, err := renderDOCXTables(files, data, PageSizeA4, Margins{Left: 40, Top: 40, Right: 40, Bottom: 40}, ConversionOptions{}) - if err != nil || supported { - t.Fatalf("missing environment font did not fall back: %t %v", supported, err) - } - if _, err := ConvertBytesToPDF(input); err != nil { - t.Fatalf("legacy font fallback failed: %v", err) - } - } - RegisterFont("Portable Test", goregular.TTF) - files, data, _ := docxReviewPackage(t, strings.Replace(docxReviewTable, "Cell", "\U0001f600", 1), nil) - _, supported, err := renderDOCXTables(files, data, PageSizeA4, Margins{Left: 40, Top: 40, Right: 40, Bottom: 40}, ConversionOptions{}) - if !supported || err == nil || errors.Is(err, errDOCXFontUnavailable) || !strings.Contains(err.Error(), "has no glyph") { - t.Fatalf("present font's missing glyph was silently downgraded: %t %v", supported, err) - } -} diff --git a/minipdf-go/font.go b/minipdf-go/font.go deleted file mode 100644 index 31944ffd..00000000 --- a/minipdf-go/font.go +++ /dev/null @@ -1,217 +0,0 @@ -package minipdf - -import ( - "bytes" - "fmt" - "sort" - "strings" - "unicode/utf16" - - "golang.org/x/image/font" - "golang.org/x/image/font/sfnt" - "golang.org/x/image/math/fixed" -) - -type embeddedFont struct { - name string - data []byte - font *sfnt.Font - runeToGlyph map[rune]sfnt.GlyphIndex - glyphToRune map[sfnt.GlyphIndex]rune - objectID int - resource string - advances []float64 - ascent, descent float64 - nativeBold, nativeItalic bool -} - -func prepareEmbeddedFont(pages []*PDFPage) *embeddedFont { - for _, registered := range RegisteredFonts() { - parsed, err := sfnt.Parse(registered.Data) - if err != nil { - continue - } - candidate := &embeddedFont{ - name: sanitizePDFFontName(registered.Name), - data: registered.Data, - font: parsed, - runeToGlyph: make(map[rune]sfnt.GlyphIndex), - glyphToRune: make(map[sfnt.GlyphIndex]rune), - } - used := false - for _, page := range pages { - for _, operation := range page.operations { - text, ok := operation.(textOperation) - if !ok || text.embedded != nil || !candidate.canEncode(text.text) { - continue - } - candidate.collect(text.text) - used = true - } - } - if used { - return candidate - } - } - return nil -} - -func (embedded *embeddedFont) canEncode(text string) bool { - var buffer sfnt.Buffer - for _, character := range normalizedFontRunes(text) { - glyph, err := embedded.font.GlyphIndex(&buffer, character) - if err != nil || glyph == 0 { - return false - } - } - return true -} - -func (embedded *embeddedFont) collect(text string) { - var buffer sfnt.Buffer - for _, character := range normalizedFontRunes(text) { - glyph, err := embedded.font.GlyphIndex(&buffer, character) - if err != nil || glyph == 0 { - continue - } - embedded.runeToGlyph[character] = glyph - if _, exists := embedded.glyphToRune[glyph]; !exists { - embedded.glyphToRune[glyph] = character - } - } -} - -func (embedded *embeddedFont) encode(text string) (string, bool) { - var encoded strings.Builder - for _, character := range normalizedFontRunes(text) { - glyph, ok := embedded.runeToGlyph[character] - if !ok { - return "", false - } - fmt.Fprintf(&encoded, "%04X", uint16(glyph)) - } - return encoded.String(), true -} - -func normalizedFontRunes(text string) []rune { - characters := []rune(text) - for index, character := range characters { - if character == '\n' || character == '\r' || character == '\t' { - characters[index] = ' ' - } - } - return characters -} - -func appendEmbeddedFontObjects(objects *[][]byte, embedded *embeddedFont) int { - fontFile := fmt.Appendf(nil, "<< /Length %d /Length1 %d >>\nstream\n", len(embedded.data), len(embedded.data)) - fontFile = append(fontFile, embedded.data...) - fontFile = append(fontFile, []byte("\nendstream")...) - fontFileID := appendPDFObject(objects, fontFile) - - unitsPerEm := int64(embedded.font.UnitsPerEm()) - fontBounds := "-1000 -1000 2000 2000" - ascent := int64(800) - descent := int64(-200) - capHeight := int64(700) - if unitsPerEm > 0 { - ppem := fixed.Int26_6(embedded.font.UnitsPerEm()) - if bounds, err := embedded.font.Bounds(nil, ppem, font.HintingNone); err == nil { - fontBounds = fmt.Sprintf("%d %d %d %d", - int64(bounds.Min.X)*1000/unitsPerEm, - -int64(bounds.Max.Y)*1000/unitsPerEm, - int64(bounds.Max.X)*1000/unitsPerEm, - -int64(bounds.Min.Y)*1000/unitsPerEm, - ) - } - if metrics, err := embedded.font.Metrics(nil, ppem, font.HintingNone); err == nil { - ascent = int64(metrics.Ascent) * 1000 / unitsPerEm - descent = -int64(metrics.Descent) * 1000 / unitsPerEm - capHeight = int64(metrics.CapHeight) * 1000 / unitsPerEm - } - } - - descriptorID := appendPDFObject(objects, []byte(fmt.Sprintf( - "<< /Type /FontDescriptor /FontName /%s /Flags 32 /FontBBox [%s] /ItalicAngle 0 /Ascent %d /Descent %d /CapHeight %d /StemV 80 /FontFile2 %d 0 R >>", - embedded.name, fontBounds, ascent, descent, capHeight, fontFileID, - ))) - - glyphs := make([]int, 0, len(embedded.glyphToRune)) - for glyph := range embedded.glyphToRune { - glyphs = append(glyphs, int(glyph)) - } - sort.Ints(glyphs) - widths := make([]string, 0, len(glyphs)) - for _, glyph := range glyphs { - width := int64(1000) - if unitsPerEm > 0 { - advance, err := embedded.font.GlyphAdvance(nil, sfnt.GlyphIndex(glyph), fixed.Int26_6(embedded.font.UnitsPerEm()), font.HintingNone) - if err == nil { - width = int64(advance) * 1000 / unitsPerEm - } - } - widths = append(widths, fmt.Sprintf("%d [%d]", glyph, width)) - } - cidFontID := appendPDFObject(objects, []byte(fmt.Sprintf( - "<< /Type /Font /Subtype /CIDFontType2 /BaseFont /%s /CIDSystemInfo << /Registry (Adobe) /Ordering (Identity) /Supplement 0 >> /FontDescriptor %d 0 R /DW 1000 /W [%s] /CIDToGIDMap /Identity >>", - embedded.name, descriptorID, strings.Join(widths, " "), - ))) - - toUnicode := buildToUnicodeCMap(embedded.glyphToRune) - toUnicodeObject := fmt.Appendf(nil, "<< /Length %d >>\nstream\n", len(toUnicode)) - toUnicodeObject = append(toUnicodeObject, toUnicode...) - toUnicodeObject = append(toUnicodeObject, []byte("\nendstream")...) - toUnicodeID := appendPDFObject(objects, toUnicodeObject) - - return appendPDFObject(objects, []byte(fmt.Sprintf( - "<< /Type /Font /Subtype /Type0 /BaseFont /%s /Encoding /Identity-H /DescendantFonts [%d 0 R] /ToUnicode %d 0 R >>", - embedded.name, cidFontID, toUnicodeID, - ))) -} - -func buildToUnicodeCMap(glyphToRune map[sfnt.GlyphIndex]rune) []byte { - glyphs := make([]int, 0, len(glyphToRune)) - for glyph := range glyphToRune { - glyphs = append(glyphs, int(glyph)) - } - sort.Ints(glyphs) - - var cmap bytes.Buffer - cmap.WriteString("/CIDInit /ProcSet findresource begin\n12 dict begin\nbegincmap\n/CIDSystemInfo << /Registry (Adobe) /Ordering (UCS) /Supplement 0 >> def\n/CMapName /Adobe-Identity-UCS def\n/CMapType 2 def\n1 begincodespacerange\n<0000> \nendcodespacerange\n") - for start := 0; start < len(glyphs); start += 100 { - end := min(start+100, len(glyphs)) - fmt.Fprintf(&cmap, "%d beginbfchar\n", end-start) - for _, glyph := range glyphs[start:end] { - fmt.Fprintf(&cmap, "<%04X> <%s>\n", glyph, utf16Hex(glyphToRune[sfnt.GlyphIndex(glyph)])) - } - cmap.WriteString("endbfchar\n") - } - cmap.WriteString("endcmap\nCMapName currentdict /CMap defineresource pop\nend\nend") - return cmap.Bytes() -} - -func utf16Hex(character rune) string { - var encoded strings.Builder - for _, unit := range utf16.Encode([]rune{character}) { - fmt.Fprintf(&encoded, "%04X", unit) - } - return encoded.String() -} - -func sanitizePDFFontName(name string) string { - var sanitized strings.Builder - for _, character := range name { - if character >= 'A' && character <= 'Z' || character >= 'a' && character <= 'z' || character >= '0' && character <= '9' { - sanitized.WriteRune(character) - } - } - if sanitized.Len() == 0 { - return "MiniPdfFont" - } - return sanitized.String() -} - -func appendPDFObject(objects *[][]byte, object []byte) int { - *objects = append(*objects, object) - return len(*objects) -} diff --git a/minipdf-go/go.mod b/minipdf-go/go.mod deleted file mode 100644 index 9279b431..00000000 --- a/minipdf-go/go.mod +++ /dev/null @@ -1,7 +0,0 @@ -module github.com/mini-software/MiniPdf/minipdf-go - -go 1.22 - -require golang.org/x/image v0.24.0 - -require golang.org/x/text v0.22.0 // indirect diff --git a/minipdf-go/go.sum b/minipdf-go/go.sum deleted file mode 100644 index 4fe2ad0e..00000000 --- a/minipdf-go/go.sum +++ /dev/null @@ -1,4 +0,0 @@ -golang.org/x/image v0.24.0 h1:AN7zRgVsbvmTfNyqIbbOraYL8mSwcKncEj8ofjgzcMQ= -golang.org/x/image v0.24.0/go.mod h1:4b/ITuLfqYq1hqZcjofwctIhi7sZh2WaCjvsBNjjya8= -golang.org/x/text v0.22.0 h1:bofq7m3/HAFvbF51jz3Q9wLg3jkvSPuiZu/pD1XwgtM= -golang.org/x/text v0.22.0/go.mod h1:YRoo4H8PVmsu+E3Ou7cqLVH8oXWIHVoX0jqUWALQhfY= diff --git a/minipdf-go/minipdf.go b/minipdf-go/minipdf.go deleted file mode 100644 index 47e78a0c..00000000 --- a/minipdf-go/minipdf.go +++ /dev/null @@ -1,232 +0,0 @@ -package minipdf - -import ( - "bytes" - "errors" - "fmt" - "io" - "math" - "os" - "path/filepath" - "strings" - "sync" -) - -var ( - ErrUnsupportedFormat = errors.New("unsupported or unknown Office document format") - ErrInvalidPackage = errors.New("invalid Office package") - ErrInvalidInput = errors.New("invalid input") - PageSizeA4 = PageSize{Width: 595.28, Height: 841.89} - PageSizeLetter = PageSize{Width: 612, Height: 792} -) - -type OfficeFormat string - -const ( - OfficeFormatUnknown OfficeFormat = "unknown" - OfficeFormatXLSX OfficeFormat = "xlsx" - OfficeFormatDOCX OfficeFormat = "docx" - OfficeFormatPPTX OfficeFormat = "pptx" -) - -type PageSize struct { - Width float64 - Height float64 -} - -func NewPageSize(width, height float64) (PageSize, error) { - if math.IsNaN(width) || math.IsNaN(height) || math.IsInf(width, 0) || math.IsInf(height, 0) || width <= 0 || height <= 0 { - return PageSize{}, fmt.Errorf("%w: page width and height must be positive finite values", ErrInvalidInput) - } - return PageSize{Width: width, Height: height}, nil -} - -type Margins struct { - Left float64 - Top float64 - Right float64 - Bottom float64 -} - -// NewMargins creates validated page margins measured in PDF points. -func NewMargins(left, top, right, bottom float64) (Margins, error) { - values := []float64{left, top, right, bottom} - for _, value := range values { - if math.IsNaN(value) || math.IsInf(value, 0) || value < 0 { - return Margins{}, fmt.Errorf("%w: margins must be non-negative finite values", ErrInvalidInput) - } - } - return Margins{Left: left, Top: top, Right: right, Bottom: bottom}, nil -} - -type ConversionOptions struct { - PageSize *PageSize - // Margins overrides DOCX page margins in PDF points. - Margins *Margins - // Compress applies Flate compression to PDF page content streams. - Compress bool - // MaxRows limits rendered worksheet rows. Zero leaves rows unlimited. - MaxRows int - // MaxColumns limits rendered worksheet columns. Zero leaves columns unlimited. - MaxColumns int - // Landscape overrides XLSX worksheet orientation when non-nil. - Landscape *bool -} - -type RegisteredFont struct { - Name string - Data []byte -} - -var fontRegistry struct { - sync.RWMutex - fonts []RegisteredFont -} - -func RegisterFont(name string, data []byte) { - fontRegistry.Lock() - defer fontRegistry.Unlock() - fontRegistry.fonts = append(fontRegistry.fonts, RegisteredFont{Name: name, Data: bytes.Clone(data)}) -} - -func RegisteredFonts() []RegisteredFont { - fontRegistry.RLock() - defer fontRegistry.RUnlock() - fonts := make([]RegisteredFont, len(fontRegistry.fonts)) - for index, font := range fontRegistry.fonts { - fonts[index] = RegisteredFont{Name: font.Name, Data: bytes.Clone(font.Data)} - } - return fonts -} - -// ClearRegisteredFonts removes all process-wide font registrations. -func ClearRegisteredFonts() { - fontRegistry.Lock() - defer fontRegistry.Unlock() - fontRegistry.fonts = nil -} - -// ConvertReaderToPDF reads an Office package and returns the converted PDF. -func ConvertReaderToPDF(input io.Reader) ([]byte, error) { - return ConvertReaderToPDFWithOptions(input, ConversionOptions{}) -} - -// ConvertReaderToPDFWithOptions reads an Office package and returns the converted PDF. -func ConvertReaderToPDFWithOptions(input io.Reader, options ConversionOptions) ([]byte, error) { - data, err := io.ReadAll(io.LimitReader(input, int64(defaultOfficePackageLimits.maxTotalSize)+1)) - if err != nil { - return nil, fmt.Errorf("read input: %w", err) - } - if uint64(len(data)) > defaultOfficePackageLimits.maxTotalSize { - return nil, fmt.Errorf("%w: input exceeds the configured size limit", ErrInvalidPackage) - } - return ConvertBytesToPDFWithOptions(data, options) -} - -// ConvertReaderToWriter converts an Office package and writes the PDF to output. -func ConvertReaderToWriter(input io.Reader, output io.Writer, options ConversionOptions) error { - pdf, err := ConvertReaderToPDFWithOptions(input, options) - if err != nil { - return err - } - if _, err := io.Copy(output, bytes.NewReader(pdf)); err != nil { - return fmt.Errorf("write PDF: %w", err) - } - return nil -} - -func DetectOfficeFormat(input []byte) (OfficeFormat, error) { - files, err := openOfficePackage(input) - if err != nil { - return OfficeFormatUnknown, err - } - for name := range files { - switch { - case strings.HasPrefix(name, "word/"): - return OfficeFormatDOCX, nil - case strings.HasPrefix(name, "xl/"): - return OfficeFormatXLSX, nil - case strings.HasPrefix(name, "ppt/"): - return OfficeFormatPPTX, nil - } - } - return OfficeFormatUnknown, nil -} - -func ConvertToPDF(inputPath, outputPath string) error { - return ConvertToPDFWithOptions(inputPath, outputPath, ConversionOptions{}) -} - -func ConvertToPDFWithOptions(inputPath, outputPath string, options ConversionOptions) error { - pdf, err := ConvertToPDFBytesWithOptions(inputPath, options) - if err != nil { - return err - } - if err := os.WriteFile(outputPath, pdf, 0o644); err != nil { - return fmt.Errorf("write PDF: %w", err) - } - return nil -} - -func ConvertToPDFBytes(inputPath string) ([]byte, error) { - return ConvertToPDFBytesWithOptions(inputPath, ConversionOptions{}) -} - -func ConvertToPDFBytesWithOptions(inputPath string, options ConversionOptions) ([]byte, error) { - input, err := os.ReadFile(inputPath) - if err != nil { - return nil, fmt.Errorf("read input: %w", err) - } - extension := strings.ToLower(filepath.Ext(inputPath)) - format := OfficeFormatUnknown - switch extension { - case ".docx": - format = OfficeFormatDOCX - case ".xlsx": - format = OfficeFormatXLSX - case ".pptx": - format = OfficeFormatPPTX - } - return convertBytesAs(input, format, options) -} - -func ConvertBytesToPDF(input []byte) ([]byte, error) { - return ConvertBytesToPDFWithOptions(input, ConversionOptions{}) -} - -func ConvertBytesToPDFWithOptions(input []byte, options ConversionOptions) ([]byte, error) { - format, err := DetectOfficeFormat(input) - if err != nil { - return nil, err - } - return convertBytesAs(input, format, options) -} - -func convertBytesAs(input []byte, format OfficeFormat, options ConversionOptions) ([]byte, error) { - if format == OfficeFormatUnknown { - detected, err := DetectOfficeFormat(input) - if err != nil { - return nil, err - } - format = detected - } - if options.Margins != nil && format != OfficeFormatDOCX { - return nil, fmt.Errorf("%w: margin overrides apply only to DOCX input", ErrInvalidInput) - } - if options.MaxRows < 0 || options.MaxColumns < 0 { - return nil, fmt.Errorf("%w: XLSX row and column limits cannot be negative", ErrInvalidInput) - } - if format != OfficeFormatXLSX && (options.MaxRows != 0 || options.MaxColumns != 0 || options.Landscape != nil) { - return nil, fmt.Errorf("%w: worksheet limits and orientation apply only to XLSX input", ErrInvalidInput) - } - switch format { - case OfficeFormatDOCX: - return convertDOCX(input, options) - case OfficeFormatXLSX: - return convertXLSX(input, options) - case OfficeFormatPPTX: - return convertPPTX(input, options) - default: - return nil, ErrUnsupportedFormat - } -} diff --git a/minipdf-go/minipdf_test.go b/minipdf-go/minipdf_test.go deleted file mode 100644 index 9d38bbf4..00000000 --- a/minipdf-go/minipdf_test.go +++ /dev/null @@ -1,133 +0,0 @@ -package minipdf - -import ( - "archive/zip" - "bytes" - "errors" - "io" - "math" - "testing" -) - -func TestClearRegisteredFonts(t *testing.T) { - ClearRegisteredFonts() - t.Cleanup(ClearRegisteredFonts) - RegisterFont("Example", []byte("font data")) - - ClearRegisteredFonts() - - if fonts := RegisteredFonts(); len(fonts) != 0 { - t.Fatalf("RegisteredFonts() returned %d fonts after clear", len(fonts)) - } -} - -func TestConvertReaderToWriter(t *testing.T) { - input := zipPackage(t, "word/document.xml", `Hello stream`) - expected, err := ConvertBytesToPDF(input) - if err != nil { - t.Fatal(err) - } - - var output bytes.Buffer - if err := ConvertReaderToWriter(bytes.NewReader(input), &output, ConversionOptions{}); err != nil { - t.Fatal(err) - } - if !bytes.Equal(output.Bytes(), expected) { - t.Fatal("stream conversion differs from byte conversion") - } -} - -func TestConvertReaderToWriterPropagatesIOErrors(t *testing.T) { - _, err := ConvertReaderToPDF(errorReader{}) - if !errors.Is(err, errTestIO) { - t.Fatalf("ConvertReaderToPDF() error = %v, want errTestIO", err) - } - - input := zipPackage(t, "word/document.xml", ``) - err = ConvertReaderToWriter(bytes.NewReader(input), errorWriter{}, ConversionOptions{}) - if !errors.Is(err, errTestIO) { - t.Fatalf("ConvertReaderToWriter() error = %v, want errTestIO", err) - } -} - -var errTestIO = errors.New("test I/O error") - -type errorReader struct{} - -func (errorReader) Read([]byte) (int, error) { - return 0, errTestIO -} - -type errorWriter struct{} - -func (errorWriter) Write([]byte) (int, error) { - return 0, errTestIO -} - -var _ io.Reader = errorReader{} -var _ io.Writer = errorWriter{} - -func TestDetectOfficeFormat(t *testing.T) { - tests := []struct { - name string - entry string - format OfficeFormat - }{ - {name: "docx", entry: "word/document.xml", format: OfficeFormatDOCX}, - {name: "xlsx", entry: "xl/workbook.xml", format: OfficeFormatXLSX}, - {name: "pptx", entry: "ppt/presentation.xml", format: OfficeFormatPPTX}, - {name: "unknown", entry: "custom/data.xml", format: OfficeFormatUnknown}, - } - - for _, test := range tests { - t.Run(test.name, func(t *testing.T) { - format, err := DetectOfficeFormat(zipPackage(t, test.entry, "")) - if err != nil { - t.Fatalf("DetectOfficeFormat() error = %v", err) - } - if format != test.format { - t.Fatalf("DetectOfficeFormat() = %q, want %q", format, test.format) - } - }) - } -} - -func TestNewPageSizeRejectsInvalidDimensions(t *testing.T) { - for _, dimensions := range [][2]float64{{0, 100}, {-1, 100}, {100, math.Inf(1)}} { - if _, err := NewPageSize(dimensions[0], dimensions[1]); err == nil { - t.Fatalf("NewPageSize(%v, %v) succeeded", dimensions[0], dimensions[1]) - } - } -} - -func TestNewMarginsRejectsInvalidDimensions(t *testing.T) { - for _, margins := range [][4]float64{{-1, 0, 0, 0}, {0, math.Inf(1), 0, 0}} { - if _, err := NewMargins(margins[0], margins[1], margins[2], margins[3]); !errors.Is(err, ErrInvalidInput) { - t.Fatalf("NewMargins%v error = %v, want ErrInvalidInput", margins, err) - } - } -} - -func TestUnknownPackageIsUnsupported(t *testing.T) { - _, err := ConvertBytesToPDF(zipPackage(t, "custom/data.xml", "")) - if !errors.Is(err, ErrUnsupportedFormat) { - t.Fatalf("ConvertBytesToPDF() error = %v, want ErrUnsupportedFormat", err) - } -} - -func zipPackage(t *testing.T, name, content string) []byte { - t.Helper() - var buffer bytes.Buffer - writer := zip.NewWriter(&buffer) - file, err := writer.Create(name) - if err != nil { - t.Fatal(err) - } - if _, err := file.Write([]byte(content)); err != nil { - t.Fatal(err) - } - if err := writer.Close(); err != nil { - t.Fatal(err) - } - return buffer.Bytes() -} diff --git a/minipdf-go/office.go b/minipdf-go/office.go deleted file mode 100644 index af910f14..00000000 --- a/minipdf-go/office.go +++ /dev/null @@ -1,324 +0,0 @@ -package minipdf - -import ( - "archive/zip" - "bytes" - "encoding/xml" - "fmt" - "io" - "path" - "sort" - "strconv" - "strings" - "unicode" -) - -type officePackage map[string]*zip.File - -type officePackageLimits struct { - maxEntries int - maxEntrySize uint64 - maxTotalSize uint64 - maxExpansionRate uint64 -} - -var defaultOfficePackageLimits = officePackageLimits{ - maxEntries: 10_000, - maxEntrySize: 128 * 1024 * 1024, - maxTotalSize: 512 * 1024 * 1024, - maxExpansionRate: 200, -} - -type textPage struct { - lines []string - size PageSize - margins Margins - noWrap bool - skipEmpty bool -} - -func openOfficePackage(input []byte) (officePackage, error) { - reader, err := zip.NewReader(bytes.NewReader(input), int64(len(input))) - if err != nil { - return nil, fmt.Errorf("%w: open ZIP package: %v", ErrInvalidPackage, err) - } - return validateOfficePackage(reader.File, uint64(len(input)), defaultOfficePackageLimits) -} - -func validateOfficePackage(entries []*zip.File, inputSize uint64, limits officePackageLimits) (officePackage, error) { - if len(entries) > limits.maxEntries { - return nil, fmt.Errorf("%w: ZIP package contains too many entries", ErrInvalidPackage) - } - files := make(officePackage, len(entries)) - seen := make(map[string]struct{}, len(entries)) - var totalSize uint64 - for _, file := range entries { - name, err := normalizePackagePath(file.Name) - if err != nil { - return nil, err - } - if _, exists := seen[name]; exists { - return nil, fmt.Errorf("%w: ZIP package contains duplicate entry %q", ErrInvalidPackage, name) - } - seen[name] = struct{}{} - if file.Flags&0x1 != 0 { - return nil, fmt.Errorf("%w: encrypted entry %q is not supported", ErrInvalidPackage, name) - } - if file.UncompressedSize64 > limits.maxEntrySize { - return nil, fmt.Errorf("%w: ZIP entry %q expands beyond the configured limit", ErrInvalidPackage, name) - } - if exceedsExpansionRatio(file.UncompressedSize64, file.CompressedSize64, limits.maxExpansionRate) { - return nil, fmt.Errorf("%w: ZIP entry %q exceeds the configured expansion ratio", ErrInvalidPackage, name) - } - if totalSize > limits.maxTotalSize || file.UncompressedSize64 > limits.maxTotalSize-totalSize { - return nil, fmt.Errorf("%w: ZIP package expands beyond the configured limit", ErrInvalidPackage) - } - totalSize += file.UncompressedSize64 - if exceedsExpansionRatio(totalSize, inputSize, limits.maxExpansionRate) { - return nil, fmt.Errorf("%w: ZIP package exceeds the configured expansion ratio", ErrInvalidPackage) - } - if !file.FileInfo().IsDir() { - files[name] = file - } - } - return files, nil -} - -func exceedsExpansionRatio(uncompressedSize, compressedSize, maximum uint64) bool { - if uncompressedSize == 0 { - return false - } - if compressedSize == 0 || maximum == 0 { - return true - } - return (uncompressedSize+maximum-1)/maximum > compressedSize -} - -func normalizePackagePath(name string) (string, error) { - normalized := strings.ReplaceAll(name, `\`, "/") - if strings.HasPrefix(normalized, "/") || strings.Contains(normalized, ":") || strings.ContainsRune(normalized, '\x00') { - return "", fmt.Errorf("%w: ZIP package contains unsafe entry path %q", ErrInvalidPackage, name) - } - for _, segment := range strings.Split(normalized, "/") { - if segment == ".." { - return "", fmt.Errorf("%w: ZIP package contains unsafe entry path %q", ErrInvalidPackage, name) - } - } - return normalized, nil -} - -func (files officePackage) read(name string) ([]byte, error) { - file, ok := files[name] - if !ok { - return nil, fmt.Errorf("Office package part %q is missing", name) - } - reader, err := file.Open() - if err != nil { - return nil, fmt.Errorf("open Office package part %q: %w", name, err) - } - defer reader.Close() - data, err := io.ReadAll(io.LimitReader(reader, int64(defaultOfficePackageLimits.maxEntrySize)+1)) - if err != nil { - return nil, fmt.Errorf("read Office package part %q: %w", name, err) - } - if uint64(len(data)) > defaultOfficePackageLimits.maxEntrySize { - return nil, fmt.Errorf("read Office package part %q: entry expands beyond the configured limit", name) - } - return data, nil -} - -func renderTextPages(pages []textPage, options ConversionOptions) []byte { - document := NewPDFDocument() - for _, sourcePage := range pages { - pageSize := sourcePage.size - if options.PageSize != nil { - pageSize = *options.PageSize - } - margins := sourcePage.margins - if options.Margins != nil { - margins = *options.Margins - } - addTextPages(document, sourcePage.lines, pageSize, margins, sourcePage.noWrap, sourcePage.skipEmpty, 0) - } - return document.BytesWithOptions(PDFSaveOptions{Compress: options.Compress}) -} - -// 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 - -// 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, down to minimumTextFitZoom, until it fits that many pages. -func addTextPages(document *PDFDocument, lines []string, pageSize PageSize, margins Margins, noWrap, skipEmpty bool, fitHeight int) { - if margins == (Margins{}) { - margins = Margins{Left: 54, Top: 54, Right: 54, Bottom: 54} - } - 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 - } - zoom := 100 - if fitHeight > 0 { - // Like ScPrintFunc::CalcZoom, keep 100% when the content already fits - // and otherwise search for the largest zoom that does. - // 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 { - leading := baseLeading * float64(zoom) / 100 - pages := 0 - pageHasText := false - if !skipEmpty { - pages = 1 - pageHasText = true - } - y := pageSize.Height - margins.Top - for _, line := range wrapAt(zoom) { - if y < margins.Bottom { - 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) { - 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 - } - } - } - } - } - wrapped := wrapAt(zoom) - fontSize := baseFontSize * float64(zoom) / 100 - leading := baseLeading * float64(zoom) / 100 - - var page *PDFPage - if !skipEmpty { - page = document.AddPage(pageSize.Width, pageSize.Height) - } - y := pageSize.Height - margins.Top - for _, line := range wrapped { - if y < margins.Bottom { - page = nil - y = pageSize.Height - margins.Top - } - if !skipEmpty || strings.TrimSpace(line) != "" { - if page == nil { - page = document.AddPage(pageSize.Width, pageSize.Height) - } - page.AddText(line, margins.Left, y, fontSize, PDFColorBlack, false) - } - y -= leading - } -} - -func textCharactersPerLine(pageSize PageSize, margins Margins, fontSize float64) int { - if margins == (Margins{}) { - margins = Margins{Left: 54, Top: 54, Right: 54, Bottom: 54} - } - maximum := int((pageSize.Width - margins.Left - margins.Right) / (fontSize * 0.52)) - if maximum < 10 { - return 10 - } - return maximum -} - -func wrapText(text string, limit int) []string { - if text == "" { - return []string{""} - } - var lines []string - for _, explicitLine := range strings.Split(text, "\n") { - runes := []rune(explicitLine) - for len(runes) > limit { - breakAt := limit - for index := limit; index > 0; index-- { - if unicode.IsSpace(runes[index-1]) { - breakAt = index - break - } - } - lines = append(lines, strings.TrimSpace(string(runes[:breakAt]))) - runes = runes[breakAt:] - for len(runes) > 0 && unicode.IsSpace(runes[0]) { - runes = runes[1:] - } - } - lines = append(lines, string(runes)) - } - return lines -} - -func attrValue(start xml.StartElement, localName string) string { - for _, attribute := range start.Attr { - if attribute.Name.Local == localName { - return attribute.Value - } - } - return "" -} - -func sortedPackageParts(files officePackage, prefix, extension string) []string { - var names []string - for name := range files { - if strings.HasPrefix(name, prefix) && strings.HasSuffix(name, extension) && !strings.Contains(name, "/_rels/") { - names = append(names, name) - } - } - sort.Slice(names, func(left, right int) bool { - leftNumber := trailingNumber(strings.TrimSuffix(path.Base(names[left]), extension)) - rightNumber := trailingNumber(strings.TrimSuffix(path.Base(names[right]), extension)) - if leftNumber == rightNumber { - return names[left] < names[right] - } - return leftNumber < rightNumber - }) - return names -} - -func trailingNumber(value string) int { - start := len(value) - for start > 0 && value[start-1] >= '0' && value[start-1] <= '9' { - start-- - } - number, err := strconv.Atoi(value[start:]) - if err != nil { - return 0 - } - return number -} diff --git a/minipdf-go/office_test.go b/minipdf-go/office_test.go deleted file mode 100644 index 44fe44e6..00000000 --- a/minipdf-go/office_test.go +++ /dev/null @@ -1,1124 +0,0 @@ -package minipdf - -import ( - "archive/zip" - "bytes" - "encoding/xml" - "errors" - "fmt" - "math" - "slices" - "strings" - "testing" -) - -func TestOpenOfficePackageRejectsUnsafePaths(t *testing.T) { - input := officePackageEntries(t, []packageEntry{ - {name: "word/document.xml", content: ""}, - {name: "../escape.xml", content: ""}, - }) - - _, err := openOfficePackage(input) - assertPackageErrorContains(t, err, "unsafe entry path") - if !errors.Is(err, ErrInvalidPackage) { - t.Fatalf("error = %v, want ErrInvalidPackage", err) - } -} - -func TestOpenOfficePackageRejectsDuplicateNormalizedPaths(t *testing.T) { - input := officePackageEntries(t, []packageEntry{ - {name: "word/document.xml", content: ""}, - {name: `word\document.xml`, content: ""}, - }) - - _, err := openOfficePackage(input) - assertPackageErrorContains(t, err, "duplicate entry") -} - -func TestValidateOfficePackageLimits(t *testing.T) { - baseLimits := officePackageLimits{ - maxEntries: 10, - maxEntrySize: 100, - maxTotalSize: 200, - maxExpansionRate: 10, - } - tests := []struct { - name string - entries []*zip.File - inputSize uint64 - limits officePackageLimits - message string - }{ - { - name: "entry count", - entries: []*zip.File{ - zipFile("word/document.xml", 1, 1, 0), - zipFile("word/styles.xml", 1, 1, 0), - }, - inputSize: 2, - limits: officePackageLimits{maxEntries: 1, maxEntrySize: 100, maxTotalSize: 200, maxExpansionRate: 10}, - message: "too many entries", - }, - { - name: "entry size", - entries: []*zip.File{zipFile("word/document.xml", 10, 101, 0)}, - inputSize: 10, - limits: baseLimits, - message: "entry \"word/document.xml\" expands beyond", - }, - { - name: "total size", - entries: []*zip.File{ - zipFile("word/document.xml", 60, 60, 0), - zipFile("word/styles.xml", 60, 60, 0), - }, - inputSize: 120, - limits: officePackageLimits{maxEntries: 10, maxEntrySize: 100, maxTotalSize: 100, maxExpansionRate: 10}, - message: "package expands beyond", - }, - { - name: "entry expansion ratio", - entries: []*zip.File{zipFile("word/document.xml", 10, 101, 0)}, - inputSize: 101, - limits: officePackageLimits{maxEntries: 10, maxEntrySize: 200, maxTotalSize: 200, maxExpansionRate: 10}, - message: "entry \"word/document.xml\" exceeds", - }, - { - name: "package expansion ratio", - entries: []*zip.File{zipFile("word/document.xml", 30, 30, 0)}, - inputSize: 2, - limits: baseLimits, - message: "package exceeds", - }, - { - name: "encrypted entry", - entries: []*zip.File{zipFile("word/document.xml", 1, 1, 0x1)}, - inputSize: 1, - limits: baseLimits, - message: "encrypted entry", - }, - } - - for _, test := range tests { - t.Run(test.name, func(t *testing.T) { - _, err := validateOfficePackage(test.entries, test.inputSize, test.limits) - assertPackageErrorContains(t, err, test.message) - if !errors.Is(err, ErrInvalidPackage) { - t.Fatalf("error = %v, want ErrInvalidPackage", err) - } - }) - } -} - -func TestConvertDOCXToPDF(t *testing.T) { - input := officePackageBytes(t, map[string]string{ - "word/document.xml": `Hello DOCX`, - }) - - pdf, err := ConvertBytesToPDF(input) - assertPDFContains(t, pdf, err, "Hello DOCX", "/MediaBox [0 0 612 792]") -} - -func TestConversionCompressionOption(t *testing.T) { - input := officePackageBytes(t, map[string]string{ - "word/document.xml": `Hello compressed DOCX`, - }) - - pdf, err := ConvertBytesToPDFWithOptions(input, ConversionOptions{Compress: true}) - assertPDFContains(t, pdf, err, "/Filter /FlateDecode") -} - -func TestDOCXSectionMarginsAndOverride(t *testing.T) { - input := officePackageBytes(t, map[string]string{ - "word/document.xml": `Margin text`, - }) - - pdf, err := ConvertBytesToPDF(input) - assertPDFContains(t, pdf, err, "72 756 Td") - - margins, err := NewMargins(20, 30, 40, 50) - if err != nil { - t.Fatal(err) - } - pdf, err = ConvertBytesToPDFWithOptions(input, ConversionOptions{Margins: &margins}) - assertPDFContains(t, pdf, err, "20 762 Td") -} - -func TestDOCXMarginOverrideIsFormatSpecific(t *testing.T) { - input := officePackageBytes(t, map[string]string{ - "xl/workbook.xml": ``, - "xl/worksheets/sheet1.xml": ``, - }) - margins, err := NewMargins(20, 30, 40, 50) - if err != nil { - t.Fatal(err) - } - - _, err = ConvertBytesToPDFWithOptions(input, ConversionOptions{Margins: &margins}) - if !errors.Is(err, ErrInvalidInput) { - t.Fatalf("error = %v, want ErrInvalidInput", err) - } -} - -func TestDOCXMarginOverrideRejectsInvalidLayout(t *testing.T) { - input := officePackageBytes(t, map[string]string{ - "word/document.xml": `Margin text`, - }) - invalidMargins := []Margins{ - {Left: -1}, - {Left: 400, Right: 300}, - {Top: 500, Bottom: 400}, - } - for _, margins := range invalidMargins { - _, err := ConvertBytesToPDFWithOptions(input, ConversionOptions{Margins: &margins}) - if !errors.Is(err, ErrInvalidInput) { - t.Fatalf("margins = %#v, error = %v, want ErrInvalidInput", margins, err) - } - } -} - -func TestConvertXLSXToPDF(t *testing.T) { - input := officePackageBytes(t, map[string]string{ - "xl/workbook.xml": ``, - "xl/sharedStrings.xml": `Hello XLSX`, - "xl/worksheets/sheet1.xml": `0Cell B` + - ``, - }) - - pdf, err := ConvertBytesToPDF(input) - assertPDFContains(t, pdf, err, "Hello XLSX", "Cell B", "/MediaBox [0 0 792 612]") - if bytes.Contains(pdf, []byte("Sheet 1")) { - t.Fatal("PDF contains a synthetic worksheet title") - } -} - -func TestConvertXLSXSkipsEmptyWorksheets(t *testing.T) { - mixed := officePackageBytes(t, map[string]string{ - "xl/workbook.xml": ``, - "xl/worksheets/sheet1.xml": ``, - "xl/worksheets/sheet2.xml": `` + - `First sheet`, - "xl/worksheets/sheet3.xml": ``, - "xl/worksheets/sheet4.xml": `` + - `Second sheet`, - }) - - pdf, err := ConvertBytesToPDF(mixed) - assertPDFContains(t, pdf, err, "First sheet", "Second sheet") - if pages := bytes.Count(pdf, []byte("/Type /Page ")); pages != 2 { - t.Fatalf("mixed workbook page count = %d, want 2", pages) - } - - allEmpty := officePackageBytes(t, map[string]string{ - "xl/workbook.xml": ``, - "xl/worksheets/sheet1.xml": ``, - "xl/worksheets/sheet2.xml": ``, - }) - pdf, err = ConvertBytesToPDF(allEmpty) - if err != nil { - t.Fatal(err) - } - if pages := bytes.Count(pdf, []byte("/Type /Page ")); pages != 1 { - t.Fatalf("empty workbook page count = %d, want 1", pages) - } - - layoutOnly := officePackageBytes(t, map[string]string{ - "xl/workbook.xml": ``, - "xl/worksheets/sheet1.xml": `` + - `Data`, - "xl/worksheets/sheet2.xml": `` + - ``, - "xl/worksheets/sheet3.xml": ``, - }) - pdf, err = ConvertBytesToPDF(layoutOnly) - if err != nil { - t.Fatal(err) - } - if pages := bytes.Count(pdf, []byte("/Type /Page ")); pages != 2 { - t.Fatalf("layout-only workbook page count = %d, want 2", pages) - } -} - -func TestConvertXLSXSkipsHiddenWorksheets(t *testing.T) { - sheet := func(text string) string { - return `` + - `` + text + `` - } - entries := map[string]string{ - "xl/workbook.xml": `` + - `` + - `` + - `` + - `` + - ``, - "xl/_rels/workbook.xml.rels": `` + - `` + - `` + - `` + - `` + - ``, - "xl/worksheets/sheet1.xml": sheet("Visible report"), - "xl/worksheets/data.xml": sheet("Hidden lookup"), - "xl/worksheets/sheet3.xml": sheet("Very hidden internal"), - "xl/worksheets/sheet2.xml": sheet("Visible summary"), - "xl/worksheets/sheet5.xml": sheet("Orphan worksheet"), - } - - for _, renderer := range []string{"text", "grid"} { - t.Run(renderer, func(t *testing.T) { - if renderer == "grid" { - entries["xl/styles.xml"] = `` - entries["xl/worksheets/sheet1.xml"] = strings.Replace( - entries["xl/worksheets/sheet1.xml"], ``, - `1+1`, 1) - if !needsCalculatedXLSXGrid([]byte(entries["xl/worksheets/sheet1.xml"])) { - t.Fatal("fixture does not select the grid renderer") - } - } - pdf, err := ConvertBytesToPDF(officePackageBytes(t, entries)) - assertPDFContains(t, pdf, err, "Visible report", "Visible summary") - for _, text := range []string{"Hidden lookup", "Very hidden internal", "Orphan worksheet"} { - if bytes.Contains(pdf, []byte(text)) { - t.Fatalf("PDF contains excluded worksheet text %q", text) - } - } - if pages := bytes.Count(pdf, []byte("/Type /Page ")); pages != 2 { - t.Fatalf("page count = %d, want 2", pages) - } - }) - } -} - -func TestConvertXLSXSkipsEmptyTextPages(t *testing.T) { - tests := []struct { - name string - cell string - }{ - {name: "empty rows", cell: "A"}, - {name: "empty horizontal groups", cell: "J"}, - } - 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": `` + - `First` + - `Middle` + - `Last` + - `` + - ``, - }) - pdf, err := ConvertBytesToPDF(input) - assertPDFContains(t, pdf, err, "First", "Middle", "Last") - if pages := bytes.Count(pdf, []byte("/Type /Page ")); pages != 3 { - t.Fatalf("page count = %d, want 3 nonempty pages", pages) - } - }) - } -} - -func TestTextPaginationPreservesSpacingWhenSkippingEmptyPages(t *testing.T) { - lines := make([]string, 510) - lines[0], lines[100], lines[152] = "First", "Middle", "Last" - for _, skipEmpty := range []bool{false, true} { - document := NewPDFDocument() - addTextPages(document, lines, PageSizeA4, Margins{}, true, skipEmpty, 0) - pdf := document.Bytes() - wantPages := 11 - if skipEmpty { - wantPages = 3 - } - if pages := bytes.Count(pdf, []byte("/Type /Page ")); pages != wantPages { - t.Fatalf("skipEmpty=%v: pages = %d, want %d", skipEmpty, pages, wantPages) - } - assertPDFContains(t, pdf, nil, "54 787.89 Td", "54 757.89 Td", "54 712.89 Td") - } -} - -func TestConvertXLSXRejectsMalformedWorkbookMetadata(t *testing.T) { - tests := []struct { - name string - part string - xml string - }{ - { - name: "workbook", - part: "xl/workbook.xml", - xml: ``, - }, - { - name: "truncated workbook after visible sheet", - part: "xl/workbook.xml", - xml: ``, - }, - { - name: "relationships", - part: "xl/_rels/workbook.xml.rels", - xml: ``, - }, - } - for _, test := range tests { - t.Run(test.name, func(t *testing.T) { - entries := map[string]string{ - "xl/workbook.xml": ``, - "xl/worksheets/sheet1.xml": ``, - } - entries[test.part] = test.xml - pdf, err := ConvertBytesToPDF(officePackageBytes(t, entries)) - assertPackageErrorContains(t, err, "parse "+test.part+":") - var syntaxError *xml.SyntaxError - if !errors.As(err, &syntaxError) { - t.Fatalf("error = %v, want wrapped XML syntax error", err) - } - if len(pdf) != 0 { - t.Fatal("failed conversion returned PDF data") - } - }) - } -} - -func TestConvertXLSXResolvesHiddenWorksheetParts(t *testing.T) { - const ( - visibleA = `` - hiddenA = `` - hiddenB = `` - visibleB = `` - first = `` - second = `` - ) - tests := []struct { - name string - sheets string - relationships []string - parts [2]string - present []string - absent []string - pages int - }{ - { - name: "missing relationships map sheets to non-contiguous parts by position", - sheets: hiddenA + visibleB, - parts: [2]string{"sheet2.xml", "sheet3.xml"}, - present: []string{"Second part"}, absent: []string{"First part"}, pages: 1, - }, - { - name: "missing relationships map sheets to custom part names by position", - sheets: hiddenA + visibleB, - parts: [2]string{"data.xml", "summary.xml"}, - present: []string{"Second part"}, absent: []string{"First part"}, pages: 1, - }, - { - name: "missing relationships with more sheets than parts", - sheets: visibleA + hiddenB + ``, - present: []string{"First part"}, absent: []string{"Second part"}, pages: 1, - }, - { - name: "visible sheet whose target is not a worksheet part is kept", - sheets: visibleA + hiddenB, - relationships: []string{``, second}, - present: []string{"First part"}, absent: []string{"Second part"}, pages: 1, - }, - { - name: "missing relationships map sheets to parts by position", - sheets: visibleA + hiddenB, - present: []string{"First part"}, absent: []string{"Second part"}, pages: 1, - }, - { - name: "hidden sheet with a dangling relationship id is not rendered", - sheets: visibleA + ``, - relationships: []string{``}, - present: []string{"Second part"}, absent: []string{"First part"}, pages: 1, - }, - { - name: "visible sheet with a dangling relationship id is kept", - sheets: `` + hiddenB, - relationships: []string{second}, - present: []string{"First part"}, absent: []string{"Second part"}, pages: 1, - }, - { - name: "visible sheet whose target matches no part is kept", - sheets: visibleA + hiddenB, - relationships: []string{``, second}, - present: []string{"First part"}, absent: []string{"Second part"}, pages: 1, - }, - { - name: "relationship targets match part names case-insensitively", - sheets: visibleA + hiddenB, - relationships: []string{first, ``}, - present: []string{"First part"}, absent: []string{"Second part"}, pages: 1, - }, - { - name: "all sheets hidden produce one blank page", - sheets: hiddenA + hiddenB, - relationships: []string{first, second}, - absent: []string{"First part", "Second part"}, pages: 1, - }, - { - name: "all sheets hidden without relationships produce one blank page", - sheets: hiddenA + hiddenB, - absent: []string{"First part", "Second part"}, pages: 1, - }, - { - name: "all sheets hidden with non-contiguous parts produce one blank page", - sheets: hiddenA + hiddenB, - parts: [2]string{"sheet2.xml", "sheet3.xml"}, - absent: []string{"First part", "Second part"}, pages: 1, - }, - } - for _, test := range tests { - t.Run(test.name, func(t *testing.T) { - parts := test.parts - if parts == [2]string{} { - parts = [2]string{"sheet1.xml", "sheet2.xml"} - } - entries := map[string]string{ - "xl/workbook.xml": `` + - test.sheets + ``, - "xl/worksheets/" + parts[0]: `First part`, - "xl/worksheets/" + parts[1]: `Second part`, - } - if test.relationships != nil { - entries["xl/_rels/workbook.xml.rels"] = `` + strings.Join(test.relationships, "") + `` - } - pdf, err := ConvertBytesToPDF(officePackageBytes(t, entries)) - assertPDFContains(t, pdf, err, test.present...) - for _, text := range test.absent { - if bytes.Contains(pdf, []byte(text)) { - t.Fatalf("PDF contains hidden worksheet text %q", text) - } - } - if pages := bytes.Count(pdf, []byte("/Type /Page ")); pages != test.pages { - t.Fatalf("page count = %d, want %d", pages, test.pages) - } - }) - } -} - -func TestSplitWorksheetColumnGroups(t *testing.T) { - lines := []string{ - "A\tB\tC\tD\tE\tF\tG\tH\tI\tJ", - "A1\tB1\tC1\tD1\tE1\tF1\tG1\tH1\tI1\tJ1", - } - - groups := splitWorksheetColumnGroups(lines, 9) - - if len(groups) != 2 { - t.Fatalf("group count = %d, want 2", len(groups)) - } - if groups[0][0] != "A\tB\tC\tD\tE\tF\tG\tH\tI" || groups[1][0] != "J" { - t.Fatalf("groups = %#v", groups) - } -} - -func TestSplitWorksheetTextOverflow(t *testing.T) { - pages := splitWorksheetTextOverflow([]string{"Header", "ABCDEFGHIJK", "Short"}, 5) - - if len(pages) != 3 { - t.Fatalf("page count = %d, want 3", len(pages)) - } - want := [][]string{ - {"Heade", "ABCDE", "Short"}, - {"r", "FGHIJ", ""}, - {"", "K", ""}, - } - for index := range want { - if strings.Join(pages[index], "|") != strings.Join(want[index], "|") { - t.Errorf("page %d = %#v, want %#v", index, pages[index], want[index]) - } - } -} - -func TestConvertXLSXPaginatesSingleColumnTextOverflow(t *testing.T) { - input := officePackageBytes(t, map[string]string{ - "xl/workbook.xml": ``, - "xl/worksheets/sheet1.xml": `` + - strings.Repeat("X", 1000) + ``, - }) - - pdf, err := ConvertBytesToPDF(input) - if err != nil { - t.Fatal(err) - } - if pages := bytes.Count(pdf, []byte("/Type /Page ")); pages != 12 { - t.Fatalf("PDF page count = %d, want 12", pages) - } -} - -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 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: "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 { - 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 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": ``, - "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` + - `Fifth` + - `Tenth` + - ``) - - lines, _, _, err := extractWorksheet(worksheet, nil) - if err != nil { - t.Fatal(err) - } - if len(lines) != 10 { - t.Fatalf("line count = %d, want 10", len(lines)) - } - if lines[0] != "First" || lines[4] != "Fifth" || lines[9] != "Tenth" { - t.Fatalf("sparse row values = %#v", lines) - } -} - -func TestExtractWorksheetPreservesSparseColumns(t *testing.T) { - worksheet := []byte(`` + - `Left` + - `Right` + - `Data` + - `Far` + - ``) - - lines, _, _, err := extractWorksheet(worksheet, nil) - if err != nil { - t.Fatal(err) - } - if lines[0] != "Left\t\t\tRight" || lines[1] != "Data\t\t\t\t\t\t\t\t\tFar" { - t.Fatalf("sparse columns = %#v", lines) - } -} - -func TestExtractWorksheetFormatsBooleanCells(t *testing.T) { - worksheet := []byte(`` + - `10` + - `1`) - - lines, _, _, err := extractWorksheet(worksheet, nil) - if err != nil { - t.Fatal(err) - } - if len(lines) != 1 || lines[0] != "TRUE\tFALSE\t1" { - t.Fatalf("boolean row = %#v, want TRUE, FALSE, and numeric 1", lines) - } -} - -func TestConvertXLSXRendersCellStylesAndDimensions(t *testing.T) { - input := officePackageBytes(t, map[string]string{ - "xl/workbook.xml": ``, - "xl/styles.xml": `` + - `` + - `` + - `` + - `` + - ``, - "xl/worksheets/sheet1.xml": `` + - `` + - `HEADER` + - `BudgetSUM(B3:B4)` + - `2000025000` + - `` + - ``, - }) - files, err := openOfficePackage(input) - if err != nil { - t.Fatal(err) - } - worksheet, err := files.read("xl/worksheets/sheet1.xml") - if err != nil { - t.Fatal(err) - } - grid, err := readXLSXGrid(worksheet, nil) - if err != nil { - t.Fatal(err) - } - if grid.maxColumn != 2 || grid.maxRow != 4 { - t.Fatalf("printable grid = %dx%d, want 2x4", grid.maxColumn, grid.maxRow) - } - - pdf, err := ConvertBytesToPDF(input) - assertPDFContains(t, pdf, err, "HEADER", "45,000.00", "0.12156862745098039 0.3058823529411765 0.4745098039215686 rg", " re f", " RG ") -} - -func TestRenderXLSXCellMapsCalibriMetricsAndVerticalAlignment(t *testing.T) { - style := xlsxStyle{font: xlsxFont{name: "Calibri", size: 11, color: PDFColorBlack}} - page := &PDFPage{} - renderXLSXCell(page, xlsxCell{value: "Cell"}, 10, 20, 100, 15, style, true) - - bottom := page.operations[0].(textOperation) - if bottom.fontSize != 11*calibriToHelveticaFontScale || bottom.horizontalScale != calibriRegularWidthScale { - t.Fatalf("Calibri fallback metrics = size %v, scale %v", bottom.fontSize, bottom.horizontalScale) - } - if bottom.y != 20+bottom.fontSize*helveticaBaselineRatio { - t.Fatalf("bottom-aligned baseline = %v", bottom.y) - } - - style.vertical = "center" - style.align = "center" - page.operations = nil - renderXLSXCell(page, xlsxCell{value: "Cell"}, 10, 20, 100, 28, style, true) - centered := page.operations[0].(textOperation) - if centered.y != 20+(28-centered.fontSize)/2 { - t.Fatalf("centered baseline = %v", centered.y) - } - expectedX := 10 + (100-measureHelveticaText("Cell", centered.fontSize, centered.horizontalScale, false))/2 - if centered.x != expectedX { - t.Fatalf("centered x = %v, want %v", centered.x, expectedX) - } - - style.font.bold = true - page.operations = nil - renderXLSXCell(page, xlsxCell{value: "Cell"}, 10, 20, 100, 28, style, true) - bold := page.operations[0].(textOperation) - if bold.horizontalScale != calibriBoldWidthScale { - t.Fatalf("bold Calibri fallback scale = %v", bold.horizontalScale) - } -} - -func TestXLSXDefaultRowHeightUsesExcelPDFScale(t *testing.T) { - grid := xlsxGrid{defaultRowHeight: 15, rowHeights: map[int]float64{2: 22}} - if height := grid.rowHeight(1); height < 14.599 || height > 14.601 { - t.Fatalf("default row height = %v, want 14.6", height) - } - if height := grid.rowHeight(2); height != 22 { - t.Fatalf("explicit row height = %v, want 22", height) - } -} - -func TestConvertXLSXRendersClusteredColumnChart(t *testing.T) { - input := officePackageBytes(t, map[string]string{ - "xl/styles.xml": ``, - "xl/worksheets/sheet1.xml": `` + - `CategoryBudgetActual` + - `One108` + - `Two2018` + - `SUM(C2:C3)`, - "xl/worksheets/_rels/sheet1.xml.rels": ``, - "xl/drawings/drawing1.xml": `0040`, - "xl/drawings/_rels/drawing1.xml.rels": ``, - "xl/charts/chart1.xml": `<tx><rich><p><r><t>Budget vs Actual</t></r></p></rich></tx>` + - `Sheet1!B1Sheet1!A2:A3Sheet1!B2:B3` + - `Sheet1!C1Sheet1!A2:A3Sheet1!C2:C3` + - `<tx><rich><p><r><t>Category</t></r></p></rich></tx>` + - `<tx><rich><p><r><t>Amount</t></r></p></rich></tx>`, - }) - - pdf, err := ConvertBytesToPDF(input) - assertPDFContains(t, pdf, err, "Budget vs Actual", "Budget", "Actual", "Category", "Amount", "0.31 0.506 0.741 rg", "0.753 0.314 0.302 rg") -} - -func TestNeedsCalculatedXLSXGridOnlyForFullyUncachedFormulas(t *testing.T) { - for name, test := range map[string]struct { - cells string - want bool - }{ - "uncached": {cells: `SUM(A2:A3)`, want: true}, - "cached": {cells: `SUM(A2:A3)3`}, - "mixed": {cells: `A2B22`}, - "plain": {cells: `1`}, - } { - t.Run(name, func(t *testing.T) { - worksheet := []byte(`` + test.cells + ``) - if got := needsCalculatedXLSXGrid(worksheet); got != test.want { - t.Fatalf("needsCalculatedXLSXGrid() = %v, want %v", got, test.want) - } - }) - } -} - -func TestXLSXRowColumnLimitsAndOrientation(t *testing.T) { - input := officePackageBytes(t, map[string]string{ - "xl/workbook.xml": ``, - "xl/worksheets/sheet1.xml": `` + - `A1B1C1` + - `A2` + - ``, - }) - landscape := true - - pdf, err := ConvertBytesToPDFWithOptions(input, ConversionOptions{ - MaxRows: 1, MaxColumns: 2, Landscape: &landscape, - }) - assertPDFContains(t, pdf, err, "A1", "B1", "/MediaBox [0 0 792 612]") - for _, excluded := range []string{"C1", "A2"} { - if bytes.Contains(pdf, []byte(excluded)) { - t.Errorf("PDF contains excluded value %q", excluded) - } - } -} - -func TestXLSXOptionsRejectInvalidValuesAndFormats(t *testing.T) { - xlsx := officePackageBytes(t, map[string]string{ - "xl/workbook.xml": ``, - "xl/worksheets/sheet1.xml": ``, - }) - if _, err := ConvertBytesToPDFWithOptions(xlsx, ConversionOptions{MaxRows: -1}); !errors.Is(err, ErrInvalidInput) { - t.Fatalf("MaxRows error = %v, want ErrInvalidInput", err) - } - - docx := officePackageBytes(t, map[string]string{ - "word/document.xml": ``, - }) - if _, err := ConvertBytesToPDFWithOptions(docx, ConversionOptions{MaxColumns: 1}); !errors.Is(err, ErrInvalidInput) { - t.Fatalf("DOCX MaxColumns error = %v, want ErrInvalidInput", err) - } -} - -func TestConvertPPTXToPDF(t *testing.T) { - input := officePackageBytes(t, map[string]string{ - "ppt/presentation.xml": ``, - "ppt/slides/slide1.xml": `Hello PPTX`, - }) - - customSize, err := NewPageSize(300, 400) - if err != nil { - t.Fatal(err) - } - pdf, err := ConvertBytesToPDFWithOptions(input, ConversionOptions{PageSize: &customSize}) - assertPDFContains(t, pdf, err, "Hello PPTX", "/MediaBox [0 0 300 400]") -} - -func assertPDFContains(t *testing.T, pdf []byte, err error, values ...string) { - t.Helper() - if err != nil { - t.Fatalf("conversion error = %v", err) - } - if !bytes.HasPrefix(pdf, []byte("%PDF-1.4")) { - t.Fatal("conversion did not return a PDF") - } - for _, value := range values { - if !bytes.Contains(pdf, []byte(value)) { - t.Errorf("PDF does not contain %q", value) - } - } -} - -func officePackageBytes(t *testing.T, entries map[string]string) []byte { - t.Helper() - packageEntries := make([]packageEntry, 0, len(entries)) - for name, content := range entries { - packageEntries = append(packageEntries, packageEntry{name: name, content: content}) - } - return officePackageEntries(t, packageEntries) -} - -type packageEntry struct { - name string - content string -} - -func zipFile(name string, compressedSize, uncompressedSize uint64, flags uint16) *zip.File { - return &zip.File{FileHeader: zip.FileHeader{ - Name: name, - Flags: flags, - CompressedSize64: compressedSize, - UncompressedSize64: uncompressedSize, - }} -} - -func officePackageEntries(t *testing.T, entries []packageEntry) []byte { - t.Helper() - var buffer bytes.Buffer - writer := zip.NewWriter(&buffer) - for _, entry := range entries { - file, err := writer.Create(entry.name) - if err != nil { - t.Fatal(err) - } - if _, err := file.Write([]byte(entry.content)); err != nil { - t.Fatal(err) - } - } - if err := writer.Close(); err != nil { - t.Fatal(err) - } - return buffer.Bytes() -} - -func assertPackageErrorContains(t *testing.T, err error, message string) { - t.Helper() - if err == nil { - t.Fatalf("expected package error containing %q", message) - } - if !strings.Contains(err.Error(), message) { - t.Fatalf("error = %q, want message containing %q", err, message) - } -} diff --git a/minipdf-go/pdf.go b/minipdf-go/pdf.go deleted file mode 100644 index 8c987282..00000000 --- a/minipdf-go/pdf.go +++ /dev/null @@ -1,365 +0,0 @@ -package minipdf - -import ( - "bytes" - "compress/zlib" - "fmt" - "strconv" - "strings" - "unicode" -) - -type PDFColor struct { - Red float64 - Green float64 - Blue float64 -} - -var ( - PDFColorBlack = PDFColor{} - PDFColorWhite = PDFColor{Red: 1, Green: 1, Blue: 1} - PDFColorLightGray = PDFColor{Red: 0.92, Green: 0.92, Blue: 0.92} - PDFColorTableHeader = PDFColor{Red: 0.86, Green: 0.91, Blue: 0.96} -) - -type pdfOperation interface { - appendPDF(*bytes.Buffer, *embeddedFont) -} - -type PDFDocument struct { - pages []*PDFPage -} - -// PDFSaveOptions controls PDF serialization. -type PDFSaveOptions struct { - Compress bool -} - -type PDFPage struct { - Width float64 - Height float64 - operations []pdfOperation - decorations func(int, int) []pdfOperation -} - -func NewPDFDocument() *PDFDocument { - return &PDFDocument{} -} - -func (document *PDFDocument) AddPage(width, height float64) *PDFPage { - page := &PDFPage{Width: width, Height: height} - document.pages = append(document.pages, page) - return page -} - -func (page *PDFPage) AddText(text string, x, y, fontSize float64, color PDFColor, bold bool) { - page.operations = append(page.operations, textOperation{ - text: text, x: x, y: y, fontSize: fontSize, horizontalScale: 100, color: color, bold: bold, - }) -} - -func (page *PDFPage) addScaledText(text string, x, y, fontSize, horizontalScale float64, color PDFColor, bold bool) { - page.operations = append(page.operations, textOperation{ - text: text, x: x, y: y, fontSize: fontSize, horizontalScale: horizontalScale, color: color, bold: bold, - }) -} - -func (page *PDFPage) AddRect(x, y, width, height float64, color PDFColor) { - page.operations = append(page.operations, rectOperation{ - x: x, y: y, width: width, height: height, color: color, - }) -} - -func (page *PDFPage) AddLine(x1, y1, x2, y2 float64, color PDFColor, width float64) { - page.operations = append(page.operations, lineOperation{ - x1: x1, y1: y1, x2: x2, y2: y2, color: color, width: width, - }) -} - -type textOperation struct { - text string - x, y, fontSize float64 - horizontalScale float64 - color PDFColor - bold bool - italic bool - embedded *embeddedFont - synthesize bool -} - -func (operation textOperation) appendPDF(buffer *bytes.Buffer, embedded *embeddedFont) { - if operation.embedded != nil { - embedded = operation.embedded - } - horizontalScale := "" - if operation.horizontalScale != 0 && operation.horizontalScale != 100 { - horizontalScale = pdfNumber(operation.horizontalScale) + " Tz " - } - if embedded != nil { - if encoded, ok := embedded.encode(operation.text); ok { - syntheticBold := operation.synthesize && operation.bold && !embedded.nativeBold - syntheticItalic := operation.synthesize && operation.italic && !embedded.nativeItalic - synthetic := syntheticBold || syntheticItalic - position := pdfNumber(operation.x) + " " + pdfNumber(operation.y) + " Td" - if synthetic { - buffer.WriteString("q ") - if syntheticBold { - fmt.Fprintf(buffer, "%s w %s %s %s RG ", pdfNumber(operation.fontSize/30), pdfNumber(operation.color.Red), pdfNumber(operation.color.Green), pdfNumber(operation.color.Blue)) - } - if syntheticItalic { - position = "1 0 0.21256 1 " + pdfNumber(operation.x) + " " + pdfNumber(operation.y) + " Tm" - } - } - mode := "" - if syntheticBold { - mode = "2 Tr " - } - fmt.Fprintf(buffer, "BT /%s %s Tf %s%s%s %s %s rg %s <%s> Tj ET\n", - embedded.resource, - pdfNumber(operation.fontSize), - horizontalScale, - mode, - pdfNumber(operation.color.Red), - pdfNumber(operation.color.Green), - pdfNumber(operation.color.Blue), - position, - encoded, - ) - if synthetic { - buffer.WriteString("Q\n") - } - return - } - } - font := "F1" - if operation.bold { - font = "F2" - } - if operation.italic { - font = "F3" - if operation.bold { - font = "F4" - } - } - fmt.Fprintf(buffer, "BT /%s %s Tf %s%s %s %s rg %s %s Td (%s) Tj ET\n", - font, - pdfNumber(operation.fontSize), - horizontalScale, - pdfNumber(operation.color.Red), - pdfNumber(operation.color.Green), - pdfNumber(operation.color.Blue), - pdfNumber(operation.x), - pdfNumber(operation.y), - escapePDFText(operation.text), - ) -} - -type rectOperation struct { - x, y, width, height float64 - color PDFColor -} - -func (operation rectOperation) appendPDF(buffer *bytes.Buffer, _ *embeddedFont) { - fmt.Fprintf(buffer, "%s %s %s rg %s %s %s %s re f\n", - pdfNumber(operation.color.Red), - pdfNumber(operation.color.Green), - pdfNumber(operation.color.Blue), - pdfNumber(operation.x), - pdfNumber(operation.y), - pdfNumber(operation.width), - pdfNumber(operation.height), - ) -} - -type lineOperation struct { - x1, y1, x2, y2 float64 - color PDFColor - width float64 - dash []float64 -} - -func (operation lineOperation) appendPDF(buffer *bytes.Buffer, _ *embeddedFont) { - if len(operation.dash) > 0 { - buffer.WriteString("q [") - for _, length := range operation.dash { - buffer.WriteString(pdfNumber(length) + " ") - } - buffer.WriteString("] 0 d ") - } - fmt.Fprintf(buffer, "%s %s %s RG %s w %s %s m %s %s l S\n", - pdfNumber(operation.color.Red), - pdfNumber(operation.color.Green), - pdfNumber(operation.color.Blue), - pdfNumber(operation.width), - pdfNumber(operation.x1), - pdfNumber(operation.y1), - pdfNumber(operation.x2), - pdfNumber(operation.y2), - ) - if len(operation.dash) > 0 { - buffer.WriteString("Q\n") - } -} - -func (document *PDFDocument) Bytes() []byte { - return document.BytesWithOptions(PDFSaveOptions{}) -} - -// BytesWithOptions serializes the document with the requested save behavior. -func (document *PDFDocument) BytesWithOptions(options PDFSaveOptions) []byte { - pages := document.pages - if len(pages) == 0 { - pages = []*PDFPage{{Width: PageSizeA4.Width, Height: PageSizeA4.Height}} - } - - pageCount := len(pages) - decoratedPages := make([]*PDFPage, pageCount) - for index, page := range pages { - clone := *page - clone.operations = append([]pdfOperation(nil), page.operations...) - if page.decorations != nil { - clone.operations = append(clone.operations, page.decorations(index+1, pageCount)...) - } - decoratedPages[index] = &clone - } - pages = decoratedPages - objects := make([][]byte, 4) - objects[0] = []byte("<< /Type /Catalog /Pages 2 0 R >>") - objects[2] = []byte("<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>") - objects[3] = []byte("<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica-Bold /Encoding /WinAnsiEncoding >>") - embedded := prepareEmbeddedFont(pages) - var fonts []*embeddedFont - if embedded != nil { - embedded.resource = "FU1" - embedded.objectID = appendEmbeddedFontObjects(&objects, embedded) - fonts = append(fonts, embedded) - } - seenFonts := make(map[*embeddedFont]*embeddedFont) - hasItalic := false - for _, page := range pages { - for _, operation := range page.operations { - text, ok := operation.(textOperation) - if !ok { - continue - } - hasItalic = hasItalic || text.italic - if text.embedded == nil { - continue - } - canonical := seenFonts[text.embedded] - if canonical == nil { - canonical = text.embedded - for _, existing := range fonts { - if existing.name == canonical.name && bytes.Equal(existing.data, canonical.data) { - canonical = existing - break - } - } - seenFonts[text.embedded] = canonical - if canonical == text.embedded { - fonts = append(fonts, canonical) - } - } - canonical.collect(text.text) - } - } - for index, font := range fonts { - if font == embedded { - continue - } - font.resource = fmt.Sprintf("FU%d", index+1) - font.objectID = appendEmbeddedFontObjects(&objects, font) - } - for alias, canonical := range seenFonts { - alias.resource = canonical.resource - alias.objectID = canonical.objectID - alias.runeToGlyph = canonical.runeToGlyph - alias.glyphToRune = canonical.glyphToRune - } - italicResources := "" - if hasItalic { - regular := appendPDFObject(&objects, []byte("<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica-Oblique /Encoding /WinAnsiEncoding >>")) - bold := appendPDFObject(&objects, []byte("<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica-BoldOblique /Encoding /WinAnsiEncoding >>")) - italicResources = fmt.Sprintf(" /F3 %d 0 R /F4 %d 0 R", regular, bold) - } - - pageObjectStart := len(objects) + 1 - pageReferences := make([]string, pageCount) - for index := range pages { - pageReferences[index] = fmt.Sprintf("%d 0 R", pageObjectStart+index*2) - } - objects[1] = []byte(fmt.Sprintf("<< /Type /Pages /Count %d /Kids [%s] >>", pageCount, strings.Join(pageReferences, " "))) - - for index, page := range pages { - pageObjectNumber := pageObjectStart + index*2 - contentObjectNumber := pageObjectNumber + 1 - fontResources := "/F1 3 0 R /F2 4 0 R" - fontResources += italicResources - for _, font := range fonts { - fontResources += fmt.Sprintf(" /%s %d 0 R", font.resource, font.objectID) - } - pageObject := []byte(fmt.Sprintf( - "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 %s %s] /Resources << /Font << %s >> >> /Contents %d 0 R >>", - pdfNumber(page.Width), pdfNumber(page.Height), fontResources, contentObjectNumber, - )) - var content bytes.Buffer - for _, operation := range page.operations { - operation.appendPDF(&content, embedded) - } - contentData := content.Bytes() - filter := "" - if options.Compress { - var compressed bytes.Buffer - writer := zlib.NewWriter(&compressed) - _, _ = writer.Write(contentData) - _ = writer.Close() - contentData = compressed.Bytes() - filter = " /Filter /FlateDecode" - } - contentObject := fmt.Appendf(nil, "<< /Length %d%s >>\nstream\n", len(contentData), filter) - contentObject = append(contentObject, contentData...) - contentObject = append(contentObject, []byte("\nendstream")...) - objects = append(objects, pageObject, contentObject) - } - - var output bytes.Buffer - output.WriteString("%PDF-1.4\n%\xe2\xe3\xcf\xd3\n") - offsets := make([]int, len(objects)+1) - for index, object := range objects { - offsets[index+1] = output.Len() - fmt.Fprintf(&output, "%d 0 obj\n", index+1) - output.Write(object) - output.WriteString("\nendobj\n") - } - xrefOffset := output.Len() - fmt.Fprintf(&output, "xref\n0 %d\n0000000000 65535 f \n", len(objects)+1) - for index := 1; index < len(offsets); index++ { - fmt.Fprintf(&output, "%010d 00000 n \n", offsets[index]) - } - fmt.Fprintf(&output, "trailer\n<< /Size %d /Root 1 0 R >>\nstartxref\n%d\n%%%%EOF\n", len(objects)+1, xrefOffset) - return output.Bytes() -} - -func pdfNumber(value float64) string { - return strconv.FormatFloat(value, 'f', -1, 64) -} - -func escapePDFText(text string) string { - var escaped strings.Builder - for _, character := range text { - switch character { - case '\\', '(', ')': - escaped.WriteByte('\\') - escaped.WriteRune(character) - case '\n', '\r', '\t': - escaped.WriteByte(' ') - default: - if character <= 0xff && !unicode.IsControl(character) { - escaped.WriteRune(character) - } else { - escaped.WriteByte('?') - } - } - } - return escaped.String() -} diff --git a/minipdf-go/pdf_image.go b/minipdf-go/pdf_image.go deleted file mode 100644 index 86cd1396..00000000 --- a/minipdf-go/pdf_image.go +++ /dev/null @@ -1,53 +0,0 @@ -package minipdf - -import ( - "bytes" - "compress/zlib" - "encoding/hex" - "fmt" - "image" - "image/color" - "image/draw" -) - -type imageOperation struct { - x, y, width, height float64 - pixelWidth, pixelHeight int - data []byte -} - -func newPDFImage(source image.Image, crop image.Rectangle) (imageOperation, error) { - if crop.Empty() || !crop.In(source.Bounds()) { - return imageOperation{}, fmt.Errorf("invalid PDF image crop %v", crop) - } - if int64(crop.Dx()) > 25000000/int64(crop.Dy()) { - return imageOperation{}, fmt.Errorf("PDF image exceeds 25 million pixels") - } - raster := image.NewRGBA(image.Rect(0, 0, crop.Dx(), crop.Dy())) - draw.Draw(raster, raster.Bounds(), &image.Uniform{C: color.White}, image.Point{}, draw.Src) - draw.Draw(raster, raster.Bounds(), source, crop.Min, draw.Over) - var compressed bytes.Buffer - writer := zlib.NewWriter(&compressed) - row := make([]byte, raster.Bounds().Dx()*3) - for y := 0; y < raster.Bounds().Dy(); y++ { - for x := 0; x < raster.Bounds().Dx(); x++ { - value := raster.RGBAAt(x, y) - row[x*3], row[x*3+1], row[x*3+2] = value.R, value.G, value.B - } - if _, err := writer.Write(row); err != nil { - return imageOperation{}, err - } - } - if err := writer.Close(); err != nil { - return imageOperation{}, err - } - return imageOperation{pixelWidth: raster.Bounds().Dx(), pixelHeight: raster.Bounds().Dy(), data: compressed.Bytes()}, nil -} - -func (operation imageOperation) appendPDF(buffer *bytes.Buffer, _ *embeddedFont) { - fmt.Fprintf(buffer, "q %s 0 0 %s %s %s cm BI /W %d /H %d /CS /RGB /BPC 8 /F [/ASCIIHexDecode /FlateDecode] ID\n", - pdfNumber(operation.width), pdfNumber(operation.height), pdfNumber(operation.x), pdfNumber(operation.y), - operation.pixelWidth, operation.pixelHeight) - buffer.WriteString(hex.EncodeToString(operation.data)) - buffer.WriteString(">\nEI Q\n") -} diff --git a/minipdf-go/pdf_test.go b/minipdf-go/pdf_test.go deleted file mode 100644 index 4eaf3657..00000000 --- a/minipdf-go/pdf_test.go +++ /dev/null @@ -1,119 +0,0 @@ -package minipdf - -import ( - "bytes" - "compress/zlib" - "io" - "regexp" - "strconv" - "testing" - - "golang.org/x/image/font/gofont/goregular" -) - -func TestPDFDocumentCompressesContentStreams(t *testing.T) { - document := NewPDFDocument() - page := document.AddPage(300, 400) - for index := 0; index < 100; index++ { - page.AddText("Repeated content for compression", 20, float64(350-index), 12, PDFColorBlack, false) - } - - uncompressed := document.Bytes() - compressed := document.BytesWithOptions(PDFSaveOptions{Compress: true}) - - if !bytes.Contains(compressed, []byte("/Filter /FlateDecode")) { - t.Fatal("compressed PDF does not declare FlateDecode") - } - assertPDFStreamLengths(t, compressed) - if len(compressed) >= len(uncompressed) { - t.Fatalf("compressed PDF size = %d, want less than %d", len(compressed), len(uncompressed)) - } - streamStart := bytes.Index(compressed, []byte("stream\n")) - streamEnd := bytes.Index(compressed[streamStart+len("stream\n"):], []byte("\nendstream")) - if streamStart < 0 || streamEnd < 0 { - t.Fatal("compressed content stream is missing") - } - streamStart += len("stream\n") - streamEnd += streamStart - reader, err := zlib.NewReader(bytes.NewReader(compressed[streamStart:streamEnd])) - if err != nil { - t.Fatal(err) - } - content, err := io.ReadAll(reader) - if closeErr := reader.Close(); err == nil { - err = closeErr - } - if err != nil { - t.Fatal(err) - } - if !bytes.Contains(content, []byte("Repeated content for compression")) { - t.Fatal("decompressed stream does not contain page content") - } -} - -func TestPDFDocumentEmbedsRegisteredTrueTypeFont(t *testing.T) { - ClearRegisteredFonts() - t.Cleanup(ClearRegisteredFonts) - RegisterFont("Go Regular", goregular.TTF) - document := NewPDFDocument() - document.AddPage(300, 400).AddText("Hello, Ω", 20, 350, 12, PDFColorBlack, false) - - pdf := document.Bytes() - - for _, marker := range [][]byte{ - []byte("/Subtype /Type0"), - []byte("/Subtype /CIDFontType2"), - []byte("/FontFile2"), - []byte("/ToUnicode"), - []byte("<03A9>"), - } { - if !bytes.Contains(pdf, marker) { - t.Errorf("PDF does not contain %q", marker) - } - } -} - -func TestPDFDocumentWritesValidEnvelope(t *testing.T) { - document := NewPDFDocument() - page := document.AddPage(PageSizeA4.Width, PageSizeA4.Height) - page.AddText("Hello from Go MiniPdf", 72, 760, 14, PDFColorBlack, false) - - pdf := document.Bytes() - if !bytes.HasPrefix(pdf, []byte("%PDF-1.4")) { - t.Fatal("PDF header is missing") - } - if !bytes.HasSuffix(pdf, []byte("%%EOF\n")) { - t.Fatal("PDF EOF marker is missing") - } -} - -func TestPDFStreamLengthsAreExact(t *testing.T) { - document := NewPDFDocument() - document.AddPage(300, 400).AddText("Hello", 20, 350, 12, PDFColorBlack, false) - pdf := document.Bytes() - assertPDFStreamLengths(t, pdf) -} - -func assertPDFStreamLengths(t *testing.T, pdf []byte) { - t.Helper() - pattern := regexp.MustCompile(`/Length ([0-9]+)(?: /Filter /FlateDecode)? >>\nstream\n`) - matches := pattern.FindAllSubmatchIndex(pdf, -1) - if len(matches) == 0 { - t.Fatal("no PDF streams found") - } - for _, match := range matches { - declared, err := strconv.Atoi(string(pdf[match[2]:match[3]])) - if err != nil { - t.Fatal(err) - } - streamStart := match[1] - streamEndOffset := bytes.Index(pdf[streamStart:], []byte("\nendstream")) - if streamEndOffset < 0 { - t.Fatal("stream terminator is missing") - } - actual := streamEndOffset - if declared != actual { - t.Fatalf("stream length = %d, want %d", declared, actual) - } - } -} diff --git a/minipdf-go/pptx.go b/minipdf-go/pptx.go deleted file mode 100644 index 65de5f9a..00000000 --- a/minipdf-go/pptx.go +++ /dev/null @@ -1,110 +0,0 @@ -package minipdf - -import ( - "bytes" - "encoding/xml" - "fmt" - "strconv" - "strings" -) - -func convertPPTX(input []byte, options ConversionOptions) ([]byte, error) { - files, err := openOfficePackage(input) - if err != nil { - return nil, err - } - presentationXML, err := files.read("ppt/presentation.xml") - if err != nil { - return nil, err - } - pageSize, err := extractSlideSize(presentationXML) - if err != nil { - return nil, fmt.Errorf("parse ppt/presentation.xml: %w", err) - } - slides := sortedPackageParts(files, "ppt/slides/", ".xml") - if len(slides) == 0 { - return nil, fmt.Errorf("Office package part %q is missing", "ppt/slides/slide1.xml") - } - pages := make([]textPage, 0, len(slides)) - for _, name := range slides { - slideXML, readErr := files.read(name) - if readErr != nil { - return nil, readErr - } - lines, parseErr := extractSlideText(slideXML) - if parseErr != nil { - return nil, fmt.Errorf("parse %s: %w", name, parseErr) - } - pages = append(pages, textPage{lines: lines, size: pageSize}) - } - return renderTextPages(pages, options), nil -} - -func extractSlideSize(data []byte) (PageSize, error) { - pageSize := PageSize{Width: 720, Height: 540} - decoder := xml.NewDecoder(bytes.NewReader(data)) - for { - token, err := decoder.Token() - if err != nil { - if err.Error() == "EOF" { - return pageSize, nil - } - return PageSize{}, err - } - start, ok := token.(xml.StartElement) - if !ok || start.Name.Local != "sldSz" { - continue - } - width, widthErr := strconv.ParseFloat(attrValue(start, "cx"), 64) - height, heightErr := strconv.ParseFloat(attrValue(start, "cy"), 64) - if widthErr == nil && heightErr == nil && width > 0 && height > 0 { - pageSize = PageSize{Width: width / 12700, Height: height / 12700} - } - return pageSize, nil - } -} - -func extractSlideText(data []byte) ([]string, error) { - decoder := xml.NewDecoder(bytes.NewReader(data)) - var lines []string - var paragraph strings.Builder - paragraphDepth := 0 - for { - token, err := decoder.Token() - if err != nil { - if err.Error() == "EOF" { - break - } - return nil, err - } - switch element := token.(type) { - case xml.StartElement: - switch element.Name.Local { - case "p": - paragraphDepth++ - case "t": - var text string - if err := decoder.DecodeElement(&text, &element); err != nil { - return nil, err - } - paragraph.WriteString(text) - case "br": - paragraph.WriteByte('\n') - case "tab": - paragraph.WriteString(" ") - } - case xml.EndElement: - if element.Name.Local == "p" && paragraphDepth > 0 { - paragraphDepth-- - if paragraphDepth == 0 { - lines = append(lines, strings.Split(paragraph.String(), "\n")...) - paragraph.Reset() - } - } - } - } - if len(lines) == 0 { - lines = append(lines, "Empty PPTX slide") - } - return lines, nil -} diff --git a/minipdf-go/xlsx.go b/minipdf-go/xlsx.go deleted file mode 100644 index 8f4114c2..00000000 --- a/minipdf-go/xlsx.go +++ /dev/null @@ -1,531 +0,0 @@ -package minipdf - -import ( - "bytes" - "encoding/xml" - "fmt" - "io" - "strconv" - "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 { - return nil, err - } - sharedStrings, err := readSharedStrings(files) - if err != nil { - return nil, err - } - worksheets := sortedPackageParts(files, "xl/worksheets/", ".xml") - if len(worksheets) == 0 { - return nil, errorsNewMissingWorksheets() - } - worksheets, printSettings, err := visibleXLSXWorksheets(files, worksheets) - if err != nil { - return nil, err - } - styles, differentialFills, err := readXLSXStyles(files) - if err != nil { - return nil, err - } - if len(styles) > 0 { - needsGridRendering := false - for _, name := range worksheets { - worksheetXML, readErr := files.read(name) - if readErr != nil { - return nil, readErr - } - if needsCalculatedXLSXGrid(worksheetXML) { - needsGridRendering = true - break - } - } - if needsGridRendering { - return renderXLSXWorksheets(files, worksheets, sharedStrings, styles, differentialFills, options, printSettings) - } - } - document := NewPDFDocument() - fallbackPageSize := PageSizeA4 - for _, name := range worksheets { - if settings := printSettings[strings.ToLower(name)]; len(settings.areas) > 0 { - if err := renderXLSXWorksheet(document, files, name, sharedStrings, styles, differentialFills, options, settings); err != nil { - return nil, err - } - continue - } - worksheetXML, readErr := files.read(name) - if readErr != nil { - return nil, readErr - } - lines, pageSize, fit, parseErr := extractWorksheet(worksheetXML, sharedStrings) - if parseErr != nil { - return nil, fmt.Errorf("parse %s: %w", name, parseErr) - } - lines = limitWorksheet(lines, options.MaxRows, options.MaxColumns) - if options.Landscape != nil { - isLandscape := pageSize.Width > pageSize.Height - if *options.Landscape != isLandscape { - pageSize.Width, pageSize.Height = pageSize.Height, pageSize.Width - } - } - fallbackPageSize = pageSize - if len(lines) == 0 { - continue - } - effectivePageSize := pageSize - if options.PageSize != nil { - effectivePageSize = *options.PageSize - } - hasText := false - for _, line := range lines { - if strings.TrimSpace(line) != "" { - hasText = true - break - } - } - // 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 !fitWidth && worksheetColumnCount(group) == 1 { - overflowPages = splitWorksheetTextOverflow(group, textCharactersPerLine(effectivePageSize, Margins{}, baseFontSize)) - noWrap = len(overflowPages) > 1 - } - for _, overflowPage := range overflowPages { - overflowPage = append([]string{""}, overflowPage...) - addTextPages(document, overflowPage, effectivePageSize, Margins{}, noWrap, hasText, fitHeight) - } - } - } - if len(document.pages) == 0 { - if options.PageSize != nil { - fallbackPageSize = *options.PageSize - } - document.AddPage(fallbackPageSize.Width, fallbackPageSize.Height) - } - return document.BytesWithOptions(PDFSaveOptions{Compress: options.Compress}), nil -} - -// visibleXLSXWorksheets returns the worksheet parts that Excel and LibreOffice -// would print: those that belong to a sheet xl/workbook.xml does not mark -// hidden or veryHidden. -func visibleXLSXWorksheets(files officePackage, worksheets []string) ([]string, map[string]xlsxPrintSettings, error) { - const workbookName = "xl/workbook.xml" - if _, ok := files[workbookName]; !ok { - return worksheets, nil, nil - } - data, err := files.read(workbookName) - if err != nil { - return nil, nil, err - } - // Part names are case-insensitive, so targets are compared in lower case. - targets := make(map[string]string) - relationshipsName := xlsxRelationshipPartName(workbookName) - _, hasRelationships := files[relationshipsName] - if hasRelationships { - relationshipsData, readErr := files.read(relationshipsName) - if readErr != nil { - return nil, nil, readErr - } - var relationships xlsxRelationshipsDocument - if err := xml.Unmarshal(relationshipsData, &relationships); err != nil { - return nil, nil, fmt.Errorf("parse %s: %w", relationshipsName, err) - } - for _, relationship := range relationships.Items { - targets[relationship.ID] = strings.ToLower(xlsxResolveRelationshipTarget(workbookName, relationship.Target)) - } - } - worksheetParts := make(map[string]bool, len(worksheets)) - for _, name := range worksheets { - worksheetParts[strings.ToLower(name)] = true - } - visibleParts := make(map[string]bool) - hiddenParts := make(map[string]bool) - sheetCount := 0 - var sheetParts []string - settingsByIndex := make(map[int]xlsxPrintSettings) - var sheetNames []string - date1904 := false - unresolvedVisibleSheet := false - decoder := xml.NewDecoder(bytes.NewReader(data)) - for { - token, tokenErr := decoder.Token() - if tokenErr == io.EOF { - break - } - if tokenErr != nil { - return nil, nil, fmt.Errorf("parse %s: %w", workbookName, tokenErr) - } - start, ok := token.(xml.StartElement) - if !ok { - continue - } - if start.Name.Local == "workbookPr" { - if value := attrValue(start, "date1904"); value != "" { - date1904, err = strconv.ParseBool(value) - if err != nil { - return nil, nil, fmt.Errorf("parse %s: invalid date1904 %q", workbookName, value) - } - } - } - if start.Name.Local == "definedName" { - name := attrValue(start, "name") - if name != "_xlnm.Print_Area" && name != "_xlnm.Print_Titles" { - continue - } - index, indexErr := strconv.Atoi(attrValue(start, "localSheetId")) - if indexErr != nil || index < 0 { - return nil, nil, fmt.Errorf("parse %s: invalid localSheetId for %s", workbookName, name) - } - var value string - if err := decoder.DecodeElement(&value, &start); err != nil { - return nil, nil, fmt.Errorf("parse %s: %w", workbookName, err) - } - ranges, rangeErr := parseXLSXPrintRanges(value) - if rangeErr != nil { - return nil, nil, fmt.Errorf("parse %s %s: %w", workbookName, name, rangeErr) - } - settings := settingsByIndex[index] - if name == "_xlnm.Print_Area" { - settings.areas = ranges - } else { - for _, area := range ranges { - switch { - case area.startColumn == 1 && area.endColumn == 16384: - settings.rows = xlsxRange{start: area.startRow, end: area.endRow} - case area.startRow == 1 && area.endRow == 1048576: - settings.columns = xlsxRange{start: area.startColumn, end: area.endColumn} - default: - return nil, nil, fmt.Errorf("parse %s: print titles must be whole rows or columns", workbookName) - } - } - } - settingsByIndex[index] = settings - continue - } - if start.Name.Local != "sheet" { - continue - } - sheetCount++ - sheetNames = append(sheetNames, attrValue(start, "name")) - state := attrValue(start, "state") - isHidden := state == "hidden" || state == "veryHidden" - var part string - if hasRelationships { - part = targets[attrValue(start, "id")] - } else if sheetCount <= len(worksheets) { - // Without workbook relationships, sheets map to the ordered - // worksheet parts by position. - part = strings.ToLower(worksheets[sheetCount-1]) - } - sheetParts = append(sheetParts, part) - switch { - case isHidden: - hiddenParts[part] = true - case !worksheetParts[part]: - unresolvedVisibleSheet = true - default: - visibleParts[part] = true - } - } - // When every visible sheet resolves to a worksheet part, render exactly those - // parts so that a hidden sheet with a broken relationship is never printed. - // Otherwise only drop the parts known to be hidden, so no visible sheet is - // lost. A visible chartsheet resolves to no worksheet part and therefore - // selects the second mode. - keepVisibleOnly := hasRelationships && sheetCount > 0 && !unresolvedVisibleSheet - visible := make([]string, 0, len(worksheets)) - for _, name := range worksheets { - key := strings.ToLower(name) - keep := !hiddenParts[key] - if keepVisibleOnly { - keep = visibleParts[key] - } - if keep { - visible = append(visible, name) - } - } - printSettings := make(map[string]xlsxPrintSettings) - for index, settings := range settingsByIndex { - settings.date1904 = date1904 - if index < len(sheetNames) { - settings.sheetName = sheetNames[index] - } - if index >= len(sheetParts) { - return nil, nil, fmt.Errorf("parse %s: print settings refer to missing sheet %d", workbookName, index) - } - if part := sheetParts[index]; worksheetParts[part] { - printSettings[part] = settings - } - } - return visible, printSettings, nil -} - -func limitWorksheet(lines []string, maxRows, maxColumns int) []string { - if maxRows > 0 && len(lines) > maxRows { - lines = lines[:maxRows] - } - if maxColumns <= 0 { - return lines - } - limited := make([]string, len(lines)) - for index, line := range lines { - cells := strings.Split(line, "\t") - if len(cells) > maxColumns { - cells = cells[:maxColumns] - } - limited[index] = strings.Join(cells, "\t") - } - return limited -} - -func splitWorksheetColumnGroups(lines []string, columnsPerPage int) [][]string { - maximumColumns := worksheetColumnCount(lines) - if maximumColumns <= columnsPerPage || columnsPerPage <= 0 { - return [][]string{lines} - } - - groups := make([][]string, 0, (maximumColumns+columnsPerPage-1)/columnsPerPage) - for start := 0; start < maximumColumns; start += columnsPerPage { - end := min(start+columnsPerPage, maximumColumns) - group := make([]string, len(lines)) - for rowIndex, line := range lines { - cells := strings.Split(line, "\t") - if start >= len(cells) { - continue - } - rowEnd := min(end, len(cells)) - group[rowIndex] = strings.Join(cells[start:rowEnd], "\t") - } - groups = append(groups, group) - } - return groups -} - -func worksheetColumnCount(lines []string) int { - maximum := 0 - for _, line := range lines { - maximum = max(maximum, len(strings.Split(line, "\t"))) - } - return maximum -} - -func splitWorksheetTextOverflow(lines []string, charactersPerPage int) [][]string { - if charactersPerPage <= 0 { - return [][]string{lines} - } - maximumCharacters := 0 - rows := make([][]rune, len(lines)) - for index, line := range lines { - rows[index] = []rune(line) - maximumCharacters = max(maximumCharacters, len(rows[index])) - } - pageCount := max(1, (maximumCharacters+charactersPerPage-1)/charactersPerPage) - pages := make([][]string, pageCount) - for pageIndex := range pages { - start := pageIndex * charactersPerPage - end := start + charactersPerPage - pages[pageIndex] = make([]string, len(rows)) - for rowIndex, row := range rows { - if start >= len(row) { - continue - } - pages[pageIndex][rowIndex] = string(row[start:min(end, len(row))]) - } - } - return pages -} - -func errorsNewMissingWorksheets() error { - return fmt.Errorf("Office package part %q is missing", "xl/worksheets/sheet1.xml") -} - -func readSharedStrings(files officePackage) ([]string, error) { - if _, ok := files["xl/sharedStrings.xml"]; !ok { - return nil, nil - } - data, err := files.read("xl/sharedStrings.xml") - if err != nil { - return nil, err - } - decoder := xml.NewDecoder(bytes.NewReader(data)) - var values []string - var current strings.Builder - inString := false - for { - token, tokenErr := decoder.Token() - if tokenErr != nil { - if tokenErr.Error() == "EOF" { - break - } - return nil, fmt.Errorf("parse xl/sharedStrings.xml: %w", tokenErr) - } - switch element := token.(type) { - case xml.StartElement: - if element.Name.Local == "si" { - inString = true - current.Reset() - } else if element.Name.Local == "t" && inString { - var text string - if err := decoder.DecodeElement(&text, &element); err != nil { - return nil, err - } - current.WriteString(text) - } - case xml.EndElement: - if element.Name.Local == "si" && inString { - values = append(values, current.String()) - inString = false - } - } - } - return values, nil -} - -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 - for { - token, err := decoder.Token() - if err != nil { - if err.Error() == "EOF" { - break - } - return nil, PageSize{}, worksheetFit{}, err - } - switch element := token.(type) { - case xml.StartElement: - switch element.Name.Local { - case "row": - row = nil - rowNumber = len(lines) + 1 - if parsed, parseErr := strconv.Atoi(attrValue(element, "r")); parseErr == nil && parsed > 0 { - rowNumber = parsed - } - case "c": - columnNumber := worksheetColumnIndex(attrValue(element, "r")) - for len(row)+1 < columnNumber { - row = append(row, "") - } - value, cellErr := decodeWorksheetCell(decoder, element, sharedStrings) - if cellErr != nil { - 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 - } - 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" { - for len(lines)+1 < rowNumber { - lines = append(lines, "") - } - lines = append(lines, strings.Join(row, "\t")) - } - } - } - return lines, pageSize, fit, nil -} - -func worksheetColumnIndex(reference string) int { - column := 0 - for _, character := range reference { - if character >= 'a' && character <= 'z' { - character -= 'a' - 'A' - } - if character < 'A' || character > 'Z' { - break - } - column = column*26 + int(character-'A'+1) - } - return column -} - -func decodeWorksheetCell(decoder *xml.Decoder, start xml.StartElement, sharedStrings []string) (string, error) { - value, _, err := decodeWorksheetCellContent(decoder, start, sharedStrings) - return value, err -} - -func decodeWorksheetCellContent(decoder *xml.Decoder, start xml.StartElement, sharedStrings []string) (string, string, error) { - cellType := attrValue(start, "t") - var value strings.Builder - var formula string - depth := 1 - for depth > 0 { - token, err := decoder.Token() - if err != nil { - return "", "", err - } - switch element := token.(type) { - case xml.StartElement: - depth++ - if element.Name.Local == "v" || element.Name.Local == "t" || element.Name.Local == "f" { - var text string - if err := decoder.DecodeElement(&text, &element); err != nil { - return "", "", err - } - depth-- - if element.Name.Local == "f" { - formula = text - } else { - value.WriteString(text) - } - } - case xml.EndElement: - depth-- - } - } - rawValue := value.String() - if cellType == "s" { - index, err := strconv.Atoi(strings.TrimSpace(rawValue)) - if err == nil && index >= 0 && index < len(sharedStrings) { - return sharedStrings[index], formula, nil - } - } - if cellType == "b" { - switch strings.TrimSpace(rawValue) { - case "1": - return "TRUE", formula, nil - case "0": - return "FALSE", formula, nil - } - } - return rawValue, formula, nil -} diff --git a/minipdf-go/xlsx_chart.go b/minipdf-go/xlsx_chart.go deleted file mode 100644 index 9e5b9e3a..00000000 --- a/minipdf-go/xlsx_chart.go +++ /dev/null @@ -1,497 +0,0 @@ -package minipdf - -import ( - "encoding/xml" - "fmt" - "math" - "path" - "strconv" - "strings" -) - -const xlsxEmuPerPoint = 12700 - -type xlsxChartSeries struct { - name string - categories []string - values []float64 -} - -type xlsxChart struct { - anchorRow, anchorColumn int - rowOffset, columnOffset float64 - width, height float64 - title, categoryTitle string - valueTitle, legendPosition string - gapWidth float64 - series []xlsxChartSeries -} - -type xlsxRelationshipsDocument struct { - Items []struct { - ID string `xml:"Id,attr"` - Type string `xml:"Type,attr"` - Target string `xml:"Target,attr"` - TargetMode string `xml:"TargetMode,attr"` - } `xml:"Relationship"` -} - -type xlsxDrawingMarker struct { - Column int `xml:"col"` - ColumnOffset int64 `xml:"colOff"` - Row int `xml:"row"` - RowOffset int64 `xml:"rowOff"` -} - -type xlsxChartAnchor struct { - From xlsxDrawingMarker `xml:"from"` - To xlsxDrawingMarker `xml:"to"` - Extension struct { - Width int64 `xml:"cx,attr"` - Height int64 `xml:"cy,attr"` - } `xml:"ext"` - Frame struct { - Reference struct { - ID string `xml:"id,attr"` - } `xml:"graphic>graphicData>chart"` - } `xml:"graphicFrame"` - Picture *struct { - Fill struct { - Blip struct { - ID string `xml:"embed,attr"` - } `xml:"blip"` - Crop struct { - Left int `xml:"l,attr"` - Right int `xml:"r,attr"` - Top int `xml:"t,attr"` - Bottom int `xml:"b,attr"` - } `xml:"srcRect"` - } `xml:"blipFill"` - } `xml:"pic"` - Client struct { - Print *bool `xml:"fPrintsWithSheet,attr"` - } `xml:"clientData"` -} - -type xlsxDrawingDocument struct { - OneCell []xlsxChartAnchor `xml:"oneCellAnchor"` - TwoCell []xlsxChartAnchor `xml:"twoCellAnchor"` -} - -type xlsxChartTitleXML struct { - Runs []string `xml:"tx>rich>p>r>t"` -} - -type xlsxChartSeriesXML struct { - Name string `xml:"tx>v"` - NameFormula string `xml:"tx>strRef>f"` - CategoryNum string `xml:"cat>numRef>f"` - CategoryStr string `xml:"cat>strRef>f"` - Value string `xml:"val>numRef>f"` -} - -type xlsxChartDocument struct { - Chart struct { - Title xlsxChartTitleXML `xml:"title"` - Plot struct { - Bar struct { - Series []xlsxChartSeriesXML `xml:"ser"` - GapWidth struct { - Value float64 `xml:"val,attr"` - } `xml:"gapWidth"` - } `xml:"barChart"` - CategoryAxis struct { - Title xlsxChartTitleXML `xml:"title"` - } `xml:"catAx"` - ValueAxis struct { - Title xlsxChartTitleXML `xml:"title"` - } `xml:"valAx"` - } `xml:"plotArea"` - Legend struct { - Position struct { - Value string `xml:"val,attr"` - } `xml:"legendPos"` - } `xml:"legend"` - } `xml:"chart"` -} - -func readXLSXDrawing(files officePackage, worksheetName string) (string, xlsxDrawingDocument, error) { - relationshipsName := xlsxRelationshipPartName(worksheetName) - _, ok := files[relationshipsName] - if !ok { - return "", xlsxDrawingDocument{}, nil - } - relationshipsData, err := files.read(relationshipsName) - if err != nil { - return "", xlsxDrawingDocument{}, err - } - var relationships xlsxRelationshipsDocument - if err := xml.Unmarshal(relationshipsData, &relationships); err != nil { - return "", xlsxDrawingDocument{}, fmt.Errorf("parse %s: %w", relationshipsName, err) - } - drawingName := "" - for _, relationship := range relationships.Items { - if strings.HasSuffix(relationship.Type, "/drawing") { - drawingName = xlsxResolveRelationshipTarget(worksheetName, relationship.Target) - break - } - } - if drawingName == "" { - return "", xlsxDrawingDocument{}, nil - } - - drawingData, err := files.read(drawingName) - if err != nil { - return "", xlsxDrawingDocument{}, err - } - var drawing xlsxDrawingDocument - if err := xml.Unmarshal(drawingData, &drawing); err != nil { - return "", xlsxDrawingDocument{}, fmt.Errorf("parse %s: %w", drawingName, err) - } - return drawingName, drawing, nil -} - -func readXLSXCharts(files officePackage, worksheetName string, grid *xlsxGrid) ([]xlsxChart, error) { - drawingName, drawing, err := readXLSXDrawing(files, worksheetName) - if err != nil { - return nil, err - } - anchors := append(drawing.OneCell, drawing.TwoCell...) - hasChart := false - for _, anchor := range anchors { - if anchor.Frame.Reference.ID != "" { - hasChart = true - break - } - } - if !hasChart { - return nil, nil - } - drawingRelationshipsName := xlsxRelationshipPartName(drawingName) - drawingRelationshipsData, err := files.read(drawingRelationshipsName) - if err != nil { - return nil, err - } - var drawingRelationships xlsxRelationshipsDocument - if err := xml.Unmarshal(drawingRelationshipsData, &drawingRelationships); err != nil { - return nil, fmt.Errorf("parse %s: %w", drawingRelationshipsName, err) - } - chartParts := make(map[string]string) - for _, relationship := range drawingRelationships.Items { - if strings.HasSuffix(relationship.Type, "/chart") { - chartParts[relationship.ID] = xlsxResolveRelationshipTarget(drawingName, relationship.Target) - } - } - - charts := make([]xlsxChart, 0, len(anchors)) - for _, anchor := range anchors { - chartName := chartParts[anchor.Frame.Reference.ID] - if chartName == "" { - continue - } - width := float64(anchor.Extension.Width) / xlsxEmuPerPoint - height := float64(anchor.Extension.Height) / xlsxEmuPerPoint - if width <= 0 { - width = grid.columnOffset(anchor.To.Column) - grid.columnOffset(anchor.From.Column) - } - if height <= 0 { - height = grid.rowOffset(anchor.To.Row) - grid.rowOffset(anchor.From.Row) - } - if width <= 0 || height <= 0 { - continue - } - chartData, err := files.read(chartName) - if err != nil { - return nil, err - } - chart, ok := parseXLSXChart(chartData, *grid) - if !ok { - continue - } - chart.anchorRow = anchor.From.Row - chart.anchorColumn = anchor.From.Column - chart.rowOffset = float64(anchor.From.RowOffset) / xlsxEmuPerPoint - chart.columnOffset = float64(anchor.From.ColumnOffset) / xlsxEmuPerPoint - chart.width, chart.height = width, height - charts = append(charts, chart) - grid.extendForChart(chart) - } - return charts, nil -} - -func xlsxRelationshipPartName(partName string) string { - return path.Join(path.Dir(partName), "_rels", path.Base(partName)+".rels") -} - -func xlsxResolveRelationshipTarget(partName, target string) string { - if strings.HasPrefix(target, "/") { - return strings.TrimPrefix(path.Clean(target), "/") - } - return path.Clean(path.Join(path.Dir(partName), target)) -} - -func parseXLSXChart(data []byte, grid xlsxGrid) (xlsxChart, bool) { - var document xlsxChartDocument - if xml.Unmarshal(data, &document) != nil || len(document.Chart.Plot.Bar.Series) == 0 { - return xlsxChart{}, false - } - chart := xlsxChart{ - title: xlsxChartTitle(document.Chart.Title), - categoryTitle: xlsxChartTitle(document.Chart.Plot.CategoryAxis.Title), - valueTitle: xlsxChartTitle(document.Chart.Plot.ValueAxis.Title), - legendPosition: document.Chart.Legend.Position.Value, - gapWidth: document.Chart.Plot.Bar.GapWidth.Value, - } - if chart.gapWidth <= 0 { - chart.gapWidth = 150 - } - for _, source := range document.Chart.Plot.Bar.Series { - name := source.Name - if name == "" { - values := xlsxReferenceValues(grid, source.NameFormula) - if len(values) > 0 { - name = values[0] - } - } - categoryFormula := source.CategoryStr - if categoryFormula == "" { - categoryFormula = source.CategoryNum - } - valueStrings := xlsxReferenceValues(grid, source.Value) - values := make([]float64, len(valueStrings)) - for index, value := range valueStrings { - values[index], _ = strconv.ParseFloat(strings.TrimSpace(value), 64) - } - chart.series = append(chart.series, xlsxChartSeries{ - name: name, categories: xlsxReferenceValues(grid, categoryFormula), values: values, - }) - } - return chart, len(chart.series) > 0 -} - -func xlsxChartTitle(title xlsxChartTitleXML) string { - return strings.Join(title.Runs, "") -} - -func xlsxReferenceValues(grid xlsxGrid, formula string) []string { - if separator := strings.LastIndex(formula, "!"); separator >= 0 { - formula = formula[separator+1:] - } - formula = strings.ReplaceAll(formula, "$", "") - parts := strings.Split(formula, ":") - if len(parts) == 0 || len(parts) > 2 { - return nil - } - startRow, startColumn := xlsxCellPosition(parts[0]) - endRow, endColumn := startRow, startColumn - if len(parts) == 2 { - endRow, endColumn = xlsxCellPosition(parts[1]) - } - if startRow == 0 || startColumn == 0 || endRow < startRow || endColumn < startColumn { - return nil - } - values := make([]string, 0, (endRow-startRow+1)*(endColumn-startColumn+1)) - for row := startRow; row <= endRow; row++ { - for column := startColumn; column <= endColumn; column++ { - values = append(values, grid.cells[[2]int{row, column}].value) - } - } - return values -} - -func (grid xlsxGrid) columnOffset(columnCount int) float64 { - offset := 0.0 - for column := 1; column <= columnCount; column++ { - offset += grid.columnWidth(column) - } - return offset -} - -func (grid xlsxGrid) rowOffset(rowCount int) float64 { - offset := 0.0 - for row := 1; row <= rowCount; row++ { - offset += grid.rowHeight(row) - } - return offset -} - -func (grid *xlsxGrid) extendForChart(chart xlsxChart) { - chartRight := grid.columnOffset(chart.anchorColumn) + chart.columnOffset + chart.width - for column := chart.anchorColumn + 1; grid.columnOffset(column) < chartRight; column++ { - grid.maxColumn = max(grid.maxColumn, column+1) - } - chartBottom := grid.rowOffset(chart.anchorRow) + chart.rowOffset + chart.height - for row := chart.anchorRow + 1; grid.rowOffset(row) < chartBottom; row++ { - grid.maxRow = max(grid.maxRow, row+1) - } -} - -type xlsxChartClip struct { - page *PDFPage - left, bottom, right, top float64 -} - -func (clip xlsxChartClip) line(x1, y1, x2, y2 float64, color PDFColor, width float64) { - if y1 == y2 { - if y1 < clip.bottom || y1 > clip.top { - return - } - x1, x2 = max(x1, clip.left), min(x2, clip.right) - } else if x1 == x2 { - if x1 < clip.left || x1 > clip.right { - return - } - y1, y2 = max(y1, clip.bottom), min(y2, clip.top) - } - if x2 >= x1 && y2 >= y1 { - clip.page.AddLine(x1, y1, x2, y2, color, width) - } -} - -func (clip xlsxChartClip) rect(x, y, width, height float64, color PDFColor) { - left, right := max(x, clip.left), min(x+width, clip.right) - bottom, top := max(y, clip.bottom), min(y+height, clip.top) - if right > left && top > bottom { - clip.page.AddRect(left, bottom, right-left, top-bottom, color) - } -} - -func (clip xlsxChartClip) text(text string, x, y, fontSize float64, color PDFColor, bold bool) { - if text == "" || x >= clip.right || y < clip.bottom || y > clip.top { - return - } - width := float64(len([]rune(text))) * fontSize * 0.52 - if x+width <= clip.left { - return - } - clip.page.AddText(text, x, y, fontSize, color, bold) -} - -func renderXLSXCharts(page *PDFPage, grid xlsxGrid, rows, columns xlsxRange) { - bandLeft := grid.columnOffset(columns.start - 1) - bandTop := grid.rowOffset(rows.start - 1) - bandWidth := grid.columnOffset(columns.end) - bandLeft - bandHeight := grid.rowOffset(rows.end) - bandTop - clip := xlsxChartClip{ - page: page, left: grid.margins.Left, right: grid.margins.Left + bandWidth, - top: grid.pageSize.Height - grid.margins.Top, - bottom: grid.pageSize.Height - grid.margins.Top - bandHeight, - } - for _, chart := range grid.charts { - scale := grid.layoutScale() - chart.columnOffset *= scale - chart.rowOffset *= scale - chart.width *= scale - chart.height *= scale - chartLeft := grid.columnOffset(chart.anchorColumn) + chart.columnOffset - chartTop := grid.rowOffset(chart.anchorRow) + chart.rowOffset - if chartLeft >= bandLeft+bandWidth || chartLeft+chart.width <= bandLeft || - chartTop >= bandTop+bandHeight || chartTop+chart.height <= bandTop { - continue - } - x := grid.margins.Left + chartLeft - bandLeft - top := grid.pageSize.Height - grid.margins.Top - (chartTop - bandTop) - renderXLSXClusteredChart(clip, chart, x, top) - } -} - -func renderXLSXClusteredChart(clip xlsxChartClip, chart xlsxChart, x, top float64) { - border := PDFColor{Red: 0.65, Green: 0.65, Blue: 0.65} - clip.line(x, top, x+chart.width, top, border, 0.5) - clip.line(x+chart.width, top-chart.height, x+chart.width, top, border, 0.5) - clip.line(x, top-chart.height, x+chart.width, top-chart.height, border, 0.5) - clip.line(x, top-chart.height, x, top, border, 0.5) - - const fontSize = 8.0 - titleWidth := float64(len([]rune(chart.title))) * fontSize * 0.52 - clip.text(chart.title, x+(chart.width-titleWidth)/2, top-18, fontSize, PDFColorBlack, true) - legendWidth := 0.0 - if chart.legendPosition == "r" || chart.legendPosition == "tr" { - legendWidth = 52 - } - plotLeft := x + 48 - plotRight := x + chart.width - 16 - legendWidth - plotTop := top - 34 - plotBottom := top - chart.height + 36 - plotWidth, plotHeight := plotRight-plotLeft, plotTop-plotBottom - if plotWidth <= 20 || plotHeight <= 20 { - return - } - - maximum := 0.0 - for _, series := range chart.series { - for _, value := range series.values { - maximum = max(maximum, value) - } - } - axisMaximum, step := xlsxChartAxis(maximum) - gridColor := PDFColor{Red: 0.82, Green: 0.82, Blue: 0.82} - for value := 0.0; value <= axisMaximum+step*0.01; value += step { - y := plotBottom + value/axisMaximum*plotHeight - clip.line(plotLeft, y, plotRight, y, gridColor, 0.5) - } - - categories := 0 - for _, series := range chart.series { - categories = max(categories, len(series.values)) - } - if categories > 0 { - groupWidth := plotWidth / float64(categories) - barWidth := groupWidth / (float64(len(chart.series)) + chart.gapWidth/100) - groupPadding := (groupWidth - barWidth*float64(len(chart.series))) / 2 - colors := []PDFColor{ - {Red: 0.31, Green: 0.506, Blue: 0.741}, - {Red: 0.753, Green: 0.314, Blue: 0.302}, - } - for category := 0; category < categories; category++ { - for seriesIndex, series := range chart.series { - if category >= len(series.values) { - continue - } - height := max(0.5, series.values[category]/axisMaximum*plotHeight) - barX := plotLeft + float64(category)*groupWidth + groupPadding + float64(seriesIndex)*barWidth - clip.rect(barX, plotBottom, barWidth, height, colors[seriesIndex%len(colors)]) - } - } - } - clip.line(plotLeft, plotBottom, plotLeft, plotTop, PDFColorBlack, 0.8) - clip.line(plotLeft, plotBottom, plotRight, plotBottom, PDFColorBlack, 0.8) - clip.text(chart.valueTitle, x+3, plotBottom+plotHeight*0.45, 7, PDFColorBlack, true) - categoryWidth := float64(len([]rune(chart.categoryTitle))) * 7 * 0.52 - clip.text(chart.categoryTitle, plotLeft+(plotWidth-categoryWidth)/2, plotBottom-18, 7, PDFColorBlack, true) - - if legendWidth > 0 { - legendX := plotRight + 12 - legendY := plotBottom + plotHeight*0.5 - colors := []PDFColor{ - {Red: 0.31, Green: 0.506, Blue: 0.741}, - {Red: 0.753, Green: 0.314, Blue: 0.302}, - } - for index, series := range chart.series { - y := legendY - float64(index)*16 - clip.rect(legendX, y, 7, 7, colors[index%len(colors)]) - clip.text(series.name, legendX+11, y, 7, PDFColorBlack, false) - } - } -} - -func xlsxChartAxis(maximum float64) (float64, float64) { - if maximum <= 0 { - return 1, 1 - } - roughStep := maximum / 7 - magnitude := math.Pow(10, math.Floor(math.Log10(roughStep))) - fraction := roughStep / magnitude - niceFraction := 1.0 - if fraction > 1.5 { - niceFraction = 2 - } - if fraction > 3 { - niceFraction = 5 - } - if fraction > 7 { - niceFraction = 10 - } - step := niceFraction * magnitude - return math.Ceil(maximum/step) * step, step -} diff --git a/minipdf-go/xlsx_color.go b/minipdf-go/xlsx_color.go deleted file mode 100644 index 1c8bbac8..00000000 --- a/minipdf-go/xlsx_color.go +++ /dev/null @@ -1,212 +0,0 @@ -package minipdf - -import ( - "bytes" - "encoding/xml" - "fmt" - "io" - "math" - "strings" -) - -type xlsxColorXML struct { - RGB string `xml:"rgb,attr"` - Theme *int `xml:"theme,attr"` - Tint float64 `xml:"tint,attr"` -} - -type xlsxFillXML struct { - Pattern struct { - Type string `xml:"patternType,attr"` - Foreground xlsxColorXML `xml:"fgColor"` - Background xlsxColorXML `xml:"bgColor"` - } `xml:"patternFill"` -} - -func readXLSXTheme(files officePackage) (map[int]PDFColor, error) { - names := []string{"lt1", "dk1", "lt2", "dk2", "accent1", "accent2", "accent3", "accent4", "accent5", "accent6", "hlink", "folHlink"} - defaults := []string{"FFFFFF", "000000", "EEECE1", "1F497D", "4F81BD", "C0504D", "9BBB59", "8064A2", "4BACC6", "F79646", "0000FF", "800080"} - themeName := "xl/theme/theme1.xml" - const relationshipsName = "xl/_rels/workbook.xml.rels" - hasThemeRelationship := false - if _, ok := files[relationshipsName]; ok { - data, err := files.read(relationshipsName) - if err != nil { - return nil, err - } - var relationships xlsxRelationshipsDocument - if err := xml.Unmarshal(data, &relationships); err != nil { - return nil, fmt.Errorf("parse %s: %w", relationshipsName, err) - } - for _, relationship := range relationships.Items { - if strings.HasSuffix(relationship.Type, "/theme") { - if relationship.TargetMode == "External" || strings.TrimSpace(relationship.Target) == "" { - return nil, fmt.Errorf("invalid XLSX theme relationship target %q", relationship.Target) - } - themeName = xlsxResolveRelationshipTarget("xl/workbook.xml", relationship.Target) - hasThemeRelationship = true - break - } - } - } - actualName := "" - for name := range files { - if strings.EqualFold(name, themeName) { - actualName = name - break - } - } - if actualName == "" { - if hasThemeRelationship { - return nil, fmt.Errorf("Office package theme part %q is missing", themeName) - } - colors := make(map[int]PDFColor, len(defaults)) - for index, value := range defaults { - colors[index], _ = parseXLSXColor(value) - } - return colors, nil - } - data, err := files.read(actualName) - if err != nil { - return nil, err - } - colors := make(map[int]PDFColor) - decoder := xml.NewDecoder(bytes.NewReader(data)) - inScheme := false - for { - token, err := decoder.Token() - if err == io.EOF { - break - } - if err != nil { - return nil, fmt.Errorf("parse %s: %w", actualName, err) - } - if end, ok := token.(xml.EndElement); ok && end.Name.Local == "clrScheme" { - inScheme = false - } - start, ok := token.(xml.StartElement) - if !ok { - continue - } - if start.Name.Local == "clrScheme" { - inScheme = true - continue - } - if !inScheme { - continue - } - for index, name := range names { - if start.Name.Local != name { - continue - } - var entry struct { - RGB *struct { - Value string `xml:"val,attr"` - } `xml:"srgbClr"` - System *struct { - Value string `xml:"val,attr"` - Last string `xml:"lastClr,attr"` - } `xml:"sysClr"` - } - if err := decoder.DecodeElement(&entry, &start); err != nil { - return nil, fmt.Errorf("parse %s: %w", actualName, err) - } - value := "" - switch { - case entry.RGB != nil: - value = entry.RGB.Value - case entry.System != nil: - value = entry.System.Last - if value == "" { - switch entry.System.Value { - case "window": - value = "FFFFFF" - case "windowText": - value = "000000" - } - } - } - color, ok := parseXLSXColor(value) - if !ok { - return nil, fmt.Errorf("parse %s: unsupported or invalid theme color %s", actualName, name) - } - colors[index] = color - break - } - } - return colors, nil -} - -func resolveXLSXColor(source xlsxColorXML, theme map[int]PDFColor) (*PDFColor, error) { - if math.IsNaN(source.Tint) || math.IsInf(source.Tint, 0) || source.Tint < -1 || source.Tint > 1 { - return nil, fmt.Errorf("invalid XLSX color tint %v", source.Tint) - } - var color PDFColor - switch { - case source.Theme != nil: - var ok bool - color, ok = theme[*source.Theme] - if !ok { - return nil, fmt.Errorf("unknown XLSX theme color index %d", *source.Theme) - } - case source.RGB != "": - var ok bool - color, ok = parseXLSXColor(source.RGB) - if !ok { - return nil, fmt.Errorf("invalid XLSX RGB color %q", source.RGB) - } - default: - return nil, nil - } - if source.Tint != 0 { - color = tintXLSXColor(color, source.Tint) - } - return &color, nil -} - -func tintXLSXColor(color PDFColor, tint float64) PDFColor { - minimum := min(color.Red, color.Green, color.Blue) - maximum := max(color.Red, color.Green, color.Blue) - luminance := (minimum + maximum) / 2 - chroma := maximum - minimum - saturation, hue := 0.0, 0.0 - if chroma > 0 { - saturation = chroma / (1 - math.Abs(2*luminance-1)) - switch maximum { - case color.Red: - hue = math.Mod((color.Green-color.Blue)/chroma+6, 6) - case color.Green: - hue = (color.Blue-color.Red)/chroma + 2 - case color.Blue: - hue = (color.Red-color.Green)/chroma + 4 - } - } - // Excel tint changes HSL luminance, not the individual RGB channels. - if tint < 0 { - luminance *= 1 + tint - } else { - luminance = luminance*(1-tint) + tint - } - chroma = (1 - math.Abs(2*luminance-1)) * saturation - second := chroma * (1 - math.Abs(math.Mod(hue, 2)-1)) - offset := luminance - chroma/2 - red, green, blue := 0.0, 0.0, 0.0 - switch { - case hue < 1: - red, green = chroma, second - case hue < 2: - red, green = second, chroma - case hue < 3: - green, blue = chroma, second - case hue < 4: - green, blue = second, chroma - case hue < 5: - red, blue = second, chroma - default: - red, blue = chroma, second - } - return PDFColor{ - Red: math.Round((red+offset)*255) / 255, Green: math.Round((green+offset)*255) / 255, - Blue: math.Round((blue+offset)*255) / 255, - } -} diff --git a/minipdf-go/xlsx_color_test.go b/minipdf-go/xlsx_color_test.go deleted file mode 100644 index 8a2a244d..00000000 --- a/minipdf-go/xlsx_color_test.go +++ /dev/null @@ -1,119 +0,0 @@ -package minipdf - -import ( - "math" - "strings" - "testing" -) - -func xlsxStylePackage(t *testing.T, entries map[string]string) officePackage { - t.Helper() - files, err := openOfficePackage(officePackageBytes(t, entries)) - if err != nil { - t.Fatal(err) - } - return files -} - -func TestXLSXThemeColorsAndTint(t *testing.T) { - theme, err := readXLSXTheme(xlsxStylePackage(t, map[string]string{"xl/styles.xml": ""})) - if err != nil { - t.Fatal(err) - } - for _, test := range []struct { - index int - tint float64 - want string - }{ - {0, 0, "FFFFFF"}, {1, 0, "000000"}, {2, 0, "EEECE1"}, {3, 0, "1F497D"}, - {6, 0.6, "D7E4BD"}, {6, -0.5, "4F6228"}, {0, -0.5, "808080"}, - {1, 0.5, "808080"}, {4, -1, "000000"}, {4, 1, "FFFFFF"}, - } { - color, err := resolveXLSXColor(xlsxColorXML{Theme: &test.index, Tint: test.tint}, theme) - want, _ := parseXLSXColor(test.want) - if err != nil || color == nil || *color != want { - t.Errorf("theme %d tint %g = %v, %v; want %s", test.index, test.tint, color, err, test.want) - } - } - color, err := resolveXLSXColor(xlsxColorXML{RGB: "FF92D050"}, theme) - want, _ := parseXLSXColor("92D050") - if err != nil || color == nil || *color != want { - t.Fatalf("RGB = %v, %v; want %v", color, err, want) - } - for _, index := range []int{-1, 12} { - if _, err := resolveXLSXColor(xlsxColorXML{Theme: &index}, theme); err == nil { - t.Errorf("invalid theme index %d accepted", index) - } - } - for _, tint := range []float64{-1.1, 1.1, math.NaN(), math.Inf(1)} { - if _, err := resolveXLSXColor(xlsxColorXML{RGB: "FFFFFF", Tint: tint}, theme); err == nil { - t.Errorf("invalid tint %v accepted", tint) - } - } - if _, err := resolveXLSXColor(xlsxColorXML{RGB: "invalid"}, theme); err == nil { - t.Fatal("invalid RGB accepted") - } - for _, test := range []struct{ source, want string }{ - {"FF0000", "FF8080"}, {"FFFF00", "FFFF80"}, {"00FF00", "80FF80"}, - {"00FFFF", "80FFFF"}, {"0000FF", "8080FF"}, {"FF00FF", "FF80FF"}, - } { - color, err := resolveXLSXColor(xlsxColorXML{RGB: test.source, Tint: 0.5}, theme) - want, _ := parseXLSXColor(test.want) - if err != nil || color == nil || *color != want { - t.Errorf("RGB %s tint 0.5 = %v, %v; want %s", test.source, color, err, test.want) - } - } -} - -func TestXLSXStylesUseRelatedThemeForFontsFillsAndDifferentialFills(t *testing.T) { - entries := map[string]string{ - "xl/_rels/workbook.xml.rels": ``, - "xl/theme/custom.xml": `` + - `` + - `` + - ``, - "xl/styles.xml": `` + - `` + - `` + - ``, - } - styles, fills, err := readXLSXStyles(xlsxStylePackage(t, entries)) - if err != nil { - t.Fatal(err) - } - font, _ := parseXLSXColor("123456") - fill, _ := parseXLSXColor("D7E4BD") - if len(styles) != 1 || styles[0].font.color != font || styles[0].fill == nil || *styles[0].fill != fill { - t.Fatalf("styles = %#v", styles) - } - if len(fills) != 1 || fills[0] == nil || *fills[0] != PDFColorWhite { - t.Fatalf("differential fills = %#v", fills) - } - for _, test := range []struct { - name, part, value, want string - }{ - {"missing target", "xl/_rels/workbook.xml.rels", ``, "missing"}, - {"external target", "xl/_rels/workbook.xml.rels", ``, "invalid"}, - {"malformed theme", "xl/theme/custom.xml", "", "parse"}, - {"missing indexed theme entry", "xl/theme/custom.xml", "", "unknown"}, - {"invalid theme color", "xl/theme/custom.xml", ``, "invalid"}, - } { - t.Run(test.name, func(t *testing.T) { - changed := make(map[string]string, len(entries)) - for name, value := range entries { - changed[name] = value - } - changed[test.part] = test.value - _, _, err := readXLSXStyles(xlsxStylePackage(t, changed)) - if err == nil || !strings.Contains(err.Error(), test.want) { - t.Fatalf("error = %v, want %q", err, test.want) - } - }) - } - entries["xl/theme/custom.xml"] = strings.ReplaceAll(entries["xl/theme/custom.xml"], ` lastClr="123456"`, "") - entries["xl/theme/custom.xml"] = strings.ReplaceAll(entries["xl/theme/custom.xml"], ` lastClr="FFFFFF"`, "") - fallbackStyles, fallbackFills, err := readXLSXStyles(xlsxStylePackage(t, entries)) - if err != nil || fallbackStyles[0].font.color != PDFColorBlack || *fallbackFills[0] != PDFColorWhite { - t.Fatalf("system-color fallback = %#v, %#v, %v", fallbackStyles, fallbackFills, err) - } -} diff --git a/minipdf-go/xlsx_conditional.go b/minipdf-go/xlsx_conditional.go deleted file mode 100644 index fc9a3963..00000000 --- a/minipdf-go/xlsx_conditional.go +++ /dev/null @@ -1,203 +0,0 @@ -package minipdf - -import ( - "fmt" - "regexp" - "sort" - "strconv" - "strings" -) - -type xlsxConditionalFormat struct { - References string `xml:"sqref,attr"` - Rules []xlsxConditionalRule `xml:"cfRule"` - areas []xlsxMerge -} - -type xlsxConditionalRule struct { - Type string `xml:"type,attr"` - Operator string `xml:"operator,attr"` - Text string `xml:"text,attr"` - Format *int `xml:"dxfId,attr"` - Priority int `xml:"priority,attr"` - StopIfTrue bool `xml:"stopIfTrue,attr"` - Formulas []string `xml:"formula"` -} - -var xlsxConditionalSearch = regexp.MustCompile(`(?i)^\s*ISNUMBER\(\s*SEARCH\(\s*"((?:[^"]|"")*)"\s*,\s*(\$?[A-Z]+\$?[1-9][0-9]*)\s*\)\s*\)\s*(?:=\s*TRUE(?:\(\))?)?\s*$`) -var xlsxConditionalReference = regexp.MustCompile(`(?i)^(\$?)([A-Z]+)(\$?)([1-9][0-9]*)$`) - -func (grid *xlsxGrid) applyConditionalFills(styles []xlsxStyle, fills []*PDFColor, scopes []xlsxMerge) ([]xlsxStyle, error) { - type locatedRule struct { - rule xlsxConditionalRule - format xlsxConditionalFormat - } - var rules []locatedRule - for _, format := range grid.conditionalFills { - for _, rule := range format.Rules { - if rule.Priority <= 0 { - return nil, fmt.Errorf("invalid XLSX conditional formatting priority %d", rule.Priority) - } - if rule.Format != nil && (*rule.Format < 0 || *rule.Format >= len(fills)) { - return nil, fmt.Errorf("unknown XLSX differential format index %d", *rule.Format) - } - rules = append(rules, locatedRule{rule, format}) - } - } - sort.SliceStable(rules, func(i, j int) bool { return rules[i].rule.Priority < rules[j].rule.Priority }) - implicitCells := make(map[[2]int]bool) - for _, format := range grid.conditionalFills { - for _, area := range format.areas { - for _, scope := range scopes { - for row := max(area.startRow, scope.startRow); row <= min(area.endRow, scope.endRow); row++ { - for column := max(area.startColumn, scope.startColumn); column <= min(area.endColumn, scope.endColumn); column++ { - key := [2]int{row, column} - if _, exists := grid.cells[key]; !exists { - grid.cells[key] = xlsxCell{row: row, column: column, numeric: true} - implicitCells[key] = true - } - } - } - } - } - } - for key, cell := range grid.cells { - var fill *PDFColor - for _, located := range rules { - inRange := false - for _, area := range located.format.areas { - if cell.row >= area.startRow && cell.row <= area.endRow && cell.column >= area.startColumn && cell.column <= area.endColumn { - inRange = true - break - } - } - if !inRange || !grid.matchesConditionalRule(located.rule, cell, located.format.areas[0]) { - continue - } - if fill == nil && located.rule.Format != nil { - fill = fills[*located.rule.Format] - } - if located.rule.StopIfTrue { - break - } - } - if fill != nil { - style := styleAt(styles, cell.style) - style.fill = fill - cell.style = len(styles) - styles = append(styles, style) - grid.cells[key] = cell - } else if implicitCells[key] { - delete(grid.cells, key) - } - } - return styles, nil -} - -func (grid *xlsxGrid) matchesConditionalRule(rule xlsxConditionalRule, cell xlsxCell, origin xlsxMerge) bool { - switch rule.Type { - case "containsText": - return matchesXLSXSearch(rule.Text, cell.value) - case "notContainsText": - return !matchesXLSXSearch(rule.Text, cell.value) - case "beginsWith": - return strings.HasPrefix(strings.ToLower(cell.value), strings.ToLower(rule.Text)) - case "endsWith": - return strings.HasSuffix(strings.ToLower(cell.value), strings.ToLower(rule.Text)) - case "expression": - if len(rule.Formulas) != 1 { - return false - } - match := xlsxConditionalSearch.FindStringSubmatch(rule.Formulas[0]) - if match == nil { - return false - } - key, ok := conditionalXLSXReference(match[2], cell, origin) - return ok && matchesXLSXSearch(strings.ReplaceAll(match[1], `""`, `"`), grid.cells[key].value) - case "cellIs": - if len(rule.Formulas) == 0 || !cell.numeric { - return false - } - value, ok := grid.evaluateCell([2]int{cell.row, cell.column}, make(map[[2]int]bool)) - if !ok { - return false - } - bounds := make([]float64, len(rule.Formulas)) - for index, formula := range rule.Formulas { - if key, ok := conditionalXLSXReference(strings.TrimSpace(formula), cell, origin); ok { - bounds[index], ok = grid.evaluateCell(key, make(map[[2]int]bool)) - if !ok { - return false - } - } else { - bound, err := strconv.ParseFloat(strings.TrimSpace(formula), 64) - if err != nil { - return false - } - bounds[index] = bound - } - } - switch rule.Operator { - case "equal": - return len(bounds) == 1 && value == bounds[0] - case "notEqual": - return len(bounds) == 1 && value != bounds[0] - case "lessThan": - return len(bounds) == 1 && value < bounds[0] - case "lessThanOrEqual": - return len(bounds) == 1 && value <= bounds[0] - case "greaterThan": - return len(bounds) == 1 && value > bounds[0] - case "greaterThanOrEqual": - return len(bounds) == 1 && value >= bounds[0] - case "between": - return len(bounds) == 2 && value >= bounds[0] && value <= bounds[1] - case "notBetween": - return len(bounds) == 2 && (value < bounds[0] || value > bounds[1]) - } - } - // Other valid conditional-rule formulas retain the existing base style. - return false -} - -func matchesXLSXSearch(pattern, value string) bool { - if !strings.ContainsAny(pattern, "*?~") { - return strings.Contains(strings.ToLower(value), strings.ToLower(pattern)) - } - var expression strings.Builder - expression.WriteString("(?is)") - characters := []rune(pattern) - for index := 0; index < len(characters); index++ { - switch character := characters[index]; character { - case '*': - expression.WriteString(".*") - case '?': - expression.WriteByte('.') - case '~': - if index+1 < len(characters) && strings.ContainsRune("*?~", characters[index+1]) { - index++ - expression.WriteString(regexp.QuoteMeta(string(characters[index]))) - } else { - expression.WriteByte('~') - } - default: - expression.WriteString(regexp.QuoteMeta(string(character))) - } - } - return regexp.MustCompile(expression.String()).MatchString(value) -} - -func conditionalXLSXReference(reference string, cell xlsxCell, origin xlsxMerge) ([2]int, bool) { - match := xlsxConditionalReference.FindStringSubmatch(reference) - if match == nil { - return [2]int{}, false - } - row, column := xlsxCellPosition(strings.ToUpper(match[2]) + match[4]) - if match[1] == "" { - column += cell.column - origin.startColumn - } - if match[3] == "" { - row += cell.row - origin.startRow - } - return [2]int{row, column}, row > 0 && row <= 1048576 && column > 0 && column <= 16384 -} diff --git a/minipdf-go/xlsx_conditional_test.go b/minipdf-go/xlsx_conditional_test.go deleted file mode 100644 index 1a70e52c..00000000 --- a/minipdf-go/xlsx_conditional_test.go +++ /dev/null @@ -1,221 +0,0 @@ -package minipdf - -import ( - "bytes" - "fmt" - "strings" - "testing" -) - -func TestXLSXConditionalResultFillsAreDataDriven(t *testing.T) { - for _, result := range []string{"ACCEPT", "reject", "hold", "pending"} { - t.Run(result, func(t *testing.T) { - worksheet := `` + - `Title` + - fmt.Sprintf(`%s`, result) + - `` + - `ISNUMBER(SEARCH("accept",$H$16))=TRUE` + - `ISNUMBER(SEARCH("reject",$H$16))=TRUE` + - `ISNUMBER(SEARCH("hold",$H$16))=TRUE` + - `` + - `` + - `` + - `` + - `` - grid, err := readXLSXGrid([]byte(worksheet), nil) - if err != nil { - t.Fatal(err) - } - red, _ := parseXLSXColor("FF0000") - green, _ := parseXLSXColor("92D050") - yellow, _ := parseXLSXColor("FFFF00") - white := PDFColorWhite - styles, err := grid.applyConditionalFills([]xlsxStyle{{fill: &red}}, []*PDFColor{&white, &green, &red, &yellow}, nil) - if err != nil { - t.Fatal(err) - } - wantTitle, wantResult := white, green - switch result { - case "reject": - wantResult = red - case "hold": - wantResult = yellow - case "pending": - wantTitle, wantResult = red, red - } - for _, key := range [][2]int{{2, 5}, {2, 6}, {16, 8}} { - want := wantTitle - if key[0] == 16 { - want = wantResult - } - style := styleAt(styles, grid.cells[key].style) - if style.fill == nil || *style.fill != want { - t.Errorf("cell %v fill = %v, want %v", key, style.fill, want) - } - } - }) - } -} - -func TestXLSXConditionalFillsPriorityStopAndRelativeReferences(t *testing.T) { - for _, test := range []struct { - name, rules string - want PDFColor - }{ - {"priority", ``, PDFColorWhite}, - {"stop without fill", ``, PDFColorBlack}, - {"relative column", `ISNUMBER(SEARCH("match",B1))`, PDFColorWhite}, - {"mixed absolute row", `ISNUMBER(SEARCH("match",B$1))`, PDFColorWhite}, - } { - t.Run(test.name, func(t *testing.T) { - grid, err := readXLSXGrid([]byte(``+ - `matchmatch`+ - `match`+ - ``+test.rules+``), nil) - if err != nil { - t.Fatal(err) - } - black, white := PDFColorBlack, PDFColorWhite - styles, err := grid.applyConditionalFills([]xlsxStyle{{fill: &black}}, []*PDFColor{&white, &black}, nil) - if err != nil { - t.Fatal(err) - } - for _, column := range []int{1, 2} { - if fill := styleAt(styles, grid.cells[[2]int{1, column}].style).fill; fill == nil || *fill != test.want { - t.Errorf("column %d fill = %v, want %v", column, fill, test.want) - } - } - if fill := styleAt(styles, grid.cells[[2]int{1, 3}].style).fill; *fill != black { - t.Fatal("conditional fill applied outside sqref") - } - }) - } -} - -func TestXLSXConditionalNumericBoundsAndErrors(t *testing.T) { - for _, operator := range []string{"between", "notBetween"} { - grid, err := readXLSXGrid([]byte(`515`+ - ``+ - `010`), nil) - if err != nil { - t.Fatal(err) - } - black, white := PDFColorBlack, PDFColorWhite - styles, err := grid.applyConditionalFills([]xlsxStyle{{fill: &black}}, []*PDFColor{&white}, nil) - if err != nil { - t.Fatal(err) - } - for _, column := range []int{1, 2} { - want := black - if (operator == "between" && column == 1) || (operator == "notBetween" && column == 2) { - want = white - } - if *styleAt(styles, grid.cells[[2]int{1, column}].style).fill != want { - t.Errorf("%s column %d did not match numeric bounds", operator, column) - } - } - } - for _, rule := range []string{`dxfId="0" priority="0"`, `dxfId="10" priority="1"`} { - grid, err := readXLSXGrid([]byte(``), nil) - if err != nil { - t.Fatal(err) - } - if _, err := grid.applyConditionalFills(nil, nil, nil); err == nil { - t.Fatalf("invalid rule %s accepted", rule) - } - } - for _, reference := range []string{"A0:B1", "R1C1:R2C2", "A1:XFE1", "A1:A1048577", ""} { - _, err := readXLSXGrid([]byte(``), nil) - if err == nil || !strings.Contains(err.Error(), "range") { - t.Fatalf("invalid range %q error = %v", reference, err) - } - } -} - -func TestXLSXConditionalSearchWildcards(t *testing.T) { - for _, test := range []struct { - pattern, value string - want bool - }{ - {"ac*pt", "Status: ACCEPT", true}, {"ac?pt", "accept", false}, - {"ac??pt", "accept", true}, {"~*", "literal *", true}, - {"~*", "accept", false}, {"~~", "~", true}, {`"accept"`, `"ACCEPT"`, true}, - } { - if got := matchesXLSXSearch(test.pattern, test.value); got != test.want { - t.Errorf("SEARCH(%q, %q) = %v, want %v", test.pattern, test.value, got, test.want) - } - } -} - -func TestConvertXLSXPrintedConditionalFills(t *testing.T) { - entries := map[string]string{ - "xl/workbook.xml": `` + - `Report!$A$1:$B$1`, - "xl/styles.xml": `` + - `` + - `` + - ``, - "xl/worksheets/sheet1.xml": `Accept` + - `` + - `ISNUMBER(SEARCH("accept",$A$1))=TRUE`, - } - pdf, err := ConvertBytesToPDF(officePackageBytes(t, entries)) - assertPDFContains(t, pdf, err, "Accept") - if bytes.Contains(pdf, []byte("1 0 0 rg")) { - t.Fatal("printed grid retained red base fill instead of conditional theme-white fill") - } - if bytes.Count(pdf, []byte("1 1 1 rg")) != 2 { - t.Fatal("printed grid did not paint conditional fill on both stored and implicit blank cells") - } - if bytes.Count(pdf, []byte("/Type /Page ")) != 1 { - t.Fatal("conditional styles changed the printed page count") - } - limited, err := ConvertBytesToPDFWithOptions(officePackageBytes(t, entries), ConversionOptions{MaxColumns: 1}) - if err != nil { - t.Fatal(err) - } - if bytes.Count(limited, []byte("1 1 1 rg")) != 1 { - t.Fatal("conditional fills ignored the printed column limit") - } -} - -func TestXLSXImplicitConditionalFillsStayWithinPrintedScope(t *testing.T) { - for _, value := range []string{"Accept", "Pending"} { - grid, err := readXLSXGrid([]byte(``+ - value+``+ - `ISNUMBER(SEARCH("accept",$A$1))`+ - ``), nil) - if err != nil { - t.Fatal(err) - } - white := PDFColorWhite - _, err = grid.applyConditionalFills(nil, []*PDFColor{&white}, []xlsxMerge{{startRow: 1, endRow: 2, startColumn: 1, endColumn: 2}}) - if err != nil { - t.Fatal(err) - } - wantCells := 1 - if value == "Accept" { - wantCells = 4 - } - if len(grid.cells) != wantCells || grid.maxRow != 1 || grid.maxColumn != 1 { - t.Errorf("%s: cells = %d, dimensions = %d/%d; conditional fills expanded print scope or retained unmatched blanks", - value, len(grid.cells), grid.maxRow, grid.maxColumn) - } - } -} - -func TestXLSXConditionalMixedAbsoluteReferences(t *testing.T) { - origin := xlsxMerge{startRow: 3, startColumn: 3} - cell := xlsxCell{row: 5, column: 4} - for _, test := range []struct { - reference string - want [2]int - }{ - {"A1", [2]int{3, 2}}, {"$A1", [2]int{3, 1}}, - {"A$1", [2]int{1, 2}}, {"$A$1", [2]int{1, 1}}, - } { - if got, ok := conditionalXLSXReference(test.reference, cell, origin); !ok || got != test.want { - t.Errorf("%s = %v/%v, want %v", test.reference, got, ok, test.want) - } - } -} diff --git a/minipdf-go/xlsx_font.go b/minipdf-go/xlsx_font.go deleted file mode 100644 index 6e3b8bcb..00000000 --- a/minipdf-go/xlsx_font.go +++ /dev/null @@ -1,96 +0,0 @@ -package minipdf - -import ( - "fmt" - "os" - "path/filepath" - "runtime" - "strings" - - "golang.org/x/image/font" - "golang.org/x/image/font/sfnt" - "golang.org/x/image/math/fixed" -) - -func readXLSXFont(name string, bold, italic bool) (*embeddedFont, error) { - variant := name - if bold { - variant += " Bold" - } - if italic { - variant += " Italic" - } - normalize := func(value string) string { - return strings.ToLower(strings.NewReplacer(" ", "", "-", "").Replace(value)) - } - newFont := func(data []byte) (*embeddedFont, error) { - parsed, err := sfnt.Parse(data) - if err != nil { - return nil, fmt.Errorf("parse XLSX font %q: %w", variant, err) - } - if parsed.UnitsPerEm() == 0 { - return nil, fmt.Errorf("invalid XLSX font %q units-per-em", variant) - } - advances := make([]float64, parsed.NumGlyphs()) - metrics, err := parsed.Metrics(nil, fixed.Int26_6(parsed.UnitsPerEm()), font.HintingNone) - if err != nil { - return nil, fmt.Errorf("read XLSX font %q metrics: %w", variant, err) - } - for index := range advances { - advance, err := parsed.GlyphAdvance(nil, sfnt.GlyphIndex(index), fixed.Int26_6(parsed.UnitsPerEm()), font.HintingNone) - if err != nil { - return nil, fmt.Errorf("read XLSX font %q glyph metrics: %w", variant, err) - } - advances[index] = float64(advance) / float64(parsed.UnitsPerEm()) - } - return &embeddedFont{name: sanitizePDFFontName(variant), data: data, font: parsed, advances: advances, - ascent: float64(metrics.Ascent) / float64(parsed.UnitsPerEm()), descent: float64(metrics.Descent) / float64(parsed.UnitsPerEm()), - runeToGlyph: make(map[rune]sfnt.GlyphIndex), glyphToRune: make(map[sfnt.GlyphIndex]rune)}, nil - } - for _, registered := range RegisteredFonts() { - if normalize(registered.Name) == normalize(variant) { - return newFont(registered.Data) - } - } - if runtime.GOOS != "windows" { - return nil, nil - } - index := 0 - if bold { - index++ - } - if italic { - index += 2 - } - var files []string - switch strings.ToLower(name) { - case "calibri": - files = []string{"calibri.ttf", "calibrib.ttf", "calibrii.ttf", "calibriz.ttf"} - case "arial": - files = []string{"arial.ttf", "arialbd.ttf", "ariali.ttf", "arialbi.ttf"} - default: - return nil, nil - } - windows := os.Getenv("WINDIR") - if windows == "" { - return nil, nil - } - path := filepath.Join(windows, "Fonts", files[index]) - data, err := os.ReadFile(path) - if os.IsNotExist(err) { - return nil, nil - } - if err != nil { - return nil, fmt.Errorf("read XLSX font %s: %w", path, err) - } - return newFont(data) -} - -func measureXLSXFont(text string, size float64, embedded *embeddedFont) float64 { - embedded.collect(text) - width := 0.0 - for _, character := range normalizedFontRunes(text) { - width += embedded.advances[embedded.runeToGlyph[character]] * size - } - return width -} diff --git a/minipdf-go/xlsx_footer.go b/minipdf-go/xlsx_footer.go deleted file mode 100644 index 58cec140..00000000 --- a/minipdf-go/xlsx_footer.go +++ /dev/null @@ -1,190 +0,0 @@ -package minipdf - -import ( - "fmt" - "strconv" - "strings" -) - -type xlsxHeaderFooter struct { - Odd string `xml:"oddFooter"` - Even string `xml:"evenFooter"` - First string `xml:"firstFooter"` - DifferentFirst bool `xml:"differentFirst,attr"` - DifferentOddEven bool `xml:"differentOddEven,attr"` - ScaleWithDoc *bool `xml:"scaleWithDoc,attr"` - runs [3][]xlsxFooterRun -} - -type xlsxFooterRun struct { - text string - field byte - portion, line int - font xlsxFont -} - -func parseXLSXFooter(value string, defaultFont xlsxFont, sheetName string) ([]xlsxFooterRun, error) { - current := defaultFont - if current.size <= 0 { - current.size = 11 - } - portion := 1 - lines := [3]int{} - var text strings.Builder - var runs []xlsxFooterRun - flush := func() { - if text.Len() > 0 { - runs = append(runs, xlsxFooterRun{text: text.String(), portion: portion, line: lines[portion], font: current}) - text.Reset() - } - } - for index := 0; index < len(value); index++ { - switch value[index] { - case '\n': - flush() - lines[portion]++ - case '&': - index++ - if index >= len(value) { - return nil, fmt.Errorf("incomplete XLSX footer control code") - } - switch token := value[index]; token { - case '&': - text.WriteByte('&') - case 'L', 'C', 'R': - flush() - portion = map[byte]int{'L': 0, 'C': 1, 'R': 2}[token] - case 'P', 'N': - flush() - runs = append(runs, xlsxFooterRun{field: token, portion: portion, line: lines[portion], font: current}) - case 'A': - text.WriteString(sheetName) - case 'B', 'I': - flush() - if token == 'B' { - current.bold = !current.bold - } else { - current.italic = !current.italic - } - var err error - current.embedded, err = readXLSXFont(current.name, current.bold, current.italic) - if err != nil { - return nil, err - } - case '"': - flush() - end := strings.IndexByte(value[index+1:], '"') - if end < 0 { - return nil, fmt.Errorf("unclosed XLSX footer font") - } - descriptor := strings.SplitN(value[index+1:index+1+end], ",", 2) - current.name = descriptor[0] - current.bold, current.italic = false, false - if len(descriptor) > 1 { - current.bold = strings.Contains(strings.ToLower(descriptor[1]), "bold") - current.italic = strings.Contains(strings.ToLower(descriptor[1]), "italic") - } - var err error - current.embedded, err = readXLSXFont(current.name, current.bold, current.italic) - if err != nil { - return nil, err - } - index += end + 1 - default: - if token >= '0' && token <= '9' { - flush() - end := index + 1 - for end < len(value) && ((value[end] >= '0' && value[end] <= '9') || value[end] == '.') { - end++ - } - size, err := strconv.ParseFloat(value[index:end], 64) - if err != nil || size <= 0 || size > 409 { - return nil, fmt.Errorf("invalid XLSX footer font size %q", value[index:end]) - } - current.size = size - index = end - 1 - } else { - return nil, fmt.Errorf("unsupported XLSX footer control code &%c", token) - } - } - default: - text.WriteByte(value[index]) - } - } - flush() - return runs, nil -} - -func (grid *xlsxGrid) prepareFooters(styles []xlsxStyle, sheetName string) error { - defaultFont := styleAt(styles, 0).font - for index, value := range []string{grid.headerFooter.Odd, grid.headerFooter.Even, grid.headerFooter.First} { - runs, err := parseXLSXFooter(value, defaultFont, sheetName) - if err != nil { - return err - } - grid.headerFooter.runs[index] = runs - } - return nil -} - -func xlsxFooterDecoration(grid xlsxGrid, scale float64, localPage int) func(int, int) []pdfOperation { - if grid.headerFooter.Odd == "" && grid.headerFooter.Even == "" && grid.headerFooter.First == "" { - return nil - } - if grid.headerFooter.ScaleWithDoc != nil && !*grid.headerFooter.ScaleWithDoc { - scale = 1 - } - return func(pageNumber, total int) []pdfOperation { - runs := grid.headerFooter.runs[0] - if grid.headerFooter.DifferentFirst && localPage == 1 { - runs = grid.headerFooter.runs[2] - } else if grid.headerFooter.DifferentOddEven && pageNumber%2 == 0 { - runs = grid.headerFooter.runs[1] - } - type lineKey struct{ portion, line int } - widths := make(map[lineKey]float64) - counts := [3]int{} - var operations []textOperation - keys := make([]lineKey, 0, len(runs)) - lineHeight := 0.0 - for _, run := range runs { - value := run.text - if run.field == 'P' { - value = strconv.Itoa(pageNumber) - } else if run.field == 'N' { - value = strconv.Itoa(total) - } - size := run.font.size * scale - lineHeight = max(lineHeight, size*1.4) - counts[run.portion] = max(counts[run.portion], run.line+1) - embedded := run.font.embedded - if embedded != nil && !embedded.canEncode(value) { - embedded = nil - } - width := measureHelveticaText(value, size, 100, run.font.bold) - if embedded != nil { - width = measureXLSXFont(value, size, embedded) - } - key := lineKey{run.portion, run.line} - operations = append(operations, textOperation{text: value, x: widths[key], fontSize: size, horizontalScale: 100, color: run.font.color, - bold: run.font.bold, italic: run.font.italic, embedded: embedded}) - keys = append(keys, key) - widths[key] += width - } - result := make([]pdfOperation, 0, len(operations)) - for index, operation := range operations { - key := keys[index] - switch key.portion { - case 0: - operation.x += grid.margins.Left - case 1: - operation.x += (grid.pageSize.Width - widths[key]) / 2 - case 2: - operation.x += grid.pageSize.Width - grid.margins.Right - widths[key] - } - operation.y = grid.footerMargin + float64(counts[key.portion]-key.line-1)*lineHeight + operation.fontSize*0.3 - result = append(result, operation) - } - return result - } -} diff --git a/minipdf-go/xlsx_layout_test.go b/minipdf-go/xlsx_layout_test.go deleted file mode 100644 index 89eb56b8..00000000 --- a/minipdf-go/xlsx_layout_test.go +++ /dev/null @@ -1,269 +0,0 @@ -package minipdf - -import ( - "bytes" - "image" - "image/color" - "image/png" - "math" - "strings" - "testing" - - "golang.org/x/image/font/gofont/gobold" - "golang.org/x/image/font/gofont/goregular" -) - -func TestPrintedXLSXNumberFormats(t *testing.T) { - for _, test := range []struct { - value string - id int - code string - date1904 bool - want string - }{ - {"46046", 164, `dd\-mmm\-yyyy`, false, "24-Jan-2026"}, - {"1", 164, "yyyy-mm-dd", false, "1900-01-01"}, - {"0", 164, "dd-mmm-yyyy", false, "00-Jan-1900"}, - {"1", 164, "dddd", false, "Sunday"}, - {"59", 164, "yyyy-mm-dd", false, "1900-02-28"}, - {"60", 164, "yyyy-mm-dd", false, "1900-02-29"}, - {"61", 164, "yyyy-mm-dd", false, "1900-03-01"}, - {"0", 164, "yyyy-mm-dd", true, "1904-01-01"}, - {"46087", 14, "", false, "3/6/2026"}, - {"61859", 3, "", false, "61,859"}, - {"-1234.567", 4, "", false, "-1,234.57"}, - {"1.25", 165, "0.0", false, "1.3"}, - {"1.5", 165, "0.##", false, "1.5"}, - {"0.125", 9, "", false, "13%"}, - {"132.22999999999999", 0, "", false, "132.23"}, - {"123.4", 164, "[Red]0.00", false, "123.4"}, - {"-123.4", 164, "[Red]0.00", false, "-123.4"}, - {"123.4", 164, `0.0"days"`, false, "123.4"}, - } { - value, err := formatPrintedXLSXValue(test.value, test.id, test.code, test.date1904) - if err != nil || value != test.want { - t.Errorf("%q format %d/%q date1904=%v = %q, %v; want %q", test.value, test.id, test.code, test.date1904, value, err, test.want) - } - } - for _, value := range []string{"invalid", "NaN", "Inf"} { - if _, err := formatPrintedXLSXValue(value, 0, "", false); err == nil { - t.Errorf("invalid numeric value %q accepted", value) - } - if _, err := formatPrintedXLSXValue("2957004", 164, "yyyy-mm-dd", true); err == nil { - t.Fatal("1904 date beyond year 9999 accepted") - } - } -} - -func TestXLSXPrintCenteringIncludesRepeatedColumns(t *testing.T) { - grid, err := readXLSXGrid([]byte(``+ - `TitleBody`+ - ``), nil) - if err != nil { - t.Fatal(err) - } - document := NewPDFDocument() - settings := xlsxPrintSettings{areas: []xlsxMerge{{startRow: 1, endRow: 1, startColumn: 2, endColumn: 2}}, columns: xlsxRange{start: 1, end: 1}} - if err := renderXLSXPrintGrid(document, grid, nil, settings, ConversionOptions{}); err != nil { - t.Fatal(err) - } - width := grid.columnWidth(1) + grid.columnWidth(2) - wantX := (grid.pageSize.Width-width)/2 + 1.5 - for _, operation := range document.pages[0].operations { - text, ok := operation.(textOperation) - if ok && text.text == "Title" { - if math.Abs(text.x-wantX) > 1e-6 { - t.Errorf("repeated column x = %g, want %g", text.x, wantX) - } - if text.y < grid.pageSize.Height/2-20 || text.y > grid.pageSize.Height/2+20 { - t.Errorf("vertical centering y = %g", text.y) - } - return - } - } - t.Fatal("missing repeated column") -} - -func TestXLSXFooterUsesFinalDocumentPageCountWithoutMutation(t *testing.T) { - grid, err := readXLSXGrid([]byte(`Body`+ - `&L&6 Left && literal Second&CPage &P of &N&R&A`), nil) - if err != nil { - t.Fatal(err) - } - if err := grid.prepareFooters(nil, "Report"); err != nil { - t.Fatal(err) - } - doc := NewPDFDocument() - settings := xlsxPrintSettings{areas: []xlsxMerge{{startRow: 1, endRow: 1, startColumn: 1, endColumn: 1}}} - for i := 0; i < 2; i++ { - if err := renderXLSXPrintGrid(doc, grid, nil, settings, ConversionOptions{}); err != nil { - t.Fatal(err) - } - } - count := len(doc.pages[0].operations) - pdf := doc.Bytes() - for _, text := range []string{"Left & literal", "Second", "Report"} { - if !bytes.Contains(pdf, []byte(text)) { - t.Errorf("missing footer %q", text) - } - } - for page := 1; page <= 2; page++ { - operations := doc.pages[page-1].decorations(page, 2) - var text strings.Builder - for _, operation := range operations { - text.WriteString(operation.(textOperation).text) - } - if !strings.Contains(text.String(), "Page "+string(rune('0'+page))+" of 2") { - t.Errorf("footer = %q", text.String()) - } - } - if len(doc.pages[0].operations) != count || !bytes.Equal(pdf, doc.Bytes()) { - t.Fatal("PDF serialization mutated or duplicated footers") - } -} - -func TestXLSXFooterFirstEvenAndUnscaledVariants(t *testing.T) { - grid, err := readXLSXGrid([]byte(``+ - `&6Odd&6Even&6First`+ - ``), nil) - if err != nil { - t.Fatal(err) - } - if err := grid.prepareFooters(nil, "Sheet"); err != nil { - t.Fatal(err) - } - for _, test := range []struct { - local, global int - want string - }{{1, 3, "First"}, {2, 4, "Even"}, {3, 5, "Odd"}} { - operations := xlsxFooterDecoration(grid, 0.5, test.local)(test.global, 5) - if len(operations) != 1 { - t.Fatal(operations) - } - text := operations[0].(textOperation) - if text.text != test.want || text.fontSize != 6 { - t.Errorf("footer = %#v", text) - } - } - if _, err := parseXLSXFooter(`&"Unclosed`, xlsxFont{size: 11}, ""); err == nil { - t.Fatal("unclosed footer font accepted") - } -} - -func TestXLSXPictureCropRelationshipAndTitleRepeat(t *testing.T) { - source := image.NewRGBA(image.Rect(0, 0, 8, 6)) - for y := 0; y < 6; y++ { - for x := 0; x < 8; x++ { - source.Set(x, y, color.RGBA{R: uint8(x * 20), G: uint8(y * 30), A: 255}) - } - } - var encoded bytes.Buffer - if err := png.Encode(&encoded, source); err != nil { - t.Fatal(err) - } - entries := map[string]string{ - "xl/worksheets/sheet1.xml": ``, - "xl/worksheets/_rels/sheet1.xml.rels": ``, - "xl/drawings/drawing1.xml": `00` + - ``, - "xl/drawings/_rels/drawing1.xml.rels": ``, - "xl/media/logo.png": string(encoded.Bytes()), - } - grid, err := readXLSXGrid([]byte(``+ - ``), nil) - if err != nil { - t.Fatal(err) - } - pictures, err := readXLSXPictures(xlsxStylePackage(t, entries), "xl/worksheets/sheet1.xml", grid) - if err != nil { - t.Fatal(err) - } - if len(pictures) != 1 || pictures[0].image.pixelWidth != 4 || pictures[0].image.pixelHeight != 6 { - t.Fatalf("pictures = %#v", pictures) - } - grid.pictures = pictures - doc := NewPDFDocument() - settings := xlsxPrintSettings{areas: []xlsxMerge{{startRow: 1, endRow: 3, startColumn: 1, endColumn: 1}}, rows: xlsxRange{start: 1, end: 1}} - if err := renderXLSXPrintGrid(doc, grid, nil, settings, ConversionOptions{}); err != nil { - t.Fatal(err) - } - if len(doc.pages) != 2 { - t.Fatal("missing page break") - } - for _, page := range doc.pages { - images := 0 - for _, operation := range page.operations { - if _, ok := operation.(imageOperation); ok { - images++ - } - } - if images != 1 { - t.Errorf("repeated logo count = %d, want 1", images) - } - } - if !bytes.Contains(doc.Bytes(), []byte("/ASCIIHexDecode /FlateDecode")) { - t.Fatal("missing inline raster image") - } - delete(entries, "xl/drawings/_rels/drawing1.xml.rels") - if _, err := readXLSXPictures(xlsxStylePackage(t, entries), "xl/worksheets/sheet1.xml", grid); err == nil { - t.Fatal("missing picture relationship part accepted") - } -} - -func TestPrintedXLSXNamedFontVariantsAndWidths(t *testing.T) { - ClearRegisteredFonts() - defer ClearRegisteredFonts() - RegisterFont("Unit Font", goregular.TTF) - RegisterFont("Unit Font Bold", gobold.TTF) - regular, err := readXLSXFont("Unit Font", false, false) - if err != nil { - t.Fatal(err) - } - bold, err := readXLSXFont("Unit Font", true, false) - if err != nil { - t.Fatal(err) - } - if regular == nil || bold == nil || bytes.Equal(regular.data, bold.data) { - t.Fatal("font variants were not resolved independently") - } - width := measureXLSXFont("00", 10, regular) - if math.Abs(width-2*measureXLSXFont("0", 10, regular)) > 1e-9 { - t.Fatal("font advance widths are inconsistent") - } - doc := NewPDFDocument() - page := doc.AddPage(200, 200) - renderXLSXCellText(page, xlsxCell{value: "Regular"}, 0, 100, 100, 20, xlsxStyle{font: xlsxFont{size: 10, embedded: regular}}) - renderXLSXCellText(page, xlsxCell{value: "Bold"}, 0, 70, 100, 20, xlsxStyle{font: xlsxFont{size: 10, bold: true, embedded: bold}}) - pdf := doc.Bytes() - if bytes.Count(pdf, []byte("/Subtype /Type0")) != 2 { - t.Fatal("PDF did not embed both named font variants") - } - if !bytes.Contains(pdf, []byte("/FU1")) || !bytes.Contains(pdf, []byte("/FU2")) { - t.Fatal("missing font resources") - } - if !bytes.Equal(pdf, doc.Bytes()) { - t.Fatal("font serialization is not repeatable") - } - shrunk := doc.AddPage(200, 200) - renderXLSXCellText(shrunk, xlsxCell{value: "0000000000"}, 0, 0, 20, 20, xlsxStyle{shrink: true, font: xlsxFont{size: 10, embedded: regular}}) - text := shrunk.operations[0].(textOperation) - if text.fontSize >= 10 || measureXLSXFont(text.text, text.fontSize, regular) > 16+1e-8 { - t.Fatal("shrink-to-fit does not use the selected font's advance widths") - } - if math.Abs(text.y-text.fontSize*regular.descent) > 1e-8 { - t.Fatal("bottom alignment ignored actual font descent") - } -} - -func TestXLSXDoubleBordersKeepTwoSeparateStrokes(t *testing.T) { - page := NewPDFDocument().AddPage(100, 100) - renderXLSXCell(page, xlsxCell{}, 10, 10, 20, 20, xlsxStyle{border: xlsxBorder{bottom: 1.5, bottomDouble: true}}, false) - if len(page.operations) != 2 { - t.Fatal("double border was rendered as a single thick line") - } - first := page.operations[0].(lineOperation) - second := page.operations[1].(lineOperation) - if first.y1 == second.y1 || first.width != 0.5 || second.width != 0.5 { - t.Fatalf("double border = %#v / %#v", first, second) - } -} diff --git a/minipdf-go/xlsx_number.go b/minipdf-go/xlsx_number.go deleted file mode 100644 index 1b1b78b5..00000000 --- a/minipdf-go/xlsx_number.go +++ /dev/null @@ -1,192 +0,0 @@ -package minipdf - -import ( - "fmt" - "math" - "regexp" - "strconv" - "strings" - "time" -) - -var xlsxSimpleNumberFormat = regexp.MustCompile(`^[#0]+(?:,[#0]+)*(?:\.[0#]+)?%?$`) - -func formatPrintedXLSXValue(value string, id int, code string, date1904 bool) (string, error) { - number, err := strconv.ParseFloat(strings.TrimSpace(value), 64) - if err != nil || math.IsNaN(number) || math.IsInf(number, 0) { - return "", fmt.Errorf("invalid numeric XLSX value %q", value) - } - if code == "" { - code = map[int]string{1: "0", 2: "0.00", 3: "#,##0", 4: "#,##0.00", 9: "0%", 10: "0.00%", 14: "m/d/yyyy", 15: "d-mmm-yy", 16: "d-mmm", 17: "mmm-yy"}[id] - } - if code == "" && id == 0 { - return strconv.FormatFloat(number, 'g', 15, 64), nil - } - datePattern, quoted, bracket := false, false, false - for index := 0; index < len(code); index++ { - if code[index] == '\\' { - index++ - if index >= len(code) { - return "", fmt.Errorf("incomplete XLSX format escape %q", code) - } - } else if code[index] == '"' { - quoted = !quoted - } else if !quoted && code[index] == '[' { - bracket = true - } else if !quoted && code[index] == ']' { - bracket = false - } else if !quoted && !bracket && strings.ContainsAny(strings.ToLower(code[index:index+1]), "dy") { - datePattern = true - } - } - if quoted { - return "", fmt.Errorf("unclosed XLSX format literal %q", code) - } - if datePattern { - maximum := 2958465.0 - if date1904 { - maximum -= 1462 - } - if number < 0 || number > maximum { - return "", fmt.Errorf("XLSX date serial %g is outside the supported range", number) - } - day := int(math.Floor(number)) - date := time.Date(1899, 12, 31, 0, 0, 0, 0, time.UTC) - if date1904 { - date = time.Date(1904, 1, 1, 0, 0, 0, 0, time.UTC) - } else if day >= 60 { - day-- - } - date = date.AddDate(0, 0, day) - dayOfMonth := date.Day() - weekday := date.Weekday() - if !date1904 && int(number) < 61 { - weekday = time.Weekday((int(number) + 6) % 7) - } - if !date1904 && int(number) == 0 { - date = time.Date(1900, 1, 1, 0, 0, 0, 0, time.UTC) - dayOfMonth = 0 - } - if !date1904 && int(number) == 60 { - dayOfMonth = 29 - } - var output strings.Builder - for index := 0; index < len(code); { - character := code[index] - if character == '\\' { - index++ - if index >= len(code) { - return "", fmt.Errorf("incomplete XLSX format escape %q", code) - } - output.WriteByte(code[index]) - index++ - continue - } - if character == '"' { - end := strings.IndexByte(code[index+1:], '"') - if end < 0 { - return "", fmt.Errorf("unclosed XLSX format literal %q", code) - } - output.WriteString(code[index+1 : index+1+end]) - index += end + 2 - continue - } - lower := strings.ToLower(string(character)) - end := index + 1 - for end < len(code) && strings.EqualFold(code[end:end+1], lower) { - end++ - } - count := end - index - switch lower { - case "d": - switch count { - case 1: - output.WriteString(strconv.Itoa(dayOfMonth)) - case 2: - fmt.Fprintf(&output, "%02d", dayOfMonth) - case 3: - output.WriteString(weekday.String()[:3]) - case 4: - output.WriteString(weekday.String()) - default: - return value, nil - } - case "m": - switch count { - case 1: - output.WriteString(strconv.Itoa(int(date.Month()))) - case 2: - fmt.Fprintf(&output, "%02d", date.Month()) - case 3: - output.WriteString(date.Format("Jan")) - case 4: - output.WriteString(date.Format("January")) - default: - return value, nil - } - case "y": - if count == 2 { - fmt.Fprintf(&output, "%02d", date.Year()%100) - } else if count == 4 { - fmt.Fprintf(&output, "%04d", date.Year()) - } else { - return value, nil - } - default: - if (character >= 'A' && character <= 'Z') || (character >= 'a' && character <= 'z') || strings.ContainsRune("[];_", rune(character)) { - return value, nil - } - output.WriteString(code[index:end]) - } - index = end - } - return output.String(), nil - } - if !xlsxSimpleNumberFormat.MatchString(code) { - return value, nil - } - percent := strings.HasSuffix(code, "%") - if percent { - number *= 100 - code = strings.TrimSuffix(code, "%") - } - precision, minimum := 0, 0 - if index := strings.IndexByte(code, '.'); index >= 0 { - fraction := code[index+1:] - precision = len(fraction) - minimum = strings.Count(fraction, "0") - } - if precision > 30 { - return value, nil - } - factor := math.Pow10(precision) - if math.Abs(number) <= math.MaxFloat64/factor { - number = math.Round(number*factor) / factor - } - formatted := strconv.FormatFloat(number, 'f', precision, 64) - parts := strings.SplitN(formatted, ".", 2) - digits := parts[0] - sign := "" - if strings.HasPrefix(digits, "-") { - sign, digits = "-", digits[1:] - } - if strings.Contains(code, ",") { - for index := len(digits) - 3; index > 0; index -= 3 { - digits = digits[:index] + "," + digits[index:] - } - } - result := sign + digits - if len(parts) > 1 { - fraction := parts[1] - for len(fraction) > minimum && strings.HasSuffix(fraction, "0") { - fraction = strings.TrimSuffix(fraction, "0") - } - if fraction != "" { - result += "." + fraction - } - } - if percent { - result += "%" - } - return result, nil -} diff --git a/minipdf-go/xlsx_picture.go b/minipdf-go/xlsx_picture.go deleted file mode 100644 index 6f27a503..00000000 --- a/minipdf-go/xlsx_picture.go +++ /dev/null @@ -1,122 +0,0 @@ -package minipdf - -import ( - "bytes" - "encoding/xml" - "fmt" - "image" - _ "image/gif" - _ "image/jpeg" - _ "image/png" - "math" - "strings" -) - -type xlsxPicture struct { - anchorRow, anchorColumn int - rowOffset, columnOffset, width, height float64 - image imageOperation -} - -func readXLSXPictures(files officePackage, worksheetName string, grid xlsxGrid) ([]xlsxPicture, error) { - name, drawing, err := readXLSXDrawing(files, worksheetName) - if err != nil { - return nil, err - } - anchors := append(drawing.OneCell, drawing.TwoCell...) - var pictures []xlsxPicture - var targets map[string]string - for _, anchor := range anchors { - if anchor.Picture == nil || (anchor.Client.Print != nil && !*anchor.Client.Print) { - continue - } - if anchor.From.Row < 0 || anchor.From.Row >= 1048576 || anchor.From.Column < 0 || anchor.From.Column >= 16384 || - anchor.From.RowOffset < 0 || anchor.From.ColumnOffset < 0 || anchor.To.Row > 1048576 || anchor.To.Column > 16384 { - return nil, fmt.Errorf("invalid XLSX picture anchor in %s", name) - } - if targets == nil { - part := xlsxRelationshipPartName(name) - data, err := files.read(part) - if err != nil { - return nil, err - } - var relationships xlsxRelationshipsDocument - if err := xml.Unmarshal(data, &relationships); err != nil { - return nil, fmt.Errorf("parse %s: %w", part, err) - } - targets = make(map[string]string) - for _, relationship := range relationships.Items { - if strings.HasSuffix(relationship.Type, "/image") { - if relationship.TargetMode == "External" { - return nil, fmt.Errorf("unsupported external XLSX picture %s", relationship.ID) - } - targets[relationship.ID] = xlsxResolveRelationshipTarget(name, relationship.Target) - } - } - } - target := targets[anchor.Picture.Fill.Blip.ID] - if target == "" { - return nil, fmt.Errorf("missing XLSX picture relationship %q", anchor.Picture.Fill.Blip.ID) - } - data, err := files.read(target) - if err != nil { - return nil, err - } - config, _, err := image.DecodeConfig(bytes.NewReader(data)) - if err != nil { - return nil, fmt.Errorf("decode XLSX picture %s: %w", target, err) - } - if config.Width <= 0 || config.Height <= 0 || int64(config.Width) > 25000000/int64(config.Height) { - return nil, fmt.Errorf("XLSX picture %s exceeds 25 million pixels", target) - } - source, _, err := image.Decode(bytes.NewReader(data)) - if err != nil { - return nil, fmt.Errorf("decode XLSX picture %s: %w", target, err) - } - crop := anchor.Picture.Fill.Crop - if min(crop.Left, crop.Right, crop.Top, crop.Bottom) < 0 || max(crop.Left, crop.Right, crop.Top, crop.Bottom) > 100000 || - crop.Left+crop.Right >= 100000 || crop.Top+crop.Bottom >= 100000 { - return nil, fmt.Errorf("unsupported XLSX picture crop in %s", name) - } - bounds := source.Bounds() - left := bounds.Min.X + int(math.Round(float64(bounds.Dx()*crop.Left)/100000)) - top := bounds.Min.Y + int(math.Round(float64(bounds.Dy()*crop.Top)/100000)) - cropWidth := int(math.Round(float64(bounds.Dx()*(100000-crop.Left-crop.Right)) / 100000)) - cropHeight := int(math.Round(float64(bounds.Dy()*(100000-crop.Top-crop.Bottom)) / 100000)) - rectangle := image.Rect(left, top, min(bounds.Max.X, left+cropWidth), min(bounds.Max.Y, top+cropHeight)) - raster, err := newPDFImage(source, rectangle) - if err != nil { - return nil, fmt.Errorf("read XLSX picture %s: %w", target, err) - } - x := float64(anchor.From.ColumnOffset) / xlsxEmuPerPoint - y := float64(anchor.From.RowOffset) / xlsxEmuPerPoint - width := float64(anchor.Extension.Width) / xlsxEmuPerPoint - height := float64(anchor.Extension.Height) / xlsxEmuPerPoint - if width <= 0 { - width = grid.columnOffset(anchor.To.Column) - grid.columnOffset(anchor.From.Column) + float64(anchor.To.ColumnOffset)/xlsxEmuPerPoint - x - } - if height <= 0 { - height = grid.rowOffset(anchor.To.Row) - grid.rowOffset(anchor.From.Row) + float64(anchor.To.RowOffset)/xlsxEmuPerPoint - y - } - if width <= 0 || height <= 0 { - return nil, fmt.Errorf("invalid XLSX picture size in %s", name) - } - pictures = append(pictures, xlsxPicture{anchorRow: anchor.From.Row + 1, anchorColumn: anchor.From.Column + 1, - columnOffset: x, rowOffset: y, width: width, height: height, image: raster}) - } - return pictures, nil -} - -func renderXLSXPictures(page *PDFPage, grid xlsxGrid, rows, columns xlsxRange) { - for _, picture := range grid.pictures { - if picture.anchorRow < rows.start || picture.anchorRow > rows.end || picture.anchorColumn < columns.start || picture.anchorColumn > columns.end || - grid.hiddenRows[picture.anchorRow] || grid.hiddenColumns[picture.anchorColumn] { - continue - } - operation := picture.image - operation.x = grid.margins.Left + xlsxRangeSize(xlsxRange{start: columns.start, end: picture.anchorColumn - 1}, grid.columnWidth) + picture.columnOffset*grid.layoutScale() - operation.y = grid.pageSize.Height - grid.margins.Top - xlsxRangeSize(xlsxRange{start: rows.start, end: picture.anchorRow - 1}, grid.rowHeight) - (picture.rowOffset+picture.height)*grid.layoutScale() - operation.width, operation.height = picture.width*grid.layoutScale(), picture.height*grid.layoutScale() - page.operations = append(page.operations, operation) - } -} diff --git a/minipdf-go/xlsx_print.go b/minipdf-go/xlsx_print.go deleted file mode 100644 index b99cfece..00000000 --- a/minipdf-go/xlsx_print.go +++ /dev/null @@ -1,240 +0,0 @@ -package minipdf - -import ( - "fmt" - "math" - "strings" -) - -type xlsxPrintSettings struct { - areas []xlsxMerge - rows, columns xlsxRange - date1904 bool - sheetName string -} - -func parseXLSXPrintRanges(value string) ([]xlsxMerge, error) { - var references []string - start := 0 - quoted := false - for index, character := range value { - switch character { - case '\'': - quoted = !quoted - case ',': - if !quoted { - references = append(references, value[start:index]) - start = index + 1 - } - } - } - if quoted { - return nil, fmt.Errorf("unclosed sheet name in print range %q", value) - } - references = append(references, value[start:]) - var ranges []xlsxMerge - for _, reference := range references { - reference = strings.TrimSpace(reference) - if index := strings.LastIndex(reference, "!"); index >= 0 { - reference = reference[index+1:] - } - reference = strings.ReplaceAll(reference, "$", "") - parts := strings.Split(reference, ":") - if len(parts) == 1 { - parts = append(parts, parts[0]) - } - if len(parts) != 2 { - return nil, fmt.Errorf("unsupported print range %q", reference) - } - startRow, startColumn := xlsxCellPosition(parts[0]) - endRow, endColumn := xlsxCellPosition(parts[1]) - switch { - case startRow == 0 && endRow == 0 && startColumn > 0 && endColumn > 0 && - strings.Trim(parts[0], "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz") == "" && - strings.Trim(parts[1], "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz") == "": - startRow, endRow = 1, 1048576 - case startColumn == 0 && endColumn == 0 && startRow > 0 && endRow > 0: - startColumn, endColumn = 1, 16384 - } - if startRow <= 0 || startColumn <= 0 || endRow < startRow || endColumn < startColumn || - endRow > 1048576 || endColumn > 16384 { - return nil, fmt.Errorf("invalid print range %q", reference) - } - ranges = append(ranges, xlsxMerge{startRow: startRow, endRow: endRow, startColumn: startColumn, endColumn: endColumn}) - } - return ranges, nil -} - -func xlsxRangeSize(span xlsxRange, size func(int) float64) float64 { - total := 0.0 - for index := span.start; index > 0 && index <= span.end; index++ { - total += size(index) - } - return total -} - -func xlsxPrintBands(span xlsxRange, available float64, size func(int) float64, titles xlsxRange, breaks map[int]bool) ([]xlsxRange, error) { - var bands []xlsxRange - titleSize := xlsxRangeSize(titles, size) - for start := span.start; start <= span.end; { - capacity := available - if titles.start > 0 && start > titles.end { - capacity -= titleSize - } - if capacity <= 0 { - return nil, fmt.Errorf("XLSX print titles exceed printable page size") - } - end := start - used := 0.0 - for end <= span.end { - if end > start && (breaks[end-1] || used+size(end) > capacity+1e-6) { - break - } - used += size(end) - end++ - } - bands = append(bands, xlsxRange{start: start, end: end - 1}) - start = end - } - return bands, nil -} - -func limitXLSXPrintArea(grid xlsxGrid, area xlsxMerge, options ConversionOptions) xlsxMerge { - if area.endRow == 1048576 { - area.endRow = grid.maxRow - } - if area.endColumn == 16384 { - area.endColumn = grid.maxColumn - } - if options.MaxRows > 0 { - area.endRow = min(area.endRow, options.MaxRows) - } - if options.MaxColumns > 0 { - area.endColumn = min(area.endColumn, options.MaxColumns) - } - return area -} - -func renderXLSXPrintGrid(document *PDFDocument, grid xlsxGrid, styles []xlsxStyle, settings xlsxPrintSettings, options ConversionOptions) error { - grid.printLayout = true - firstPage := len(document.pages) - availableWidth := grid.pageSize.Width - grid.margins.Left - grid.margins.Right - availableHeight := grid.pageSize.Height - grid.margins.Top - grid.margins.Bottom - if availableWidth <= 0 || availableHeight <= 0 { - return fmt.Errorf("XLSX margins leave no printable page area") - } - for _, area := range settings.areas { - area = limitXLSXPrintArea(grid, area, options) - if area.endRow < area.startRow || area.endColumn < area.startColumn { - continue - } - printGrid := grid - rowBreaks, columnBreaks := grid.rowBreaks, grid.columnBreaks - if grid.fitToPage { - printGrid.printScale = 1 - scale := math.Inf(1) - if grid.fitWidth > 0 { - width := xlsxRangeSize(xlsxRange{start: area.startColumn, end: area.endColumn}, printGrid.columnWidth) - if settings.columns.start > 0 { - repeats := grid.fitWidth - 1 - if area.startColumn > settings.columns.end { - repeats++ - } - width += xlsxRangeSize(settings.columns, printGrid.columnWidth) * float64(repeats) - } - if width > 0 { - scale = min(scale, availableWidth*float64(grid.fitWidth)/width) - } - } - if grid.fitHeight > 0 { - height := xlsxRangeSize(xlsxRange{start: area.startRow, end: area.endRow}, printGrid.rowHeight) - if settings.rows.start > 0 { - repeats := grid.fitHeight - 1 - if area.startRow > settings.rows.end { - repeats++ - } - height += xlsxRangeSize(settings.rows, printGrid.rowHeight) * float64(repeats) - } - if height > 0 { - scale = min(scale, availableHeight*float64(grid.fitHeight)/height) - } - } - if !math.IsInf(scale, 1) { - if scale <= 0 { - return fmt.Errorf("XLSX print titles leave no fit-to-page space") - } - printGrid.printScale = min(1, scale) - } - rowBreaks, columnBreaks = nil, nil - } - columnBands, err := xlsxPrintBands(xlsxRange{start: area.startColumn, end: area.endColumn}, availableWidth, printGrid.columnWidth, settings.columns, columnBreaks) - if err != nil { - return err - } - rowBands, err := xlsxPrintBands(xlsxRange{start: area.startRow, end: area.endRow}, availableHeight, printGrid.rowHeight, settings.rows, rowBreaks) - if err != nil { - return err - } - renderBand := func(rowBand, columnBand xlsxRange) { - page := document.AddPage(grid.pageSize.Width, grid.pageSize.Height) - bandGrid := printGrid - if grid.horizontalCentered { - width := xlsxRangeSize(columnBand, printGrid.columnWidth) - if settings.columns.start > 0 && columnBand.start > settings.columns.end { - width += xlsxRangeSize(settings.columns, printGrid.columnWidth) - } - bandGrid.margins.Left += max(0, (availableWidth-width)/2) - } - if grid.verticalCentered { - height := xlsxRangeSize(rowBand, printGrid.rowHeight) - if settings.rows.start > 0 && rowBand.start > settings.rows.end { - height += xlsxRangeSize(settings.rows, printGrid.rowHeight) - } - bandGrid.margins.Top += max(0, (availableHeight-height)/2) - } - renderXLSXPrintBand(page, bandGrid, styles, rowBand, columnBand, settings) - localPage := len(document.pages) - firstPage - page.decorations = xlsxFooterDecoration(grid, printGrid.layoutScale(), localPage) - } - if grid.overThenDown { - for _, rowBand := range rowBands { - for _, columnBand := range columnBands { - renderBand(rowBand, columnBand) - } - } - } else { - for _, columnBand := range columnBands { - for _, rowBand := range rowBands { - renderBand(rowBand, columnBand) - } - } - } - } - return nil -} - -func renderXLSXPrintBand(page *PDFPage, grid xlsxGrid, styles []xlsxStyle, rows, columns xlsxRange, settings xlsxPrintSettings) { - body := grid - repeatRows := settings.rows.start > 0 && rows.start > settings.rows.end - repeatColumns := settings.columns.start > 0 && columns.start > settings.columns.end - if repeatRows { - body.margins.Top += xlsxRangeSize(settings.rows, grid.rowHeight) - } - if repeatColumns { - body.margins.Left += xlsxRangeSize(settings.columns, grid.columnWidth) - } - if repeatRows { - header := grid - header.margins.Left = body.margins.Left - renderXLSXBand(page, header, styles, settings.rows, columns) - } - if repeatColumns { - header := grid - header.margins.Top = body.margins.Top - renderXLSXBand(page, header, styles, rows, settings.columns) - } - if repeatRows && repeatColumns { - renderXLSXBand(page, grid, styles, settings.rows, settings.columns) - } - renderXLSXBand(page, body, styles, rows, columns) -} diff --git a/minipdf-go/xlsx_print_test.go b/minipdf-go/xlsx_print_test.go deleted file mode 100644 index 18494891..00000000 --- a/minipdf-go/xlsx_print_test.go +++ /dev/null @@ -1,254 +0,0 @@ -package minipdf - -import ( - "bytes" - "strings" - "testing" -) - -func TestParseXLSXPrintRanges(t *testing.T) { - tests := []struct { - reference string - want []xlsxMerge - }{ - {"'O''Brien, report'!$B$2:$D$80,'O''Brien, report'!$F$5", []xlsxMerge{ - {startRow: 2, endRow: 80, startColumn: 2, endColumn: 4}, - {startRow: 5, endRow: 5, startColumn: 6, endColumn: 6}, - }}, - {"Photos!$A:$Y", []xlsxMerge{{startRow: 1, endRow: 1048576, startColumn: 1, endColumn: 25}}}, - {"Photos!$2:$11", []xlsxMerge{{startRow: 2, endRow: 11, startColumn: 1, endColumn: 16384}}}, - } - for _, test := range tests { - t.Run(test.reference, func(t *testing.T) { - got, err := parseXLSXPrintRanges(test.reference) - if err != nil { - t.Fatal(err) - } - if len(got) != len(test.want) { - t.Fatalf("ranges = %#v, want %#v", got, test.want) - } - for index := range got { - if got[index] != test.want[index] { - t.Fatalf("ranges = %#v, want %#v", got, test.want) - } - } - }) - } - for _, reference := range []string{"", "'Unclosed!A1:B2", "Sheet!#REF!", "A0:B2", "B2:A1", "A1:XFE2", "A1:A1048577", "R1C1:R2C2"} { - if _, err := parseXLSXPrintRanges(reference); err == nil { - t.Fatalf("invalid print range %q was accepted", reference) - } - } -} - -func TestConvertXLSXPrintAreaUsesRelationshipsAndPreservesSheetOrder(t *testing.T) { - entries := map[string]string{ - "xl/workbook.xml": `` + - `` + - `Printed!$B$2:$D$3`, - "xl/_rels/workbook.xml.rels": `` + - `` + - `` + - ``, - "xl/worksheets/sheet1.xml": `Before`, - "xl/worksheets/sheet2.xml": `` + - `Outside top` + - `PrintedHelper column` + - `Trailing data` + - ``, - "xl/worksheets/sheet3.xml": `After`, - } - pdf, err := ConvertBytesToPDF(officePackageBytes(t, entries)) - assertPDFContains(t, pdf, err, "Before", "Printed", "After") - for _, value := range []string{"Outside top", "Helper column", "Trailing data"} { - if bytes.Contains(pdf, []byte(value)) { - t.Fatalf("PDF contains out-of-print-area text %q", value) - } - } - if pages := bytes.Count(pdf, []byte("/Type /Page ")); pages != 3 { - t.Fatalf("pages = %d, want 3", pages) - } - if before, printed, after := bytes.Index(pdf, []byte("(Before)")), bytes.Index(pdf, []byte("(Printed)")), bytes.Index(pdf, []byte("(After)")); before >= printed || printed >= after { - t.Fatal("mixed grid and text worksheets changed their order") - } -} - -func TestConvertXLSXPrintAreaRespectsHiddenCellsScaleAndRepeatedTitles(t *testing.T) { - entries := map[string]string{ - "xl/workbook.xml": `` + - `Report!$B$2:$D$80` + - `Report!$2:$2` + - ``, - "xl/worksheets/sheet1.xml": `` + - `` + - `` + - `HeaderHidden column` + - `` + - `First body` + - `Second body` + - `` + - ``, - } - pdf, err := ConvertBytesToPDF(officePackageBytes(t, entries)) - assertPDFContains(t, pdf, err, "Header", "First body", "Second body", "/F1 5.5 Tf") - if pages := bytes.Count(pdf, []byte("/Type /Page ")); pages != 2 { - t.Fatalf("pages = %d, want 2 scaled pages separated by the manual break", pages) - } - if count := bytes.Count(pdf, []byte("(Header)")); count != 2 { - t.Fatalf("repeated header count = %d, want 2", count) - } - for _, text := range []string{"Hidden row", "Hidden column"} { - if bytes.Contains(pdf, []byte(text)) { - t.Fatalf("PDF contains %q", text) - } - } -} - -func TestXLSXPrintBandsReserveTitleSpace(t *testing.T) { - bands, err := xlsxPrintBands(xlsxRange{start: 2, end: 11}, 100, func(int) float64 { return 20 }, xlsxRange{start: 2, end: 3}, map[int]bool{6: true}) - if err != nil { - t.Fatal(err) - } - want := []xlsxRange{{start: 2, end: 6}, {start: 7, end: 9}, {start: 10, end: 11}} - if len(bands) != len(want) { - t.Fatalf("bands = %#v, want %#v", bands, want) - } - for index := range bands { - if bands[index] != want[index] { - t.Fatalf("bands = %#v, want %#v", bands, want) - } - } - if _, err := xlsxPrintBands(xlsxRange{start: 4, end: 10}, 30, func(int) float64 { return 20 }, xlsxRange{start: 1, end: 3}, nil); err == nil { - t.Fatal("oversized repeated titles were accepted") - } -} - -func TestXLSXPrintFitModeOverridesPercentAndManualBreaks(t *testing.T) { - grid, err := readXLSXGrid([]byte(``+ - ``+ - `Header`+ - ``+ - ``), nil) - if err != nil { - t.Fatal(err) - } - document := NewPDFDocument() - err = renderXLSXPrintGrid(document, grid, nil, xlsxPrintSettings{areas: []xlsxMerge{{startRow: 1, endRow: 100, startColumn: 1, endColumn: 4}}}, ConversionOptions{}) - if err != nil { - t.Fatal(err) - } - if len(document.pages) != 1 { - t.Fatalf("fit-to-page pages = %d, want 1", len(document.pages)) - } -} - -func TestConvertXLSXPrintAreaAllowsShapesWithoutDrawingRelationships(t *testing.T) { - entries := map[string]string{ - "xl/workbook.xml": `` + - `Report!A1:B2`, - "xl/worksheets/sheet1.xml": `Report`, - "xl/worksheets/_rels/sheet1.xml.rels": ``, - "xl/drawings/drawing1.xml": ``, - } - pdf, err := ConvertBytesToPDF(officePackageBytes(t, entries)) - assertPDFContains(t, pdf, err, "Report") -} - -func TestConvertXLSXRejectsInvalidPrintSettings(t *testing.T) { - for _, value := range []string{"Report!#REF!", "Report!B2:A1"} { - input := officePackageBytes(t, map[string]string{ - "xl/workbook.xml": `` + - value + ``, - "xl/worksheets/sheet1.xml": ``, - }) - _, err := ConvertBytesToPDF(input) - assertPackageErrorContains(t, err, "Print_Area") - } - for _, setting := range []string{`scale="-1"`, `fitToWidth="-1"`} { - _, err := readXLSXGrid([]byte(``), nil) - if err == nil || !strings.Contains(err.Error(), "invalid XLSX") { - t.Fatalf("setting %s: error = %v", setting, err) - } - } -} - -func TestXLSXPrintAreaRepeatsRowsAndColumns(t *testing.T) { - grid, err := readXLSXGrid([]byte(``+ - `Corner`+ - `Row title`+ - `Column title`+ - ``), nil) - if err != nil { - t.Fatal(err) - } - grid.pageSize = PageSize{Width: 400, Height: 400} - grid.margins = Margins{Left: 10, Right: 10, Top: 10, Bottom: 10} - for index := 1; index <= 6; index++ { - grid.columnWidths[index] = 100 - grid.rowHeights[index] = 100 - } - document := NewPDFDocument() - err = renderXLSXPrintGrid(document, grid, nil, xlsxPrintSettings{ - areas: []xlsxMerge{{startRow: 1, endRow: 6, startColumn: 1, endColumn: 6}}, - rows: xlsxRange{start: 1, end: 1}, - columns: xlsxRange{start: 1, end: 1}, - }, ConversionOptions{}) - if err != nil { - t.Fatal(err) - } - pdf := document.Bytes() - if len(document.pages) != 9 { - t.Fatalf("pages = %d, want 9 with repeated rows and columns", len(document.pages)) - } - for text, want := range map[string]int{"Corner": 9, "Row title": 3, "Column title": 3} { - if count := bytes.Count(pdf, []byte("("+text+")")); count != want { - t.Fatalf("%s count = %d, want %d", text, count, want) - } - } -} - -func TestXLSXPrintAreaSupportsMultipleRangesAndOptionLimits(t *testing.T) { - input := officePackageBytes(t, map[string]string{ - "xl/workbook.xml": `` + - `Report!A1:B2,Report!D10:E11`, - "xl/worksheets/sheet1.xml": `` + - `First range` + - `Second range`, - }) - for _, maxRows := range []int{0, 5} { - pdf, err := ConvertBytesToPDFWithOptions(input, ConversionOptions{MaxRows: maxRows}) - assertPDFContains(t, pdf, err, "First range") - wantPages := 2 - if maxRows > 0 { - wantPages = 1 - if bytes.Contains(pdf, []byte("Second range")) { - t.Fatal("MaxRows did not constrain the print area") - } - } else { - assertPDFContains(t, pdf, nil, "Second range") - } - if pages := bytes.Count(pdf, []byte("/Type /Page ")); pages != wantPages { - t.Fatalf("MaxRows=%d: pages = %d, want %d", maxRows, pages, wantPages) - } - } -} - -func TestXLSXPrintAreaPaintsTextAfterAdjacentFills(t *testing.T) { - grid, err := readXLSXGrid([]byte(``+ - `Long report title`+ - ``), nil) - if err != nil { - t.Fatal(err) - } - fill := PDFColor{Red: 1} - styles := []xlsxStyle{{font: xlsxFont{size: 11}, fill: &fill}} - document := NewPDFDocument() - err = renderXLSXPrintGrid(document, grid, styles, xlsxPrintSettings{areas: []xlsxMerge{{startRow: 1, endRow: 1, startColumn: 1, endColumn: 2}}}, ConversionOptions{}) - if err != nil { - t.Fatal(err) - } - operations := document.pages[0].operations - if _, ok := operations[len(operations)-1].(textOperation); !ok { - t.Fatal("adjacent cell fill can paint over the overflowing report title") - } -} diff --git a/minipdf-go/xlsx_render.go b/minipdf-go/xlsx_render.go deleted file mode 100644 index 548e8a2a..00000000 --- a/minipdf-go/xlsx_render.go +++ /dev/null @@ -1,1048 +0,0 @@ -package minipdf - -import ( - "bytes" - "encoding/xml" - "fmt" - "strconv" - "strings" -) - -const ( - xlsxColumnWidthPoints = 5.62 - xlsxDefaultRowHeightScale = 14.6 / 15 - calibriToHelveticaFontScale = 0.73 - calibriRegularWidthScale = 90 / calibriToHelveticaFontScale - calibriBoldWidthScale = 80 / calibriToHelveticaFontScale - helveticaBaselineRatio = 0.45 -) - -type xlsxStyle struct { - font xlsxFont - fill *PDFColor - border xlsxBorder - numberFmt int - numberCode string - align string - vertical string - shrink bool - padding float64 -} - -type xlsxFont struct { - name string - size float64 - color PDFColor - bold bool - italic bool - embedded *embeddedFont -} - -type xlsxBorder struct { - left, right, top, bottom float64 - leftDouble, rightDouble, topDouble, bottomDouble bool -} - -type xlsxCell struct { - row, column int - value string - formula string - style int - numeric bool - formatted string -} - -type xlsxMerge struct { - startRow, startColumn int - endRow, endColumn int -} - -type xlsxGrid struct { - cells map[[2]int]xlsxCell - columnWidths map[int]float64 - rowHeights map[int]float64 - merges []xlsxMerge - charts []xlsxChart - pictures []xlsxPicture - horizontalCentered, verticalCentered bool - footerMargin float64 - headerFooter xlsxHeaderFooter - conditionalFills []xlsxConditionalFormat - maxRow, maxColumn int - dimensionRow int - dimensionColumn int - defaultRowHeight float64 - pageSize PageSize - margins Margins - hiddenRows map[int]bool - hiddenColumns map[int]bool - rowBreaks map[int]bool - columnBreaks map[int]bool - printLayout bool - printScale float64 - fitToPage bool - fitWidth int - fitHeight int - overThenDown bool -} - -type xlsxStylesDocument struct { - Fonts struct { - Items []struct { - Bold *struct{} `xml:"b"` - Italic *struct{} `xml:"i"` - Name struct { - Value string `xml:"val,attr"` - } `xml:"name"` - Size struct { - Value float64 `xml:"val,attr"` - } `xml:"sz"` - Color xlsxColorXML `xml:"color"` - } `xml:"font"` - } `xml:"fonts"` - NumberFormats struct { - Items []struct { - ID int `xml:"numFmtId,attr"` - Code string `xml:"formatCode,attr"` - } `xml:"numFmt"` - } `xml:"numFmts"` - Fills struct { - Items []xlsxFillXML `xml:"fill"` - } `xml:"fills"` - Borders struct { - Items []struct { - Left struct { - Style string `xml:"style,attr"` - } `xml:"left"` - Right struct { - Style string `xml:"style,attr"` - } `xml:"right"` - Top struct { - Style string `xml:"style,attr"` - } `xml:"top"` - Bottom struct { - Style string `xml:"style,attr"` - } `xml:"bottom"` - } `xml:"border"` - } `xml:"borders"` - CellFormats struct { - Items []struct { - FontID int `xml:"fontId,attr"` - FillID int `xml:"fillId,attr"` - BorderID int `xml:"borderId,attr"` - NumberFmt int `xml:"numFmtId,attr"` - Alignment struct { - Horizontal string `xml:"horizontal,attr"` - Vertical string `xml:"vertical,attr"` - Shrink bool `xml:"shrinkToFit,attr"` - } `xml:"alignment"` - } `xml:"xf"` - } `xml:"cellXfs"` - DifferentialFormats struct { - Items []struct { - Fill *xlsxFillXML `xml:"fill"` - } `xml:"dxf"` - } `xml:"dxfs"` -} - -func needsCalculatedXLSXGrid(data []byte) bool { - var worksheet struct { - Cells []struct { - Formula *string `xml:"f"` - Value *string `xml:"v"` - } `xml:"sheetData>row>c"` - } - if xml.Unmarshal(data, &worksheet) != nil { - return false - } - formulaCount := 0 - for _, cell := range worksheet.Cells { - if cell.Formula == nil { - continue - } - formulaCount++ - if cell.Value != nil && strings.TrimSpace(*cell.Value) != "" { - return false - } - } - return formulaCount > 0 -} - -func readXLSXStyles(files officePackage) ([]xlsxStyle, []*PDFColor, error) { - if _, ok := files["xl/styles.xml"]; !ok { - return nil, nil, nil - } - data, err := files.read("xl/styles.xml") - if err != nil { - return nil, nil, err - } - var document xlsxStylesDocument - if err := xml.Unmarshal(data, &document); err != nil { - return nil, nil, fmt.Errorf("parse xl/styles.xml: %w", err) - } - theme, err := readXLSXTheme(files) - if err != nil { - return nil, nil, err - } - styles := make([]xlsxStyle, len(document.CellFormats.Items)) - fonts := make(map[int]*embeddedFont) - type fontKey struct { - name string - bold, italic bool - } - variants := make(map[fontKey]*embeddedFont) - for index, font := range document.Fonts.Items { - key := fontKey{strings.ToLower(font.Name.Value), font.Bold != nil, font.Italic != nil} - embedded, exists := variants[key] - if !exists { - embedded, err = readXLSXFont(font.Name.Value, key.bold, key.italic) - if err != nil { - return nil, nil, err - } - variants[key] = embedded - } - fonts[index] = embedded - } - for index, format := range document.CellFormats.Items { - style := xlsxStyle{ - font: xlsxFont{size: 11, color: PDFColorBlack}, numberFmt: format.NumberFmt, - align: format.Alignment.Horizontal, vertical: format.Alignment.Vertical, shrink: format.Alignment.Shrink, - } - if format.FontID >= 0 && format.FontID < len(document.Fonts.Items) { - font := document.Fonts.Items[format.FontID] - style.font.name = font.Name.Value - if font.Size.Value > 0 { - style.font.size = font.Size.Value - } - style.font.bold = font.Bold != nil - style.font.italic = font.Italic != nil - style.font.embedded = fonts[format.FontID] - color, err := resolveXLSXColor(font.Color, theme) - if err != nil { - return nil, nil, fmt.Errorf("parse xl/styles.xml font %d: %w", format.FontID, err) - } - if color != nil { - style.font.color = *color - } - } - if format.FillID >= 0 && format.FillID < len(document.Fills.Items) { - fill := document.Fills.Items[format.FillID].Pattern - if fill.Type == "solid" { - color, err := resolveXLSXColor(fill.Foreground, theme) - if err != nil { - return nil, nil, fmt.Errorf("parse xl/styles.xml fill %d: %w", format.FillID, err) - } - style.fill = color - } - } - if format.BorderID >= 0 && format.BorderID < len(document.Borders.Items) { - border := document.Borders.Items[format.BorderID] - style.border = xlsxBorder{ - left: borderWidth(border.Left.Style), right: borderWidth(border.Right.Style), - top: borderWidth(border.Top.Style), bottom: borderWidth(border.Bottom.Style), - leftDouble: border.Left.Style == "double", rightDouble: border.Right.Style == "double", - topDouble: border.Top.Style == "double", bottomDouble: border.Bottom.Style == "double", - } - } - styles[index] = style - for _, number := range document.NumberFormats.Items { - if number.ID == format.NumberFmt { - styles[index].numberCode = number.Code - break - } - } - } - differentialFills := make([]*PDFColor, len(document.DifferentialFormats.Items)) - for index, format := range document.DifferentialFormats.Items { - if format.Fill == nil { - continue - } - pattern := format.Fill.Pattern - if pattern.Type != "" && pattern.Type != "solid" { - continue - } - color := pattern.Background - if color.RGB == "" && color.Theme == nil { - color = pattern.Foreground - } - differentialFills[index], err = resolveXLSXColor(color, theme) - if err != nil { - return nil, nil, fmt.Errorf("parse xl/styles.xml differential fill %d: %w", index, err) - } - } - return styles, differentialFills, nil -} - -func parseXLSXColor(value string) (PDFColor, bool) { - if len(value) < 6 { - return PDFColor{}, false - } - parsed, err := strconv.ParseUint(value[len(value)-6:], 16, 32) - if err != nil { - return PDFColor{}, false - } - return PDFColor{Red: float64(parsed>>16) / 255, Green: float64(parsed>>8&0xff) / 255, Blue: float64(parsed&0xff) / 255}, true -} - -func borderWidth(style string) float64 { - switch style { - case "hair": - return 0.25 - case "medium", "mediumDashed", "mediumDashDot", "mediumDashDotDot": - return 1.5 - case "thick", "double": - return 2 - case "thin", "dashed", "dotted", "dashDot", "dashDotDot": - return 0.75 - default: - return 0 - } -} - -func renderXLSXWorksheets(files officePackage, worksheetNames []string, sharedStrings []string, styles []xlsxStyle, differentialFills []*PDFColor, options ConversionOptions, printSettings map[string]xlsxPrintSettings) ([]byte, error) { - document := NewPDFDocument() - for _, name := range worksheetNames { - if err := renderXLSXWorksheet(document, files, name, sharedStrings, styles, differentialFills, options, printSettings[strings.ToLower(name)]); err != nil { - return nil, err - } - } - return document.BytesWithOptions(PDFSaveOptions{Compress: options.Compress}), nil -} - -func renderXLSXWorksheet(document *PDFDocument, files officePackage, name string, sharedStrings []string, styles []xlsxStyle, differentialFills []*PDFColor, options ConversionOptions, settings xlsxPrintSettings) error { - data, err := files.read(name) - if err != nil { - return err - } - grid, err := readXLSXGrid(data, sharedStrings) - if err != nil { - return fmt.Errorf("parse %s: %w", name, err) - } - grid.charts, err = readXLSXCharts(files, name, &grid) - if err != nil { - return err - } - grid.applyOptions(options) - if len(settings.areas) > 0 { - grid.pictures, err = readXLSXPictures(files, name, grid) - if err != nil { - return err - } - for key, cell := range grid.cells { - if cell.value != "" && cell.numeric { - style := styleAt(styles, cell.style) - cell.formatted, err = formatPrintedXLSXValue(cell.value, style.numberFmt, style.numberCode, settings.date1904) - if err != nil { - return fmt.Errorf("format %s cell %d/%d: %w", name, cell.row, cell.column, err) - } - grid.cells[key] = cell - } - } - if err := grid.prepareFooters(styles, settings.sheetName); err != nil { - return fmt.Errorf("parse %s footer: %w", name, err) - } - var scopes []xlsxMerge - for _, area := range settings.areas { - area = limitXLSXPrintArea(grid, area, options) - if area.endRow < area.startRow || area.endColumn < area.startColumn { - continue - } - scopes = append(scopes, area) - if settings.rows.start > 0 { - scopes = append(scopes, xlsxMerge{startRow: settings.rows.start, endRow: settings.rows.end, startColumn: area.startColumn, endColumn: area.endColumn}) - } - if settings.columns.start > 0 { - scopes = append(scopes, xlsxMerge{startRow: area.startRow, endRow: area.endRow, startColumn: settings.columns.start, endColumn: settings.columns.end}) - } - if settings.rows.start > 0 && settings.columns.start > 0 { - scopes = append(scopes, xlsxMerge{startRow: settings.rows.start, endRow: settings.rows.end, startColumn: settings.columns.start, endColumn: settings.columns.end}) - } - } - styles, err = grid.applyConditionalFills(styles, differentialFills, scopes) - if err != nil { - return fmt.Errorf("render %s conditional fills: %w", name, err) - } - if err := renderXLSXPrintGrid(document, grid, styles, settings, options); err != nil { - return fmt.Errorf("render %s print area: %w", name, err) - } - } else { - renderXLSXGrid(document, grid, styles) - } - return nil -} - -func readXLSXGrid(data []byte, sharedStrings []string) (xlsxGrid, error) { - grid := xlsxGrid{ - cells: make(map[[2]int]xlsxCell), columnWidths: make(map[int]float64), rowHeights: make(map[int]float64), - defaultRowHeight: 15, pageSize: PageSizeA4, margins: Margins{Left: 54, Right: 54, Top: 72, Bottom: 72}, - hiddenRows: make(map[int]bool), hiddenColumns: make(map[int]bool), - rowBreaks: make(map[int]bool), columnBreaks: make(map[int]bool), - printScale: 1, fitWidth: 1, fitHeight: 1, - footerMargin: 36, - } - breakKind := "" - decoder := xml.NewDecoder(bytes.NewReader(data)) - for { - token, err := decoder.Token() - if err != nil { - if err.Error() == "EOF" { - break - } - return xlsxGrid{}, err - } - start, ok := token.(xml.StartElement) - if !ok { - if end, ok := token.(xml.EndElement); ok && (end.Name.Local == "rowBreaks" || end.Name.Local == "colBreaks") { - breakKind = "" - } - continue - } - switch start.Name.Local { - case "printOptions": - grid.horizontalCentered = attrValue(start, "horizontalCentered") == "1" || attrValue(start, "horizontalCentered") == "true" - grid.verticalCentered = attrValue(start, "verticalCentered") == "1" || attrValue(start, "verticalCentered") == "true" - case "headerFooter": - if err := decoder.DecodeElement(&grid.headerFooter, &start); err != nil { - return xlsxGrid{}, err - } - case "conditionalFormatting": - var format xlsxConditionalFormat - if err := decoder.DecodeElement(&format, &start); err != nil { - return xlsxGrid{}, err - } - for _, reference := range strings.Fields(format.References) { - reference = strings.ReplaceAll(reference, "$", "") - if !strings.Contains(reference, ":") { - reference += ":" + reference - } - area, ok := parseXLSXMerge(reference) - endpoints := strings.Split(reference, ":") - if !ok || len(endpoints) != 2 || !xlsxConditionalReference.MatchString(endpoints[0]) || - !xlsxConditionalReference.MatchString(endpoints[1]) || area.endRow > 1048576 || area.endColumn > 16384 { - return xlsxGrid{}, fmt.Errorf("invalid XLSX conditional formatting range %q", reference) - } - format.areas = append(format.areas, area) - } - if len(format.areas) == 0 { - return xlsxGrid{}, fmt.Errorf("missing XLSX conditional formatting range") - } - grid.conditionalFills = append(grid.conditionalFills, format) - case "dimension": - reference := attrValue(start, "ref") - parts := strings.Split(reference, ":") - grid.dimensionRow, grid.dimensionColumn = xlsxCellPosition(parts[len(parts)-1]) - case "sheetFormatPr": - if height, err := strconv.ParseFloat(attrValue(start, "defaultRowHeight"), 64); err == nil && height > 0 { - grid.defaultRowHeight = height - } - case "col": - minimum, _ := strconv.Atoi(attrValue(start, "min")) - maximum, _ := strconv.Atoi(attrValue(start, "max")) - width, _ := strconv.ParseFloat(attrValue(start, "width"), 64) - maximum = min(maximum, 16384) - for column := minimum; column <= maximum && column > 0; column++ { - grid.columnWidths[column] = width * xlsxColumnWidthPoints - grid.hiddenColumns[column] = attrValue(start, "hidden") == "1" || attrValue(start, "hidden") == "true" - } - case "row": - row, _ := strconv.Atoi(attrValue(start, "r")) - if height, err := strconv.ParseFloat(attrValue(start, "ht"), 64); err == nil && height > 0 { - grid.rowHeights[row] = height - } - grid.maxRow = max(grid.maxRow, row) - grid.hiddenRows[row] = attrValue(start, "hidden") == "1" || attrValue(start, "hidden") == "true" - case "c": - reference := attrValue(start, "r") - row, column := xlsxCellPosition(reference) - value, formula, err := decodeWorksheetCellContent(decoder, start, sharedStrings) - if err != nil { - return xlsxGrid{}, err - } - style, _ := strconv.Atoi(attrValue(start, "s")) - cellType := attrValue(start, "t") - grid.cells[[2]int{row, column}] = xlsxCell{row: row, column: column, value: value, formula: formula, style: style, numeric: cellType == "" || cellType == "n"} - grid.maxRow = max(grid.maxRow, row) - grid.maxColumn = max(grid.maxColumn, column) - case "mergeCell": - if merge, ok := parseXLSXMerge(attrValue(start, "ref")); ok { - grid.merges = append(grid.merges, merge) - } - case "pageMargins": - grid.footerMargin = inchesToPoints(attrValue(start, "footer"), 36) - grid.margins = Margins{ - Left: inchesToPoints(attrValue(start, "left"), 54), Right: inchesToPoints(attrValue(start, "right"), 54), - Top: inchesToPoints(attrValue(start, "top"), 72), Bottom: inchesToPoints(attrValue(start, "bottom"), 72), - } - case "pageSetup": - grid.overThenDown = attrValue(start, "pageOrder") == "overThenDown" - if value := attrValue(start, "scale"); value != "" { - scale, err := strconv.Atoi(value) - if err != nil || (scale != 0 && scale < 10) || scale > 400 { - return xlsxGrid{}, fmt.Errorf("invalid XLSX print scale %q", value) - } - if scale > 0 { - grid.printScale = float64(scale) / 100 - } - } - for _, setting := range []struct { - name string - target *int - }{{"fitToWidth", &grid.fitWidth}, {"fitToHeight", &grid.fitHeight}} { - if value := attrValue(start, setting.name); value != "" { - count, err := strconv.Atoi(value) - if err != nil || count < 0 { - return xlsxGrid{}, fmt.Errorf("invalid XLSX %s %q", setting.name, value) - } - *setting.target = count - } - } - if attrValue(start, "paperSize") == "1" { - grid.pageSize = PageSizeLetter - } - if attrValue(start, "orientation") == "landscape" { - grid.pageSize.Width, grid.pageSize.Height = grid.pageSize.Height, grid.pageSize.Width - } - case "pageSetUpPr": - grid.fitToPage = attrValue(start, "fitToPage") == "1" || attrValue(start, "fitToPage") == "true" - case "rowBreaks", "colBreaks": - breakKind = start.Name.Local - case "brk": - if attrValue(start, "man") == "1" || attrValue(start, "man") == "true" { - index, err := strconv.Atoi(attrValue(start, "id")) - if err != nil || index < 0 { - return xlsxGrid{}, fmt.Errorf("invalid XLSX manual page break") - } - if breakKind == "rowBreaks" { - grid.rowBreaks[index] = true - } else if breakKind == "colBreaks" { - grid.columnBreaks[index] = true - } - } - } - } - if grid.dimensionRow > 0 && grid.dimensionColumn > 0 { - grid.maxRow = grid.dimensionRow - grid.maxColumn = grid.dimensionColumn - } - grid.evaluateFormulas() - return grid, nil -} - -func (grid *xlsxGrid) evaluateFormulas() { - visiting := make(map[[2]int]bool) - for key, cell := range grid.cells { - if cell.value == "" && cell.formula != "" { - if value, ok := grid.evaluateCell(key, visiting); ok { - cell.value = strconv.FormatFloat(value, 'f', -1, 64) - grid.cells[key] = cell - } - } - } -} - -func (grid *xlsxGrid) evaluateCell(key [2]int, visiting map[[2]int]bool) (float64, bool) { - cell, exists := grid.cells[key] - if !exists { - return 0, true - } - if cell.value != "" { - value, err := strconv.ParseFloat(strings.TrimSpace(cell.value), 64) - return value, err == nil - } - if cell.formula == "" || visiting[key] { - return 0, false - } - visiting[key] = true - defer delete(visiting, key) - formula := strings.TrimSpace(strings.TrimPrefix(cell.formula, "=")) - if strings.HasPrefix(strings.ToUpper(formula), "SUM(") && strings.HasSuffix(formula, ")") { - merge, ok := parseXLSXMerge(formula[4 : len(formula)-1]) - if !ok { - return 0, false - } - total := 0.0 - for row := merge.startRow; row <= merge.endRow; row++ { - for column := merge.startColumn; column <= merge.endColumn; column++ { - value, ok := grid.evaluateCell([2]int{row, column}, visiting) - if !ok { - return 0, false - } - total += value - } - } - return total, true - } - total := 0.0 - for _, reference := range strings.Split(formula, "+") { - row, column := xlsxCellPosition(strings.TrimSpace(reference)) - if row == 0 || column == 0 { - return 0, false - } - value, ok := grid.evaluateCell([2]int{row, column}, visiting) - if !ok { - return 0, false - } - total += value - } - return total, true -} - -func xlsxCellPosition(reference string) (int, int) { - column := worksheetColumnIndex(reference) - index := 0 - for index < len(reference) && ((reference[index] >= 'A' && reference[index] <= 'Z') || (reference[index] >= 'a' && reference[index] <= 'z')) { - index++ - } - row, _ := strconv.Atoi(reference[index:]) - return row, column -} - -func parseXLSXMerge(reference string) (xlsxMerge, bool) { - parts := strings.Split(reference, ":") - if len(parts) != 2 { - return xlsxMerge{}, false - } - startRow, startColumn := xlsxCellPosition(parts[0]) - endRow, endColumn := xlsxCellPosition(parts[1]) - return xlsxMerge{startRow: startRow, startColumn: startColumn, endRow: endRow, endColumn: endColumn}, startRow > 0 && startColumn > 0 && endRow >= startRow && endColumn >= startColumn -} - -func inchesToPoints(value string, fallback float64) float64 { - inches, err := strconv.ParseFloat(value, 64) - if err != nil || inches < 0 { - return fallback - } - return inches * 72 -} - -func (grid *xlsxGrid) applyOptions(options ConversionOptions) { - if options.MaxRows > 0 { - grid.maxRow = min(grid.maxRow, options.MaxRows) - } - if options.MaxColumns > 0 { - grid.maxColumn = min(grid.maxColumn, options.MaxColumns) - } - if options.PageSize != nil { - grid.pageSize = *options.PageSize - } - if options.Margins != nil { - grid.margins = *options.Margins - } - if options.Landscape != nil && (*options.Landscape != (grid.pageSize.Width > grid.pageSize.Height)) { - grid.pageSize.Width, grid.pageSize.Height = grid.pageSize.Height, grid.pageSize.Width - } -} - -type xlsxRange struct{ start, end int } - -func renderXLSXGrid(document *PDFDocument, grid xlsxGrid, styles []xlsxStyle) { - if grid.maxRow == 0 || grid.maxColumn == 0 { - document.AddPage(grid.pageSize.Width, grid.pageSize.Height) - return - } - columnBands := xlsxBands(grid.maxColumn, grid.pageSize.Width-grid.margins.Left-grid.margins.Right, func(index int) float64 { return grid.columnWidth(index) }) - rowBands := xlsxBands(grid.maxRow, grid.pageSize.Height-grid.margins.Top-grid.margins.Bottom, func(index int) float64 { return grid.rowHeight(index) }) - for _, columnBand := range columnBands { - for _, rowBand := range rowBands { - page := document.AddPage(grid.pageSize.Width, grid.pageSize.Height) - renderXLSXBand(page, grid, styles, rowBand, columnBand) - } - } -} - -func xlsxBands(count int, available float64, size func(int) float64) []xlsxRange { - var bands []xlsxRange - for start := 1; start <= count; { - end := start - used := 0.0 - for end <= count && (used+size(end) <= available || end == start) { - used += size(end) - end++ - } - bands = append(bands, xlsxRange{start: start, end: end - 1}) - start = end - } - return bands -} - -func (grid xlsxGrid) columnWidth(column int) float64 { - if grid.printLayout && grid.hiddenColumns[column] { - return 0 - } - scale := grid.layoutScale() - if width := grid.columnWidths[column]; width > 0 && (grid.printLayout || grid.dimensionColumn == 0 || column <= grid.dimensionColumn) { - return width * scale - } - return 8.43 * xlsxColumnWidthPoints * scale -} - -func (grid xlsxGrid) rowHeight(row int) float64 { - if grid.printLayout && grid.hiddenRows[row] { - return 0 - } - scale := grid.layoutScale() - if height := grid.rowHeights[row]; height > 0 { - return height * scale - } - return grid.defaultRowHeight * xlsxDefaultRowHeightScale * scale -} - -func (grid xlsxGrid) layoutScale() float64 { - if grid.printLayout { - return grid.printScale - } - return 1 -} - -func renderXLSXBand(page *PDFPage, grid xlsxGrid, styles []xlsxStyle, rows, columns xlsxRange) { - type cellText struct { - cell xlsxCell - x, y, width, height float64 - style xlsxStyle - } - var textCells []cellText - paintCell := func(cell xlsxCell, x, y, width, height float64, style xlsxStyle, drawText bool) { - if grid.printLayout { - renderXLSXCell(page, cell, x, y, width, height, style, false) - if drawText && width > 0 && height > 0 { - textCells = append(textCells, cellText{cell: cell, x: x, y: y, width: width, height: height, style: style}) - } - } else { - renderXLSXCell(page, cell, x, y, width, height, style, drawText) - } - } - xPositions := map[int]float64{columns.start: grid.margins.Left} - for column := columns.start; column <= columns.end; column++ { - xPositions[column+1] = xPositions[column] + grid.columnWidth(column) - } - yPositions := map[int]float64{rows.start: grid.pageSize.Height - grid.margins.Top} - for row := rows.start; row <= rows.end; row++ { - yPositions[row+1] = yPositions[row] - grid.rowHeight(row) - } - merged := make(map[[2]int]bool) - for _, merge := range grid.merges { - for row := merge.startRow; row <= merge.endRow; row++ { - for column := merge.startColumn; column <= merge.endColumn; column++ { - merged[[2]int{row, column}] = true - } - } - if merge.endRow < rows.start || merge.startRow > rows.end || merge.endColumn < columns.start || merge.startColumn > columns.end { - continue - } - cell := grid.cells[[2]int{merge.startRow, merge.startColumn}] - startColumn := max(merge.startColumn, columns.start) - endColumn := min(merge.endColumn, columns.end) - startRow := max(merge.startRow, rows.start) - endRow := min(merge.endRow, rows.end) - paintCell(cell, xPositions[startColumn], yPositions[endRow+1], xPositions[endColumn+1]-xPositions[startColumn], yPositions[startRow]-yPositions[endRow+1], grid.scaledStyle(styles, cell.style), merge.startColumn >= columns.start && merge.startColumn <= columns.end) - } - for row := rows.start; row <= rows.end; row++ { - for column := columns.start; column <= columns.end; column++ { - if grid.rowHeight(row) == 0 || grid.columnWidth(column) == 0 { - continue - } - if merged[[2]int{row, column}] { - continue - } - cell, exists := grid.cells[[2]int{row, column}] - if !exists { - continue - } - paintCell(cell, xPositions[column], yPositions[row+1], grid.columnWidth(column), grid.rowHeight(row), grid.scaledStyle(styles, cell.style), true) - } - } - for _, text := range textCells { - renderXLSXCellText(page, text.cell, text.x, text.y, text.width, text.height, text.style) - } - renderXLSXCharts(page, grid, rows, columns) - if grid.printLayout { - renderXLSXPictures(page, grid, rows, columns) - } -} - -func (grid xlsxGrid) scaledStyle(styles []xlsxStyle, index int) xlsxStyle { - style := styleAt(styles, index) - if !grid.printLayout { - style.font.embedded = nil - style.font.italic = false - style.shrink = false - } else { - style.padding = 1.5 * grid.layoutScale() - } - scale := grid.layoutScale() - style.font.size *= scale - style.border.left *= scale - style.border.right *= scale - style.border.top *= scale - style.border.bottom *= scale - return style -} - -func styleAt(styles []xlsxStyle, index int) xlsxStyle { - if index >= 0 && index < len(styles) { - return styles[index] - } - return xlsxStyle{font: xlsxFont{size: 11, color: PDFColorBlack}} -} - -func renderXLSXCell(page *PDFPage, cell xlsxCell, x, y, width, height float64, style xlsxStyle, drawText bool) { - if width <= 0 || height <= 0 { - return - } - if style.fill != nil { - page.AddRect(x, y, width, height, *style.fill) - } - if style.border.left > 0 { - drawXLSXBorder(page, x, y, x, y+height, style.border.left, style.border.leftDouble) - } - if style.border.right > 0 { - drawXLSXBorder(page, x+width, y, x+width, y+height, style.border.right, style.border.rightDouble) - } - if style.border.top > 0 { - drawXLSXBorder(page, x, y+height, x+width, y+height, style.border.top, style.border.topDouble) - } - if style.border.bottom > 0 { - drawXLSXBorder(page, x, y, x+width, y, style.border.bottom, style.border.bottomDouble) - } - if !drawText || cell.value == "" { - return - } - renderXLSXCellText(page, cell, x, y, width, height, style) -} - -func drawXLSXBorder(page *PDFPage, x1, y1, x2, y2, width float64, double bool) { - if !double { - page.AddLine(x1, y1, x2, y2, PDFColorBlack, width) - return - } - offset := width / 3 - if x1 == x2 { - page.AddLine(x1-offset, y1, x2-offset, y2, PDFColorBlack, offset) - page.AddLine(x1+offset, y1, x2+offset, y2, PDFColorBlack, offset) - } else { - page.AddLine(x1, y1-offset, x2, y2-offset, PDFColorBlack, offset) - page.AddLine(x1, y1+offset, x2, y2+offset, PDFColorBlack, offset) - } -} - -func renderXLSXCellText(page *PDFPage, cell xlsxCell, x, y, width, height float64, style xlsxStyle) { - if cell.value == "" { - return - } - text := formatXLSXValue(cell.value, cell.numeric, style.numberFmt) - if cell.formatted != "" { - text = cell.formatted - } - fontSize := style.font.size - horizontalScale := 100.0 - embedded := style.font.embedded - if embedded != nil && !embedded.canEncode(text) { - embedded = nil - } - if embedded == nil && strings.EqualFold(style.font.name, "Calibri") { - fontSize *= calibriToHelveticaFontScale - horizontalScale = calibriRegularWidthScale - if style.font.bold { - horizontalScale = calibriBoldWidthScale - } - } - textWidth := measureHelveticaText(text, fontSize, horizontalScale, style.font.bold) - if embedded != nil { - textWidth = measureXLSXFont(text, fontSize, embedded) - } - padding := style.padding - if padding == 0 { - padding = 2 - } - if style.shrink && textWidth > width-2*padding && width > 2*padding { - ratio := (width - 2*padding) / textWidth - fontSize *= ratio - textWidth *= ratio - } - textX := x + padding - switch style.align { - case "center": - textX = x + (width-textWidth)/2 - case "right": - textX = x + width - textWidth - padding - case "left": - textX = x + padding - default: - if cell.numeric { - textX = x + width - textWidth - padding - } - } - textY := y + fontSize*helveticaBaselineRatio - if embedded != nil { - textY = y + fontSize*embedded.descent - } - if style.vertical == "center" { - textY = y + (height-fontSize)/2 - } else if style.vertical == "top" { - textY = y + height - fontSize - if embedded != nil { - textY = y + height - fontSize*embedded.ascent - } - } - page.operations = append(page.operations, textOperation{text: text, x: textX, y: textY, fontSize: fontSize, - horizontalScale: horizontalScale, color: style.font.color, bold: style.font.bold, italic: style.font.italic, embedded: embedded}) -} - -func measureHelveticaText(text string, fontSize, horizontalScale float64, bold bool) float64 { - total := 0 - for _, character := range text { - total += helveticaCharacterWidth(character, bold) - } - return float64(total) * fontSize / 1000 * horizontalScale / 100 -} - -func helveticaCharacterWidth(character rune, bold bool) int { - if bold { - switch character { - case ' ', ',': - return 278 - case '!', ':', ';', '(', ')', '-', '.', '/': - return 333 - case '"': - return 474 - case '#', '$', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9': - return 556 - case '%': - return 889 - case '&', 'A', 'B', 'C', 'D', 'G', 'H', 'K', 'N', 'O', 'P', 'Q', 'R', 'U', 'V', 'X', 'Y': - return 722 - case '\'', 'I': - return 238 - case '*': - return 389 - case '+', '<', '=', '>', '^', '~': - return 584 - case '?', 'E', 'S': - return 611 - case '@': - return 975 - case 'F', 'L', 'T', 'Z': - return 611 - case 'J': - return 556 - case 'M': - return 833 - case 'W': - return 944 - case '[', ']': - return 333 - case '\\': - return 278 - case '_': - return 556 - case '`': - return 333 - case 'a', 'c', 'e', 's', 'x', 'v': - return 556 - case 'b', 'd', 'g', 'h', 'n', 'o', 'p', 'q', 'u': - return 611 - case 'f', 't': - return 333 - case 'i', 'j', 'l': - return 278 - case 'k': - return 556 - case 'm': - return 889 - case 'r': - return 389 - case 'w': - return 778 - case 'y': - return 556 - case 'z': - return 500 - case '{', '}': - return 389 - case '|': - return 280 - } - } else { - switch character { - case ' ', '!', ',', '.', '/', ':', ';', 'I', '[', '\\', ']': - return 278 - case '"': - return 355 - case '#', '$', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '?', 'L', '_': - return 556 - case '%': - return 889 - case '&', 'A', 'B', 'E', 'K', 'P', 'S', 'V', 'X', 'Y': - return 667 - case '\'': - return 191 - case '(', ')', '-', '`': - return 333 - case '*': - return 389 - case '+', '<', '=', '>', '~': - return 584 - case '@': - return 1015 - case 'C', 'D', 'H', 'N', 'R', 'U': - return 722 - case 'F', 'T', 'Z': - return 611 - case 'G', 'O', 'Q': - return 778 - case 'J': - return 500 - case 'M': - return 833 - case 'W': - return 944 - case '^': - return 469 - case 'a', 'b', 'd', 'e', 'g', 'h', 'n', 'o', 'p', 'q', 'u': - return 556 - case 'c', 'k', 's', 'v', 'x', 'y', 'z': - return 500 - case 'f': - return 278 - case 'i', 'j', 'l': - return 222 - case 'm': - return 833 - case 'r': - return 333 - case 't': - return 278 - case 'w': - return 722 - case '{', '}': - return 334 - case '|': - return 260 - } - } - if character >= 0x1100 && (character <= 0x115f || character >= 0x2e80 && character <= 0x9fff || character >= 0xac00 && character <= 0xd7af || character >= 0xf900 && character <= 0xfaff || character >= 0xfe30 && character <= 0xfe4f || character >= 0xff01 && character <= 0xff60 || character >= 0xffe0 && character <= 0xffe6) { - return 1000 - } - return 556 -} - -func formatXLSXValue(value string, numeric bool, numberFormat int) string { - if !numeric || numberFormat != 4 { - return value - } - number, err := strconv.ParseFloat(strings.TrimSpace(value), 64) - if err != nil { - return value - } - formatted := strconv.FormatFloat(number, 'f', 2, 64) - parts := strings.SplitN(formatted, ".", 2) - digits := parts[0] - sign := "" - if strings.HasPrefix(digits, "-") { - sign, digits = "-", digits[1:] - } - for index := len(digits) - 3; index > 0; index -= 3 { - digits = digits[:index] + "," + digits[index:] - } - return sign + digits + "." + parts[1] -} diff --git a/minipdf-java/.mvn/wrapper/maven-wrapper.properties b/minipdf-java/.mvn/wrapper/maven-wrapper.properties deleted file mode 100644 index ffcab66a..00000000 --- a/minipdf-java/.mvn/wrapper/maven-wrapper.properties +++ /dev/null @@ -1,3 +0,0 @@ -wrapperVersion=3.3.4 -distributionType=only-script -distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.9/apache-maven-3.9.9-bin.zip diff --git a/minipdf-java/README.md b/minipdf-java/README.md deleted file mode 100644 index d36f8e36..00000000 --- a/minipdf-java/README.md +++ /dev/null @@ -1,107 +0,0 @@ -# MiniPdf for Java - -MiniPdf for Java supports JDK 8 through JDK 25 as a library and command-line tool for converting -DOCX, XLSX, and PPTX files to PDF without Microsoft Office or LibreOffice. - -## Install - -The library is available from Maven Central: - -```xml - - io.github.mini-software - minipdf - 0.4.1 - -``` - -## Library - -```java -import io.github.minisoftware.minipdf.MiniPdf; - -import java.nio.file.Paths; - -MiniPdf.convertToPdf( - Paths.get("document.docx"), - Paths.get("document.pdf")); -``` - -Use `MiniPdf.convertBytesToPdf` when the Office document is already in memory. -`ConversionOptions.withPageSize` overrides the output page size. - -Register fonts before converting when DOCX, XLSX, or PPTX content needs glyphs -that are not available in the standard PDF fonts: - -```java -import java.nio.file.Files; -import java.nio.file.Paths; - -try { - MiniPdf.registerFont( - "Noto Sans", - Files.readAllBytes(Paths.get("fonts/NotoSans-Regular.ttf"))); - MiniPdf.convertToPdf( - Paths.get("document.docx"), - Paths.get("document.pdf")); -} finally { - MiniPdf.clearRegisteredFonts(); -} -``` - -Registered fonts are process-wide. `clearRegisteredFonts` removes them when the -same process needs a different font set for a later conversion. - -## CLI - -Download the executable JAR with Maven: - -```powershell -mvn dependency:copy ` - -Dartifact=io.github.mini-software:minipdf-cli:0.4.1 ` - -DoutputDirectory=. -``` - -Convert a document: - -```powershell -java -jar minipdf-cli-0.4.1.jar input.pptx -o output.pdf -``` - -The CLI accepts `.docx`, `.xlsx`, and `.pptx` files. Run it with `--help` for -page-size and font-directory options. - -## Current Scope - -The Java implementation currently provides text-first Office conversion: - -- DOCX paragraphs, tabs, line breaks, explicit and section page breaks, and landscape page size -- XLSX shared strings, inline strings, numbers, and booleans -- PPTX slide text, native slide dimensions, and one PDF page per slide -- bounded OOXML ZIP loading and XML external-entity protection - -Advanced Office layout, images, charts, and embedded fonts are not yet fully -reproduced by the Java renderer. - -## Build and Test - -From this directory: - -```powershell -mvn -B -ntp verify -``` - -## Publishing - -The `Maven Central Publish` GitHub Actions workflow publishes both `minipdf` -and `minipdf-cli`. Configure these repository or `maven-central` environment -secrets before running it: - -- `MAVEN_CENTRAL_USERNAME` -- `MAVEN_CENTRAL_TOKEN` -- `GPG_PRIVATE_KEY` -- `GPG_PASSPHRASE` - -Publish a GitHub Release whose tag matches `java-v`, such as -`java-v0.4.1`, or manually dispatch the workflow with `version` set to `0.4.1`. -The requested version must match the Maven project version. diff --git a/minipdf-java/minipdf-cli/pom.xml b/minipdf-java/minipdf-cli/pom.xml deleted file mode 100644 index 2a144669..00000000 --- a/minipdf-java/minipdf-cli/pom.xml +++ /dev/null @@ -1,49 +0,0 @@ - - - 4.0.0 - - - io.github.mini-software - minipdf-java-parent - 0.4.1 - - - minipdf-cli - MiniPdf Java CLI - - - - ${project.groupId} - minipdf - ${project.version} - - - - - - - org.apache.maven.plugins - maven-shade-plugin - 3.6.1 - - - package - - shade - - - false - - - io.github.minisoftware.minipdf.cli.MiniPdfCommand - - - - - - - - - \ No newline at end of file diff --git a/minipdf-java/minipdf-cli/src/main/java/io/github/minisoftware/minipdf/cli/MiniPdfCommand.java b/minipdf-java/minipdf-cli/src/main/java/io/github/minisoftware/minipdf/cli/MiniPdfCommand.java deleted file mode 100644 index 06f0fc73..00000000 --- a/minipdf-java/minipdf-cli/src/main/java/io/github/minisoftware/minipdf/cli/MiniPdfCommand.java +++ /dev/null @@ -1,245 +0,0 @@ -package io.github.minisoftware.minipdf.cli; - -import io.github.minisoftware.minipdf.ConversionOptions; -import io.github.minisoftware.minipdf.MiniPdf; -import io.github.minisoftware.minipdf.MiniPdfException; -import io.github.minisoftware.minipdf.PageSize; - -import java.io.IOException; -import java.io.PrintWriter; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.util.Locale; -import java.util.stream.Stream; - -public final class MiniPdfCommand { - private static final String VERSION = "minipdf-java 0.4.1"; - - private PrintWriter out = new PrintWriter(System.out, true); - private PrintWriter err = new PrintWriter(System.err, true); - - public static void main(String[] args) { - MiniPdfCommand commandLine = createCommandLine(); - int exitCode = commandLine.execute(args); - System.exit(exitCode); - } - - public static MiniPdfCommand createCommandLine() { - return new MiniPdfCommand(); - } - - public void setOut(PrintWriter out) { - this.out = out; - } - - public void setErr(PrintWriter err) { - this.err = err; - } - - public int execute(String... args) { - try { - return executeCommand(args); - } catch (Exception exception) { - String message = exception.getMessage(); - err.println("Error: " + (message == null ? exception.toString() : message)); - return 1; - } - } - - private int executeCommand(String[] args) throws IOException, MiniPdfException, CliException { - boolean convertCommand = args.length > 0 && "convert".equals(args[0]); - ParsedCommand parsed = parse(args, convertCommand ? 1 : 0); - if (parsed.help) { - printUsage(convertCommand); - return 0; - } - if (parsed.version) { - out.println(VERSION); - return 0; - } - if (parsed.input == null) { - throw new CliException("input file is required"); - } - return convert(parsed.input, parsed.arguments); - } - - private ParsedCommand parse(String[] args, int startIndex) throws CliException { - ParsedCommand parsed = new ParsedCommand(); - boolean optionsEnabled = true; - for (int index = startIndex; index < args.length; index++) { - String argument = args[index]; - if (optionsEnabled && "--".equals(argument)) { - optionsEnabled = false; - } else if (optionsEnabled && ("-h".equals(argument) || "--help".equals(argument))) { - parsed.help = true; - } else if (optionsEnabled && ("-V".equals(argument) || "--version".equals(argument))) { - parsed.version = true; - } else if (optionsEnabled && ("-o".equals(argument) || "--output".equals(argument))) { - parsed.arguments.output = Paths.get(optionValue(args, ++index, argument)); - } else if (optionsEnabled && argument.startsWith("--output=")) { - parsed.arguments.output = Paths.get(inlineOptionValue(argument, "--output")); - } else if (optionsEnabled && "--fonts".equals(argument)) { - parsed.arguments.fonts = Paths.get(optionValue(args, ++index, argument)); - } else if (optionsEnabled && argument.startsWith("--fonts=")) { - parsed.arguments.fonts = Paths.get(inlineOptionValue(argument, "--fonts")); - } else if (optionsEnabled && "--paper-size".equals(argument)) { - parsed.arguments.paperSize = parsePaperSize(optionValue(args, ++index, argument)); - } else if (optionsEnabled && argument.startsWith("--paper-size=")) { - parsed.arguments.paperSize = parsePaperSize(inlineOptionValue(argument, "--paper-size")); - } else if (optionsEnabled && "--page-width".equals(argument)) { - parsed.arguments.pageWidth = parseFloat(optionValue(args, ++index, argument), argument); - } else if (optionsEnabled && argument.startsWith("--page-width=")) { - parsed.arguments.pageWidth = parseFloat(inlineOptionValue(argument, "--page-width"), "--page-width"); - } else if (optionsEnabled && "--page-height".equals(argument)) { - parsed.arguments.pageHeight = parseFloat(optionValue(args, ++index, argument), argument); - } else if (optionsEnabled && argument.startsWith("--page-height=")) { - parsed.arguments.pageHeight = parseFloat(inlineOptionValue(argument, "--page-height"), "--page-height"); - } else if (optionsEnabled && argument.startsWith("-")) { - throw new CliException("unknown option: " + argument); - } else if (parsed.input != null) { - throw new CliException("unexpected argument: " + argument); - } else { - parsed.input = Paths.get(argument); - } - } - return parsed; - } - - private static String optionValue(String[] args, int index, String option) throws CliException { - if (index >= args.length) { - throw new CliException("missing value for " + option); - } - return args[index]; - } - - private static String inlineOptionValue(String argument, String option) throws CliException { - String value = argument.substring(option.length() + 1); - if (value.isEmpty()) { - throw new CliException("missing value for " + option); - } - return value; - } - - private static PaperSizeArgument parsePaperSize(String value) throws CliException { - try { - return PaperSizeArgument.valueOf(value.toUpperCase(Locale.ROOT)); - } catch (IllegalArgumentException exception) { - throw new CliException("invalid value for --paper-size: " + value + " (expected A4 or LETTER)"); - } - } - - private static Float parseFloat(String value, String option) throws CliException { - try { - return Float.valueOf(value); - } catch (NumberFormatException exception) { - throw new CliException("invalid number for " + option + ": " + value); - } - } - - private void printUsage(boolean convertCommand) { - if (convertCommand) { - out.println("Usage: minipdf convert [OPTIONS] INPUT"); - out.println("Convert an Office document to PDF."); - } else { - out.println("Usage: minipdf [OPTIONS] INPUT"); - out.println(" minipdf convert [OPTIONS] INPUT"); - out.println("Convert XLSX, DOCX, and PPTX files to PDF with the Java MiniPdf engine."); - } - out.println(" -o, --output OUTPUT Output PDF path"); - out.println(" --fonts DIR Directory containing font files"); - out.println(" --paper-size SIZE A4 or LETTER"); - out.println(" --page-width POINTS Custom page width"); - out.println(" --page-height POINTS Custom page height"); - out.println(" -h, --help Show this help message"); - out.println(" -V, --version Show version information"); - } - - static final class ConversionArguments { - private Path output; - private Path fonts; - private PaperSizeArgument paperSize; - private Float pageWidth; - private Float pageHeight; - - private ConversionOptions conversionOptions() throws MiniPdfException, CliException { - if (paperSize != null && (pageWidth != null || pageHeight != null)) { - throw new CliException("use either --paper-size or --page-width/--page-height, not both"); - } - if ((pageWidth == null) != (pageHeight == null)) { - throw new CliException("--page-width and --page-height must be specified together"); - } - if (paperSize != null) { - return ConversionOptions.withPageSize(paperSize == PaperSizeArgument.A4 - ? PageSize.A4 - : PageSize.LETTER); - } - if (pageWidth != null) { - return ConversionOptions.withPageSize(PageSize.of(pageWidth, pageHeight)); - } - return ConversionOptions.defaults(); - } - } - - enum PaperSizeArgument { - A4, - LETTER - } - - private int convert(Path input, ConversionArguments arguments) - throws MiniPdfException, IOException, CliException { - if (!Files.isRegularFile(input)) { - throw new CliException("file not found: " + input); - } - String fileName = input.getFileName().toString(); - int dot = fileName.lastIndexOf('.'); - String extension = dot < 0 ? "" : fileName.substring(dot + 1).toLowerCase(Locale.ROOT); - if (!extension.equals("xlsx") && !extension.equals("docx") && !extension.equals("pptx")) { - throw new CliException("unsupported file type '." + extension + "'. Supported: .xlsx, .docx, .pptx"); - } - - if (arguments.fonts != null) { - registerFonts(arguments.fonts); - } - Path output = arguments.output == null ? replaceExtension(input, "pdf") : arguments.output; - MiniPdf.convertToPdf(input, output, arguments.conversionOptions()); - out.println(output); - return 0; - } - - private static void registerFonts(Path directory) throws IOException, CliException { - if (!Files.isDirectory(directory)) { - throw new CliException("font directory not found: " + directory); - } - try (Stream paths = Files.list(directory)) { - for (Path path : (Iterable) paths.filter(Files::isRegularFile)::iterator) { - String name = path.getFileName().toString(); - int dot = name.lastIndexOf('.'); - String extension = dot < 0 ? "" : name.substring(dot + 1).toLowerCase(Locale.ROOT); - if (extension.equals("ttf") || extension.equals("ttc") || extension.equals("otf")) { - MiniPdf.registerFont(dot < 0 ? name : name.substring(0, dot), Files.readAllBytes(path)); - } - } - } - } - - private static Path replaceExtension(Path input, String extension) { - String fileName = input.getFileName().toString(); - int dot = fileName.lastIndexOf('.'); - String outputName = (dot < 0 ? fileName : fileName.substring(0, dot)) + '.' + extension; - return input.resolveSibling(outputName); - } - - private static final class ParsedCommand { - private final ConversionArguments arguments = new ConversionArguments(); - private Path input; - private boolean help; - private boolean version; - } - - private static final class CliException extends Exception { - private CliException(String message) { - super(message); - } - } -} \ No newline at end of file diff --git a/minipdf-java/minipdf-tests/pom.xml b/minipdf-java/minipdf-tests/pom.xml deleted file mode 100644 index 37456510..00000000 --- a/minipdf-java/minipdf-tests/pom.xml +++ /dev/null @@ -1,51 +0,0 @@ - - - 4.0.0 - - - io.github.mini-software - minipdf-java-parent - 0.4.1 - - - minipdf-tests - MiniPdf Java Tests - - - 5.13.4 - true - - - - - ${project.groupId} - minipdf - ${project.version} - test - - - ${project.groupId} - minipdf-cli - ${project.version} - test - - - org.junit.jupiter - junit-jupiter - ${junit.version} - test - - - org.apache.pdfbox - pdfbox - test - - - org.apache.poi - poi-ooxml - test - - - \ No newline at end of file diff --git a/minipdf-java/minipdf-tests/src/test/java/io/github/minisoftware/minipdf/BasicOfficeConversionTest.java b/minipdf-java/minipdf-tests/src/test/java/io/github/minisoftware/minipdf/BasicOfficeConversionTest.java deleted file mode 100644 index be8b5367..00000000 --- a/minipdf-java/minipdf-tests/src/test/java/io/github/minisoftware/minipdf/BasicOfficeConversionTest.java +++ /dev/null @@ -1,362 +0,0 @@ -package io.github.minisoftware.minipdf; - -import org.apache.pdfbox.Loader; -import org.apache.pdfbox.cos.COSName; -import org.apache.pdfbox.pdmodel.PDDocument; -import org.apache.pdfbox.pdmodel.PDPage; -import org.apache.pdfbox.pdmodel.font.PDFont; -import org.apache.pdfbox.text.PDFTextStripper; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.io.TempDir; - -import java.io.ByteArrayOutputStream; -import java.io.InputStream; -import java.nio.charset.StandardCharsets; -import java.nio.file.Files; -import java.nio.file.Path; -import java.util.LinkedHashMap; -import java.util.Map; -import java.util.zip.ZipEntry; -import java.util.zip.ZipOutputStream; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.junit.jupiter.api.Assertions.assertSame; -import static org.junit.jupiter.api.Assertions.assertThrows; - -class BasicOfficeConversionTest { - @TempDir - Path temporaryDirectory; - - @AfterEach - void clearRegisteredFonts() { - MiniPdf.clearRegisteredFonts(); - } - - @Test - void convertsBasicDocxText() throws Exception { - byte[] docx = packageWith(mapOf( - "word/document.xml", - "Hello DOCX" - + "")); - - String pdf = pdfText(MiniPdf.convertBytesToPdf(docx)); - - assertTrue(pdf.startsWith("%PDF-1.4")); - assertTrue(pdf.contains("(Hello DOCX) Tj")); - } - - @Test - void convertsDocxPageBreakToSeparatePdfPage() throws Exception { - byte[] docx = packageWith(mapOf( - "word/document.xml", - "First" - + "Second" - + "")); - - String pdf = pdfText(MiniPdf.convertBytesToPdf(docx)); - - assertTrue(pdf.contains("/Count 2")); - assertTrue(pdf.indexOf("(First) Tj") < pdf.indexOf("(Second) Tj")); - } - - @Test - void convertsDocxHardLineBreakToSeparateTextLine() throws Exception { - byte[] docx = packageWith(mapOf( - "word/document.xml", - "First" - + "Second")); - - String pdf = pdfText(MiniPdf.convertBytesToPdf(docx)); - - assertTrue(pdf.contains("(First) Tj")); - assertTrue(pdf.contains("(Second) Tj")); - } - - @Test - void convertsDocxTabToPrintableSpacing() throws Exception { - byte[] docx = packageWith(mapOf( - "word/document.xml", - "Left" - + "Right")); - - String pdf = pdfText(MiniPdf.convertBytesToPdf(docx)); - - assertTrue(pdf.contains("(Left Right) Tj")); - } - - @Test - void convertsDocxNextPageSectionBreakToSeparatePdfPage() throws Exception { - byte[] docx = packageWith(mapOf( - "word/document.xml", - "" - + "" - + "First" - + "Second" - + "")); - - String pdf = pdfText(MiniPdf.convertBytesToPdf(docx)); - - assertTrue(pdf.contains("/Count 2")); - assertTrue(pdf.indexOf("(First) Tj") < pdf.indexOf("(Second) Tj")); - } - - @Test - void keepsContinuousDocxSectionOnTheSamePdfPage() throws Exception { - byte[] docx = packageWith(mapOf( - "word/document.xml", - "" - + "" - + "First" - + "Second" - + "")); - - String pdf = pdfText(MiniPdf.convertBytesToPdf(docx)); - - assertTrue(pdf.contains("/Count 1")); - } - - @Test - void usesRegisteredFontForDocxUnicodeText() throws Exception { - String text = "\u041f\u0440\u0438\u0432\u0435\u0442 DOCX"; - registerTestFont(); - byte[] docx = packageWith(mapOf( - "word/document.xml", - "" + text - + "")); - - byte[] pdf = MiniPdf.convertBytesToPdf(docx); - assertUnicodeTextUsesEmbeddedFont(pdf, text); - assertNativeTrueTypeFont(pdf); - } - - @Test - void usesNativeDocxLandscapePageSize() throws Exception { - byte[] docx = packageWith(mapOf( - "word/document.xml", - "Landscape" - + "" - + "" - + "")); - - String pdf = pdfText(MiniPdf.convertBytesToPdf(docx)); - - assertTrue(pdf.contains("/MediaBox [0 0 841.9 595.3]")); - } - - @Test - void convertsBasicXlsxSharedStringsAndNumbers() throws Exception { - Map entries = new LinkedHashMap<>(); - entries.put("xl/sharedStrings.xml", - "NameAlice"); - entries.put("xl/worksheets/sheet1.xml", - "030" - + "1"); - - String pdf = pdfText(MiniPdf.convertBytesToPdf(packageWith(entries))); - - assertTrue(pdf.startsWith("%PDF-1.4")); - assertTrue(pdf.contains("(Name 30) Tj")); - assertTrue(pdf.contains("(Alice) Tj")); - } - - @Test - void honorsPageSizeOverride() throws Exception { - byte[] docx = packageWith(mapOf( - "word/document.xml", - "Size" - + "" - + "")); - - byte[] pdf = MiniPdf.convertBytesToPdf( - docx, - ConversionOptions.withPageSize(PageSize.of(400.0f, 500.0f))); - - assertTrue(pdfText(pdf).contains("/MediaBox [0 0 400 500]")); - } - - @Test - void convertsPptxSlidesToSeparatePages() throws Exception { - Map entries = new LinkedHashMap<>(); - entries.put("ppt/presentation.xml", - "" - + "" - + ""); - entries.put("ppt/_rels/presentation.xml.rels", - ""); - entries.put("ppt/slides/slide1.xml", - "Second" - + ""); - entries.put("ppt/slides/slide2.xml", - "First" - + ""); - entries.put("ppt/slides/slide10.xml", - "Orphan" - + ""); - - String pdf = pdfText(MiniPdf.convertBytesToPdf(packageWith(entries))); - - assertTrue(pdf.startsWith("%PDF-1.4")); - assertTrue(pdf.contains("/MediaBox [0 0 720 540]")); - assertTrue(pdf.contains("/Count 2")); - assertTrue(pdf.indexOf("(First) Tj") < pdf.indexOf("(Second) Tj")); - assertTrue(!pdf.contains("(Orphan) Tj")); - } - - @Test - void usesRegisteredFontForPptxUnicodeText() throws Exception { - String text = "\u041f\u0440\u0438\u0432\u0435\u0442 PPTX"; - registerTestFont(); - Map entries = new LinkedHashMap<>(); - entries.put("ppt/presentation.xml", - "" - + ""); - entries.put("ppt/_rels/presentation.xml.rels", - ""); - entries.put("ppt/slides/slide1.xml", - "" + text - + ""); - - byte[] pdf = MiniPdf.convertBytesToPdf(packageWith(entries)); - assertUnicodeTextUsesEmbeddedFont(pdf, text); - assertNativeTrueTypeFont(pdf); - } - - private static void registerTestFont() throws Exception { - try (InputStream input = PDFont.class.getResourceAsStream( - "/org/apache/pdfbox/resources/ttf/LiberationSans-Regular.ttf")) { - assertNotNull(input); - MiniPdf.registerFont("Liberation Sans", readAllBytes(input)); - } - } - - private static void assertUnicodeTextUsesEmbeddedFont(byte[] pdf, String expected) throws Exception { - try (PDDocument document = Loader.loadPDF(pdf)) { - assertEquals(expected, new PDFTextStripper().getText(document).trim()); - boolean hasEmbeddedFont = false; - for (PDPage page : document.getPages()) { - for (COSName fontName : page.getResources().getFontNames()) { - if (page.getResources().getFont(fontName).isEmbedded()) { - hasEmbeddedFont = true; - } - } - } - assertTrue(hasEmbeddedFont); - } - } - - private static void assertNativeTrueTypeFont(byte[] pdf) { - assertTrue(pdfText(pdf).contains("/DescendantFonts [7 0 R] /ToUnicode 5 0 R")); - } - - @Test - void rejectsPptxWithoutSlides() throws Exception { - byte[] pptx = packageWith(mapOf( - "ppt/presentation.xml", - "")); - - MiniPdfException exception = assertThrows( - MiniPdfException.class, - () -> MiniPdf.convertBytesToPdf(pptx)); - - assertSame(MiniPdfException.Kind.INVALID_INPUT, exception.kind()); - } - - @Test - void classifiesMalformedPptxSlideAsXmlError() throws Exception { - Map entries = new LinkedHashMap<>(); - entries.put("ppt/presentation.xml", - "" - + ""); - entries.put("ppt/_rels/presentation.xml.rels", - ""); - entries.put("ppt/slides/slide1.xml", ""); - - MiniPdfException exception = assertThrows( - MiniPdfException.class, - () -> MiniPdf.convertBytesToPdf(packageWith(entries))); - - assertSame(MiniPdfException.Kind.XML_PARSE, exception.kind()); - } - - @Test - void classifiesMalformedSharedStringsAsXmlError() throws Exception { - Map entries = new LinkedHashMap<>(); - entries.put("xl/sharedStrings.xml", "broken"); - entries.put("xl/worksheets/sheet1.xml", ""); - - MiniPdfException exception = assertThrows( - MiniPdfException.class, - () -> MiniPdf.convertBytesToPdf(packageWith(entries))); - - assertSame(MiniPdfException.Kind.XML_PARSE, exception.kind()); - } - - @Test - void convertsPathToRequestedOutput() throws Exception { - Path input = temporaryDirectory.resolve("input.docx"); - Path output = temporaryDirectory.resolve("output.pdf"); - Files.write(input, packageWith(mapOf( - "word/document.xml", - "Path API" - + ""))); - - MiniPdf.convertToPdf(input, output); - - assertTrue(Files.isRegularFile(output)); - assertTrue(new String(Files.readAllBytes(output), StandardCharsets.ISO_8859_1) - .contains("(Path API) Tj")); - } - - @Test - void classifiesMissingInputAsIoError() { - Path missing = temporaryDirectory.resolve("missing.docx"); - - MiniPdfException exception = assertThrows( - MiniPdfException.class, - () -> MiniPdf.convertToPdfBytes(missing)); - - assertSame(MiniPdfException.Kind.IO, exception.kind()); - } - - private static byte[] packageWith(Map entries) throws Exception { - ByteArrayOutputStream bytes = new ByteArrayOutputStream(); - try (ZipOutputStream archive = new ZipOutputStream(bytes)) { - for (Map.Entry entry : entries.entrySet()) { - archive.putNextEntry(new ZipEntry(entry.getKey())); - archive.write(entry.getValue().getBytes(StandardCharsets.UTF_8)); - archive.closeEntry(); - } - } - return bytes.toByteArray(); - } - - private static Map mapOf(String... entries) { - Map values = new LinkedHashMap<>(); - for (int index = 0; index < entries.length; index += 2) { - values.put(entries[index], entries[index + 1]); - } - return values; - } - - private static byte[] readAllBytes(InputStream input) throws Exception { - ByteArrayOutputStream output = new ByteArrayOutputStream(); - byte[] buffer = new byte[8192]; - int read; - while ((read = input.read(buffer)) != -1) { - output.write(buffer, 0, read); - } - return output.toByteArray(); - } - - private static String pdfText(byte[] pdf) { - return new String(pdf, StandardCharsets.ISO_8859_1); - } -} \ No newline at end of file diff --git a/minipdf-java/minipdf-tests/src/test/java/io/github/minisoftware/minipdf/ClassicFixtureSmokeTest.java b/minipdf-java/minipdf-tests/src/test/java/io/github/minisoftware/minipdf/ClassicFixtureSmokeTest.java deleted file mode 100644 index e394bb9e..00000000 --- a/minipdf-java/minipdf-tests/src/test/java/io/github/minisoftware/minipdf/ClassicFixtureSmokeTest.java +++ /dev/null @@ -1,372 +0,0 @@ -package io.github.minisoftware.minipdf; - -import org.apache.pdfbox.Loader; -import org.apache.pdfbox.cos.COSName; -import org.apache.pdfbox.contentstream.operator.Operator; -import org.apache.pdfbox.pdfparser.PDFStreamParser; -import org.apache.pdfbox.pdmodel.PDDocument; -import org.apache.pdfbox.pdmodel.graphics.PDXObject; -import org.apache.pdfbox.pdmodel.graphics.form.PDFormXObject; -import org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject; -import org.apache.pdfbox.rendering.PDFRenderer; -import org.apache.pdfbox.text.PDFTextStripper; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; -import org.apache.poi.xssf.usermodel.XSSFSheet; -import org.junit.jupiter.api.Test; - -import java.io.ByteArrayOutputStream; -import java.awt.image.BufferedImage; -import java.nio.charset.StandardCharsets; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.util.Arrays; -import java.util.stream.Stream; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertTrue; - -class ClassicFixtureSmokeTest { - private static final Path REPOSITORY_ROOT = Paths.get("..", "..").toAbsolutePath().normalize(); - - @Test - void convertsTrackedXlsxFixture() throws Exception { - Path fixture = REPOSITORY_ROOT.resolve("tests/Issue_Files/xlsx/Simple invoice1.xlsx"); - - String pdf = extractedText(MiniPdf.convertToPdfBytes(fixture)); - - assertTrue(pdf.contains("INVOICE")); - assertTrue(pdf.contains("Wedding florals")); - } - - @Test - void defaultsUnspecifiedXlsxPaperSizeToA4() throws Exception { - Path fixture = REPOSITORY_ROOT.resolve("tests/Issue_Files/xlsx/XlsxIssue77_Template1.xlsx"); - - try (PDDocument document = Loader.loadPDF(MiniPdf.convertToPdfBytes(fixture))) { - assertEquals(PageSize.A4.width(), document.getPage(0).getMediaBox().getWidth(), 0.1f); - assertEquals(PageSize.A4.height(), document.getPage(0).getMediaBox().getHeight(), 0.1f); - assertEquals(6, document.getNumberOfPages()); - PDFTextStripper stripper = new PDFTextStripper(); - stripper.setStartPage(2); - stripper.setEndPage(2); - String secondPage = stripper.getText(document); - assertTrue(secondPage.contains("RMA AUTHORIZATION"), secondPage); - } - } - - @Test - void preservesMergedCellColumnWidths() throws Exception { - Path fixture = REPOSITORY_ROOT.resolve("tests/Issue_Files/xlsx/XlsxIssue77_MergedCellAlignment.xlsx"); - - try (PDDocument document = Loader.loadPDF(MiniPdf.convertToPdfBytes(fixture))) { - String text = new PDFTextStripper().getText(document); - assertTrue(text.contains("Horizontal Left + Vertical Bottom"), text); - BufferedImage page = new PDFRenderer(document).renderImageWithDPI(0, 150.0f); - int rightmostDarkPixel = 0; - int visibleOverflowPixels = 0; - for (int y = 0; y < page.getHeight(); y++) { - for (int x = 0; x < page.getWidth(); x++) { - int rgb = page.getRGB(x, y); - if (((rgb >> 16) & 0xff) < 80 - && ((rgb >> 8) & 0xff) < 80 - && (rgb & 0xff) < 80) { - rightmostDarkPixel = Math.max(rightmostDarkPixel, x); - if (x >= 160 && x < 370 && y >= 150 && y < 185) { - visibleOverflowPixels++; - } - } - } - } - assertTrue(rightmostDarkPixel > 1150, "rightmostDarkPixel=" + rightmostDarkPixel); - assertTrue(visibleOverflowPixels > 100, "visibleOverflowPixels=" + visibleOverflowPixels); - long mergedRightBorderPixels = java.util.stream.IntStream.range(250, 280) - .mapToLong(x -> java.util.stream.IntStream.range(360, 445) - .filter(y -> { - int rgb = page.getRGB(x, y); - return ((rgb >> 16) & 0xff) < 80 - && ((rgb >> 8) & 0xff) < 80 - && (rgb & 0xff) < 80; - }) - .count()) - .max() - .orElse(0); - assertTrue(mergedRightBorderPixels > 40, "mergedRightBorderPixels=" + mergedRightBorderPixels); - } - } - - @Test - void rendersScaledTablesAndGroupedArtwork() throws Exception { - Path fixture = REPOSITORY_ROOT.resolve("tests/Issue_Files/xlsx/Business expenses budget2.xlsx"); - - try (PDDocument document = Loader.loadPDF(MiniPdf.convertToPdfBytes(fixture))) { - assertEquals(4, document.getNumberOfPages()); - PDFTextStripper stripper = new PDFTextStripper(); - stripper.setStartPage(1); - stripper.setEndPage(1); - String firstPage = stripper.getText(document); - assertEquals(1, firstPage.split("EMPLOYEE COSTS", -1).length - 1, firstPage); - - long imageCount = 0; - for (COSName name : document.getPage(0).getResources().getXObjectNames()) { - if (document.getPage(0).getResources().getXObject(name) instanceof PDImageXObject) { - imageCount++; - } - } - assertTrue(imageCount >= 2, "imageCount=" + imageCount); - - BufferedImage page = new PDFRenderer(document).renderImageWithDPI(0, 150.0f); - long stripedPixels = 0; - long translucentShapePixels = 0; - for (int y = 0; y < page.getHeight(); y++) { - for (int x = 0; x < page.getWidth(); x++) { - int rgb = page.getRGB(x, y); - int red = (rgb >> 16) & 0xff; - int green = (rgb >> 8) & 0xff; - int blue = rgb & 0xff; - if (red >= 210 && red <= 220 && green >= 210 && green <= 220 && blue >= 210 && blue <= 220) { - stripedPixels++; - } - if (red >= 110 && red <= 125 && green >= 78 && green <= 92 && blue >= 70 && blue <= 84) { - translucentShapePixels++; - } - } - } - assertTrue(stripedPixels > 100_000, "stripedPixels=" + stripedPixels); - assertTrue(translucentShapePixels > 5_000, "translucentShapePixels=" + translucentShapePixels); - } - } - - @Test - void fitsWidthWhenFitHeightIsUnlimited() throws Exception { - Path fixture = REPOSITORY_ROOT.resolve("tests/Issue_Files/xlsx/Expense report basic1.xlsx"); - - try (PDDocument document = Loader.loadPDF(MiniPdf.convertToPdfBytes(fixture))) { - assertEquals(1, document.getNumberOfPages()); - } - } - - @Test - void convertsIssueXlsxWithCjkText() throws Exception { - Path fixture = REPOSITORY_ROOT.resolve("tests/Issue_Files/xlsx/Issue202609031340.xlsx"); - byte[] pdf = MiniPdf.convertToPdfBytes(fixture); - - try (PDDocument document = Loader.loadPDF(pdf)) { - String text = new PDFTextStripper().getText(document).replaceAll("\\s+", ""); - assertTrue(text.contains("注塑制程检验标准书"), text); - assertTrue(text.contains("产品型号"), text); - assertTrue(text.contains("包装"), text); - assertTrue(text.contains("项目"), text); - assertTrue(text.contains("频率"), text); - assertTrue(text.contains("首件"), text); - assertTrue(document.getNumberOfPages() == 4, "pages=" + document.getNumberOfPages()); - boolean hasImage = false; - boolean hasVectorForm = false; - int widestImage = 0; - for (COSName name : document.getPage(0).getResources().getXObjectNames()) { - PDXObject object = document.getPage(0).getResources().getXObject(name); - if (object instanceof PDImageXObject) { - PDImageXObject image = (PDImageXObject) object; - hasImage = true; - widestImage = Math.max(widestImage, image.getWidth()); - } else if (object instanceof PDFormXObject) { - hasVectorForm = true; - } - } - assertTrue(hasImage || hasVectorForm); - assertTrue(hasVectorForm || widestImage >= 2000, "widestImage=" + widestImage); - BufferedImage pageOne = new PDFRenderer(document).renderImageWithDPI(0, 150.0f); - int longestDarkRow = 0; - for (int y = 0; y < pageOne.getHeight(); y++) { - int darkPixels = 0; - for (int x = 0; x < pageOne.getWidth(); x++) { - int rgb = pageOne.getRGB(x, y); - if (((rgb >> 16) & 0xff) < 80 - && ((rgb >> 8) & 0xff) < 80 - && (rgb & 0xff) < 80) { - darkPixels++; - } - } - longestDarkRow = Math.max(longestDarkRow, darkPixels); - } - assertTrue(longestDarkRow > 1100, "longestDarkRow=" + longestDarkRow); - long pageThreeStrokes = new PDFStreamParser(document.getPage(2)).parse().stream() - .filter(Operator.class::isInstance) - .map(Operator.class::cast) - .filter(operator -> "S".equals(operator.getName())) - .count(); - assertTrue(pageThreeStrokes > 100, "pageThreeStrokes=" + pageThreeStrokes); - } - String rawPdf = new String(pdf, StandardCharsets.ISO_8859_1); - Matcher startXref = Pattern.compile("startxref\\s+(\\d+)").matcher(rawPdf); - assertTrue(startXref.find()); - assertTrue(rawPdf.startsWith("xref", Integer.parseInt(startXref.group(1)))); - } - - @Test - void convertsMultilingualXlsxWhenTheSelectedFontLacksGlyphs() throws Exception { - byte[] workbookBytes; - try (XSSFWorkbook workbook = new XSSFWorkbook(); - ByteArrayOutputStream output = new ByteArrayOutputStream()) { - XSSFSheet sheet = workbook.createSheet("Multilingual"); - sheet.createRow(0).createCell(0).setCellValue("Hello"); - sheet.createRow(1).createCell(0).setCellValue("안녕하세요 مرحبا 😀"); - workbook.write(output); - workbookBytes = output.toByteArray(); - } - - try (PDDocument document = Loader.loadPDF(MiniPdf.convertBytesToPdf(workbookBytes))) { - String text = new PDFTextStripper().getText(document); - assertTrue(text.contains("Hello"), text); - assertTrue(document.getNumberOfPages() > 0); - } - } - - @Test - void convertsTrackedDocxFixture() throws Exception { - Path fixture = REPOSITORY_ROOT.resolve("tests/Issue_Files/docx/Invoice.docx"); - - byte[] pdf = MiniPdf.convertToPdfBytes(fixture); - String text = extractedText(pdf); - - assertTrue(text.contains("Invoice"), text); - assertTrue(text.contains("ABC12345"), text); - assertTrue(pdfText(pdf).endsWith("%%EOF\n")); - } - - @Test - void preservesVietnameseTextAndPaginationInIssue91() throws Exception { - String windows = System.getenv("WINDIR"); - org.junit.jupiter.api.Assumptions.assumeTrue( - windows != null && Files.isRegularFile(Paths.get(windows, "Fonts", "times.ttf")), - "requires Times New Roman"); - Path fixture = REPOSITORY_ROOT.resolve("tests/Issue_Files/docx/TestIssue91.docx"); - byte[] pdf = MiniPdf.convertToPdfBytes(fixture); - - try (PDDocument document = Loader.loadPDF(pdf)) { - String text = new PDFTextStripper().getText(document); - assertEquals(3, document.getNumberOfPages()); - assertTrue(text.contains("PH\u1ee4 L\u1ee4C - KHO\u1ea2N VAY V\u1ed0N \u0110\u1ea6U T\u01af"), text); - assertTrue(text.contains("Bên B chấp nhận chịu, chỉ được gia hạn"), text); - } - try (PDDocument document = Loader.loadPDF(pdf)) { - PDFTextStripper secondPageStripper = new PDFTextStripper(); - secondPageStripper.setStartPage(2); - secondPageStripper.setEndPage(2); - String secondPage = secondPageStripper.getText(document).trim(); - assertTrue(secondPage.startsWith("Trong Phụ lục này"), secondPage); - assertTrue( - secondPage.replace("\r\n", "\n").contains( - "[INTEREST_RATE] %/năm.\nTrong trường hợp"), - secondPage); - assertTrue(lines(secondPage).anyMatch(line -> line.trim().equals("2")), secondPage); - } - } - - @Test - void rendersIssue93AsSinglePageForm() throws Exception { - String windows = System.getenv("WINDIR"); - org.junit.jupiter.api.Assumptions.assumeTrue( - windows != null && Files.isRegularFile(Paths.get(windows, "Fonts", "msyh.ttc")), - "requires Microsoft YaHei"); - Path fixture = REPOSITORY_ROOT.resolve("tests/Issue_Files/docx/TestIssue93.docx"); - - try (PDDocument document = Loader.loadPDF(MiniPdf.convertToPdfBytes(fixture))) { - String text = new PDFTextStripper().getText(document); - assertEquals(1, document.getNumberOfPages()); - assertTrue(text.contains("\u57fa\u672c\u4fe1\u606f"), text); - assertTrue(text.contains("A-1_1"), text); - } - } - - @Test - void rendersIssue66AsThreePageForm() throws Exception { - String windows = System.getenv("WINDIR"); - org.junit.jupiter.api.Assumptions.assumeTrue( - windows != null && Files.isRegularFile(Paths.get(windows, "Fonts", "msyh.ttc")), - "requires Microsoft YaHei"); - Path fixture = REPOSITORY_ROOT.resolve("tests/Issue_Files/docx/issues66.docx"); - - try (PDDocument document = Loader.loadPDF(MiniPdf.convertToPdfBytes(fixture))) { - String text = new PDFTextStripper().getText(document); - assertEquals(3, document.getNumberOfPages()); - assertTrue(text.contains("\u5fae\u7eb3\u52a0\u5de5\u5e73\u53f0\u5de5\u827a\u7533\u8bf7\u8868"), text); - assertTrue(text.contains("985 \u9ad8\u6821"), text); - PDFTextStripper firstPageStripper = new PDFTextStripper(); - firstPageStripper.setStartPage(1); - firstPageStripper.setEndPage(1); - String firstPage = firstPageStripper.getText(document); - assertFalse(firstPage.contains("\u4f7f\u7528\u6d89\u53ca\u771f\u7a7a\u7684\u8bbe\u5907"), firstPage); - assertTrue(lines(firstPage).anyMatch(line -> line.trim().equals("1")), firstPage); - PDFTextStripper secondPageStripper = new PDFTextStripper(); - secondPageStripper.setStartPage(2); - secondPageStripper.setEndPage(2); - assertTrue(lines(secondPageStripper.getText(document)) - .anyMatch(line -> line.trim().equals("2"))); - PDFTextStripper thirdPageStripper = new PDFTextStripper(); - thirdPageStripper.setStartPage(3); - thirdPageStripper.setEndPage(3); - assertTrue(lines(thirdPageStripper.getText(document)) - .anyMatch(line -> line.trim().equals("3"))); - } - } - - @Test - void skipsUnsupportedDocxPictures() throws Exception { - Path fixture = REPOSITORY_ROOT.resolve("tests/Issue_Files/docx/OSCAR WARD.docx"); - - try (PDDocument document = Loader.loadPDF(MiniPdf.convertToPdfBytes(fixture))) { - assertTrue(document.getNumberOfPages() > 0); - } - } - - @Test - void preservesLiteralTextAroundPageNumberField() throws Exception { - String windows = System.getenv("WINDIR"); - org.junit.jupiter.api.Assumptions.assumeTrue( - windows != null && Files.isRegularFile(Paths.get(windows, "Fonts", "msyh.ttc")), - "requires Microsoft YaHei"); - Path fixture = REPOSITORY_ROOT.resolve("tests/Issue_Files/docx/issue202605.docx"); - - try (PDDocument document = Loader.loadPDF(MiniPdf.convertToPdfBytes(fixture))) { - assertEquals(3, document.getNumberOfPages()); - for (int page = 1; page <= document.getNumberOfPages(); page++) { - PDFTextStripper stripper = new PDFTextStripper(); - stripper.setStartPage(page); - stripper.setEndPage(page); - String expected = page + " \u9801"; - assertTrue(lines(stripper.getText(document)) - .anyMatch(line -> line.trim().equals(expected)), "missing " + expected); - } - } - } - - @Test - void convertsIssuePptx() throws Exception { - Path fixture = REPOSITORY_ROOT.resolve("tests/Issue_Files/pptx/Asian Pacific.pptx"); - - byte[] pdf = MiniPdf.convertToPdfBytes(fixture); - - try (PDDocument document = Loader.loadPDF(pdf)) { - assertTrue(document.getNumberOfPages() > 0); - } - assertTrue(pdfText(pdf).endsWith("%%EOF\n")); - } - - private static String pdfText(byte[] pdf) { - return new String(pdf, StandardCharsets.ISO_8859_1); - } - - private static String extractedText(byte[] pdf) throws Exception { - try (PDDocument document = Loader.loadPDF(pdf)) { - return new PDFTextStripper().getText(document); - } - } - - private static Stream lines(String value) { - return Arrays.stream(value.split("\\R")); - } -} \ No newline at end of file diff --git a/minipdf-java/minipdf-tests/src/test/java/io/github/minisoftware/minipdf/FontRegistrationTest.java b/minipdf-java/minipdf-tests/src/test/java/io/github/minisoftware/minipdf/FontRegistrationTest.java deleted file mode 100644 index 20828699..00000000 --- a/minipdf-java/minipdf-tests/src/test/java/io/github/minisoftware/minipdf/FontRegistrationTest.java +++ /dev/null @@ -1,39 +0,0 @@ -package io.github.minisoftware.minipdf; - -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.Test; - -import java.util.UUID; - -import static org.junit.jupiter.api.Assertions.assertArrayEquals; -import static org.junit.jupiter.api.Assertions.assertThrows; - -class FontRegistrationTest { - @AfterEach - void clearRegisteredFonts() { - MiniPdf.clearRegisteredFonts(); - } - - @Test - void registrationDefensivelyCopiesFontData() { - byte[] data = {1, 2, 3}; - String name = "test-" + UUID.randomUUID(); - - MiniPdf.registerFont(name, data); - data[0] = 9; - - RegisteredFont registered = MiniPdf.registeredFonts().stream() - .filter(font -> font.name().equals(name)) - .findFirst() - .orElseThrow(() -> new AssertionError("registered font not found")); - byte[] returned = registered.data(); - returned[1] = 9; - - assertArrayEquals(new byte[]{1, 2, 3}, registered.data()); - } - - @Test - void rejectsBlankFontNames() { - assertThrows(IllegalArgumentException.class, () -> MiniPdf.registerFont(" ", new byte[]{1})); - } -} \ No newline at end of file diff --git a/minipdf-java/minipdf-tests/src/test/java/io/github/minisoftware/minipdf/OfficeFormatDetectionTest.java b/minipdf-java/minipdf-tests/src/test/java/io/github/minisoftware/minipdf/OfficeFormatDetectionTest.java deleted file mode 100644 index 4bbfd4d9..00000000 --- a/minipdf-java/minipdf-tests/src/test/java/io/github/minisoftware/minipdf/OfficeFormatDetectionTest.java +++ /dev/null @@ -1,61 +0,0 @@ -package io.github.minisoftware.minipdf; - -import org.junit.jupiter.api.Test; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.util.zip.ZipEntry; -import java.util.zip.ZipOutputStream; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertSame; -import static org.junit.jupiter.api.Assertions.assertThrows; - -class OfficeFormatDetectionTest { - @Test - void detectsOfficeFormatsFromPackageEntries() throws Exception { - assertSame(OfficeFormat.DOCX, MiniPdf.detectOfficeFormat(packageWith("word/document.xml"))); - assertSame(OfficeFormat.XLSX, MiniPdf.detectOfficeFormat(packageWith("xl/workbook.xml"))); - assertSame(OfficeFormat.PPTX, MiniPdf.detectOfficeFormat(packageWith("ppt/presentation.xml"))); - } - - @Test - void returnsUnknownForOtherZipPackages() throws Exception { - assertSame(OfficeFormat.UNKNOWN, MiniPdf.detectOfficeFormat(packageWith("custom/data.xml"))); - } - - @Test - void normalizesBackslashesAndCase() throws Exception { - assertSame(OfficeFormat.DOCX, MiniPdf.detectOfficeFormat(packageWith("WORD\\document.xml"))); - } - - @Test - void rejectsNonZipInput() { - MiniPdfException exception = assertThrows( - MiniPdfException.class, - () -> MiniPdf.detectOfficeFormat("not a zip".getBytes())); - - assertSame(MiniPdfException.Kind.ZIP_PACKAGE, exception.kind()); - assertEquals("input is not a ZIP package", exception.getMessage()); - } - - @Test - void pptxWithoutSlidesReportsInvalidInput() throws Exception { - MiniPdfException exception = assertThrows( - MiniPdfException.class, - () -> MiniPdf.convertBytesToPdf(packageWith("ppt/presentation.xml"))); - - assertSame(MiniPdfException.Kind.INVALID_INPUT, exception.kind()); - assertEquals("PPTX package does not contain a slide", exception.getMessage()); - } - - private static byte[] packageWith(String entryName) throws IOException { - ByteArrayOutputStream bytes = new ByteArrayOutputStream(); - try (ZipOutputStream archive = new ZipOutputStream(bytes)) { - archive.putNextEntry(new ZipEntry(entryName)); - archive.write("".getBytes()); - archive.closeEntry(); - } - return bytes.toByteArray(); - } -} \ No newline at end of file diff --git a/minipdf-java/minipdf-tests/src/test/java/io/github/minisoftware/minipdf/OoxmlSecurityTest.java b/minipdf-java/minipdf-tests/src/test/java/io/github/minisoftware/minipdf/OoxmlSecurityTest.java deleted file mode 100644 index 737955f3..00000000 --- a/minipdf-java/minipdf-tests/src/test/java/io/github/minisoftware/minipdf/OoxmlSecurityTest.java +++ /dev/null @@ -1,52 +0,0 @@ -package io.github.minisoftware.minipdf; - -import org.junit.jupiter.api.Test; - -import java.io.ByteArrayOutputStream; -import java.nio.charset.StandardCharsets; -import java.util.Collections; -import java.util.Map; -import java.util.zip.ZipEntry; -import java.util.zip.ZipOutputStream; - -import static org.junit.jupiter.api.Assertions.assertSame; -import static org.junit.jupiter.api.Assertions.assertThrows; - -class OoxmlSecurityTest { - @Test - void rejectsTraversalEntryNames() throws Exception { - byte[] archive = packageWith(Collections.singletonMap("../word/document.xml", "")); - - MiniPdfException exception = assertThrows( - MiniPdfException.class, - () -> MiniPdf.detectOfficeFormat(archive)); - - assertSame(MiniPdfException.Kind.ZIP_PACKAGE, exception.kind()); - } - - @Test - void rejectsExternalEntities() throws Exception { - String document = "]>" - + "&xxe;" - + ""; - byte[] docx = packageWith(Collections.singletonMap("word/document.xml", document)); - - MiniPdfException exception = assertThrows( - MiniPdfException.class, - () -> MiniPdf.convertBytesToPdf(docx)); - - assertSame(MiniPdfException.Kind.XML_PARSE, exception.kind()); - } - - private static byte[] packageWith(Map entries) throws Exception { - ByteArrayOutputStream bytes = new ByteArrayOutputStream(); - try (ZipOutputStream archive = new ZipOutputStream(bytes)) { - for (Map.Entry entry : entries.entrySet()) { - archive.putNextEntry(new ZipEntry(entry.getKey())); - archive.write(entry.getValue().getBytes(StandardCharsets.UTF_8)); - archive.closeEntry(); - } - } - return bytes.toByteArray(); - } -} \ No newline at end of file diff --git a/minipdf-java/minipdf-tests/src/test/java/io/github/minisoftware/minipdf/PageSizeTest.java b/minipdf-java/minipdf-tests/src/test/java/io/github/minisoftware/minipdf/PageSizeTest.java deleted file mode 100644 index 790a21de..00000000 --- a/minipdf-java/minipdf-tests/src/test/java/io/github/minisoftware/minipdf/PageSizeTest.java +++ /dev/null @@ -1,36 +0,0 @@ -package io.github.minisoftware.minipdf; - -import org.junit.jupiter.api.Test; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertSame; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; - -class PageSizeTest { - @Test - void exposesStandardPageSizes() { - assertEquals(595.28f, PageSize.A4.width()); - assertEquals(841.89f, PageSize.A4.height()); - assertEquals(612.0f, PageSize.LETTER.width()); - assertEquals(792.0f, PageSize.LETTER.height()); - } - - @Test - void rejectsInvalidCustomDimensions() { - for (float invalid : new float[]{0.0f, -1.0f, Float.NaN, Float.POSITIVE_INFINITY}) { - MiniPdfException exception = assertThrows( - MiniPdfException.class, - () -> PageSize.of(invalid, 100.0f)); - assertSame(MiniPdfException.Kind.INVALID_INPUT, exception.kind()); - } - } - - @Test - void optionsExposeAnOptionalOverride() throws MiniPdfException { - assertTrue(!ConversionOptions.defaults().pageSize().isPresent()); - PageSize custom = PageSize.of(400.0f, 500.0f); - assertEquals(custom, ConversionOptions.withPageSize(custom).pageSize() - .orElseThrow(() -> new AssertionError("page size override not found"))); - } -} \ No newline at end of file diff --git a/minipdf-java/minipdf-tests/src/test/java/io/github/minisoftware/minipdf/PdfDocumentTest.java b/minipdf-java/minipdf-tests/src/test/java/io/github/minisoftware/minipdf/PdfDocumentTest.java deleted file mode 100644 index 32967d39..00000000 --- a/minipdf-java/minipdf-tests/src/test/java/io/github/minisoftware/minipdf/PdfDocumentTest.java +++ /dev/null @@ -1,226 +0,0 @@ -package io.github.minisoftware.minipdf; - -import org.apache.pdfbox.Loader; -import org.apache.pdfbox.cos.COSName; -import org.apache.pdfbox.pdmodel.PDDocument; -import org.apache.pdfbox.text.PDFTextStripper; -import org.junit.jupiter.api.Test; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.nio.charset.StandardCharsets; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; - -class PdfDocumentTest { - @Test - void writesBasicPdfDocument() { - PdfDocument document = new PdfDocument(); - PdfPage page = document.addPage(PageSize.A4.width(), PageSize.A4.height()); - page.addText("Hello from Java MiniPdf", 72.0f, 760.0f, 14.0f, PdfColor.BLACK, false); - - byte[] pdf = document.toBytes(); - String text = new String(pdf, StandardCharsets.ISO_8859_1); - - assertTrue(text.startsWith("%PDF-1.4\n")); - assertTrue(text.contains("(Hello from Java MiniPdf) Tj")); - assertTrue(text.endsWith("%%EOF\n")); - } - - @Test - void declaresStreamLengthsExactly() { - PdfDocument document = new PdfDocument(); - document.addPage(612.0f, 792.0f) - .addText("Hello", 72.0f, 700.0f, 12.0f, PdfColor.BLACK, true); - byte[] pdf = document.toBytes(); - String text = new String(pdf, StandardCharsets.ISO_8859_1); - Matcher matcher = Pattern.compile("/Length (\\d+) >>\\nstream\\n").matcher(text); - - int streams = 0; - while (matcher.find()) { - int streamStart = matcher.end(); - int streamEnd = text.indexOf("\nendstream", streamStart); - assertEquals(Integer.parseInt(matcher.group(1)), streamEnd - streamStart); - streams++; - } - assertTrue(streams > 0); - } - - @Test - void escapesPdfLiteralText() { - PdfDocument document = new PdfDocument(); - document.addPage(100.0f, 100.0f) - .addText("a(b)\\c", 10.0f, 10.0f, 10.0f, PdfColor.BLACK, false); - - String pdf = new String(document.toBytes(), StandardCharsets.ISO_8859_1); - - assertTrue(pdf.contains("(a\\(b\\)\\\\c) Tj")); - } - - @Test - void writesXrefAtDeclaredOffset() { - PdfDocument document = new PdfDocument(); - document.addPage(100.0f, 100.0f); - byte[] pdf = document.toBytes(); - String text = new String(pdf, StandardCharsets.ISO_8859_1); - Matcher matcher = Pattern.compile("startxref\\n(\\d+)\\n%%EOF").matcher(text); - - assertTrue(matcher.find()); - assertTrue(text.startsWith("xref\n", Integer.parseInt(matcher.group(1)))); - } - - @Test - void writesUnicodeWithRegisteredTrueTypeFont() throws Exception { - byte[] fontData = resourceBytes("/org/apache/pdfbox/resources/ttf/LiberationSans-Regular.ttf"); - MiniPdf.registerFont("Liberation Sans", fontData); - try { - PdfDocument document = new PdfDocument(); - document.addPage(300.0f, 200.0f) - .addText("Hello Привет", 20.0f, 150.0f, 14.0f, PdfColor.BLACK, false); - - byte[] pdf = document.toBytes(); - String raw = new String(pdf, StandardCharsets.ISO_8859_1); - assertTrue(raw.contains("/Subtype /Type0")); - assertTrue(raw.contains("/FontFile2")); - assertTrue(raw.contains("/CIDToGIDMap")); - assertTrue(raw.contains("/ToUnicode")); - - try (PDDocument parsed = Loader.loadPDF(pdf)) { - assertEquals("Hello Привет", new PDFTextStripper().getText(parsed).trim()); - boolean embedded = false; - for (COSName fontName : parsed.getPage(0).getResources().getFontNames()) { - if (parsed.getPage(0).getResources().getFont(fontName).isEmbedded()) { - embedded = true; - } - } - assertTrue(embedded); - } - } finally { - MiniPdf.clearRegisteredFonts(); - } - } - - @Test - void writesUnicodeWithRegisteredTrueTypeCollection() throws Exception { - byte[] fontData = resourceBytes("/org/apache/pdfbox/resources/ttf/LiberationSans-Regular.ttf"); - MiniPdf.registerFont("Liberation Sans TTC", trueTypeCollection(fontData)); - try { - PdfDocument document = new PdfDocument(); - document.addPage(300.0f, 200.0f) - .addText("Hello Привет", 20.0f, 150.0f, 14.0f, PdfColor.BLACK, false); - - byte[] pdf = document.toBytes(); - try (PDDocument parsed = Loader.loadPDF(pdf)) { - assertEquals("Hello Привет", new PDFTextStripper().getText(parsed).trim()); - } - assertTrue(new String(pdf, StandardCharsets.ISO_8859_1).contains("/Subtype /Type0")); - } finally { - MiniPdf.clearRegisteredFonts(); - } - } - - @Test - void unsupportedSupplementaryTextDoesNotDisableSupportedFont() throws Exception { - byte[] fontData = resourceBytes("/org/apache/pdfbox/resources/ttf/LiberationSans-Regular.ttf"); - MiniPdf.registerFont("Liberation Sans", fontData); - try { - PdfDocument document = new PdfDocument(); - PdfPage page = document.addPage(300.0f, 200.0f); - page.addText("Привет", 20.0f, 150.0f, 14.0f, PdfColor.BLACK, false); - page.addText("😀", 20.0f, 120.0f, 14.0f, PdfColor.BLACK, false); - - try (PDDocument parsed = Loader.loadPDF(document.toBytes())) { - assertTrue(new PDFTextStripper().getText(parsed).contains("Привет")); - } - } finally { - MiniPdf.clearRegisteredFonts(); - } - } - - @Test - void rejectsTrueTypeReadsOutsideDeclaredTable() throws Exception { - byte[] fontData = resourceBytes("/org/apache/pdfbox/resources/ttf/LiberationSans-Regular.ttf"); - int headRecord = tableRecord(fontData, "head"); - fontData[headRecord + 12] = 0; - fontData[headRecord + 13] = 0; - fontData[headRecord + 14] = 0; - fontData[headRecord + 15] = 1; - - assertThrows( - IllegalArgumentException.class, - () -> TrueTypeFontData.parse("invalid", fontData)); - } - - @Test - void rejectsInvalidGeometryAndColor() { - PdfDocument document = new PdfDocument(); - assertThrows(IllegalArgumentException.class, () -> document.addPage(0.0f, 100.0f)); - assertThrows(IllegalArgumentException.class, () -> new PdfColor(1.1f, 0.0f, 0.0f)); - } - - private static byte[] resourceBytes(String name) throws IOException { - try (InputStream input = PdfDocumentTest.class.getResourceAsStream(name)) { - assertNotNull(input); - ByteArrayOutputStream output = new ByteArrayOutputStream(); - byte[] buffer = new byte[8192]; - int read; - while ((read = input.read(buffer)) != -1) { - output.write(buffer, 0, read); - } - return output.toByteArray(); - } - } - - private static int tableRecord(byte[] fontData, String tableName) { - int tableCount = ((fontData[4] & 0xFF) << 8) | (fontData[5] & 0xFF); - for (int index = 0; index < tableCount; index++) { - int record = 12 + index * 16; - String name = new String(fontData, record, 4, StandardCharsets.ISO_8859_1); - if (tableName.equals(name)) { - return record; - } - } - throw new AssertionError("missing font table: " + tableName); - } - - private static byte[] trueTypeCollection(byte[] fontData) { - int collectionHeaderLength = 16; - byte[] collection = new byte[collectionHeaderLength + fontData.length]; - collection[0] = 't'; - collection[1] = 't'; - collection[2] = 'c'; - collection[3] = 'f'; - writeU32(collection, 4, 0x00010000L); - writeU32(collection, 8, 1); - writeU32(collection, 12, collectionHeaderLength); - System.arraycopy(fontData, 0, collection, collectionHeaderLength, fontData.length); - - int tableCount = ((fontData[4] & 0xFF) << 8) | (fontData[5] & 0xFF); - for (int index = 0; index < tableCount; index++) { - int record = collectionHeaderLength + 12 + index * 16; - long tableOffset = readU32(collection, record + 8); - writeU32(collection, record + 8, tableOffset + collectionHeaderLength); - } - return collection; - } - - private static long readU32(byte[] data, int offset) { - return ((long) (data[offset] & 0xFF) << 24) - | ((long) (data[offset + 1] & 0xFF) << 16) - | ((long) (data[offset + 2] & 0xFF) << 8) - | (data[offset + 3] & 0xFF); - } - - private static void writeU32(byte[] data, int offset, long value) { - data[offset] = (byte) (value >> 24); - data[offset + 1] = (byte) (value >> 16); - data[offset + 2] = (byte) (value >> 8); - data[offset + 3] = (byte) value; - } -} \ No newline at end of file diff --git a/minipdf-java/minipdf-tests/src/test/java/io/github/minisoftware/minipdf/cli/MiniPdfCommandTest.java b/minipdf-java/minipdf-tests/src/test/java/io/github/minisoftware/minipdf/cli/MiniPdfCommandTest.java deleted file mode 100644 index 7fe4a5d8..00000000 --- a/minipdf-java/minipdf-tests/src/test/java/io/github/minisoftware/minipdf/cli/MiniPdfCommandTest.java +++ /dev/null @@ -1,128 +0,0 @@ -package io.github.minisoftware.minipdf.cli; - -import org.apache.pdfbox.Loader; -import org.apache.pdfbox.pdmodel.PDDocument; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.io.TempDir; - -import java.io.PrintWriter; -import java.io.StringWriter; -import java.nio.charset.StandardCharsets; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; - -class MiniPdfCommandTest { - private static final Path REPOSITORY_ROOT = Paths.get("..", "..").toAbsolutePath().normalize(); - - @TempDir - Path temporaryDirectory; - - @Test - void convertsXlsxWithDirectSyntax() throws Exception { - Path source = REPOSITORY_ROOT.resolve("tests/Issue_Files/xlsx/Simple invoice1.xlsx"); - Path output = temporaryDirectory.resolve("direct.pdf"); - - CommandResult result = execute(source.toString(), "-o", output.toString()); - - assertEquals(0, result.exitCode()); - assertTrue(new String(Files.readAllBytes(output), StandardCharsets.ISO_8859_1) - .startsWith("%PDF-1.4")); - assertTrue(result.stdout().contains(output.toString())); - } - - @Test - void convertsDocxWithSubcommandAndCustomSize() throws Exception { - Path source = REPOSITORY_ROOT.resolve("tests/Issue_Files/docx/Invoice.docx"); - Path output = temporaryDirectory.resolve("subcommand.pdf"); - - CommandResult result = execute( - "convert", source.toString(), "-o", output.toString(), - "--page-width", "400", "--page-height", "500"); - - assertEquals(0, result.exitCode()); - try (PDDocument document = Loader.loadPDF(output.toFile())) { - assertEquals(400.0f, document.getPage(0).getMediaBox().getWidth(), 0.1f); - assertEquals(500.0f, document.getPage(0).getMediaBox().getHeight(), 0.1f); - } - } - - @Test - void convertsPptxWithDirectSyntax() throws Exception { - Path source = REPOSITORY_ROOT.resolve("tests/Issue_Files/pptx/Asian Pacific.pptx"); - Path output = temporaryDirectory.resolve("slides.pdf"); - - CommandResult result = execute(source.toString(), "-o", output.toString()); - - assertEquals(0, result.exitCode()); - try (PDDocument document = Loader.loadPDF(output.toFile())) { - assertTrue(document.getNumberOfPages() > 0); - } - assertTrue(result.stdout().contains(output.toString())); - } - - @Test - void rejectsConflictingPageOptions() { - Path source = REPOSITORY_ROOT.resolve("tests/Issue_Files/xlsx/Simple invoice1.xlsx"); - - CommandResult result = execute( - source.toString(), "--paper-size", "a4", "--page-width", "400", "--page-height", "500"); - - assertEquals(1, result.exitCode()); - assertTrue(result.stderr().contains("use either --paper-size")); - } - - @Test - void printsHelpWithoutRequiringInput() { - CommandResult result = execute("--help"); - - assertEquals(0, result.exitCode()); - assertTrue(result.stdout().contains("Usage: minipdf")); - assertEquals("", result.stderr()); - } - - @Test - void rejectsUnknownOption() { - CommandResult result = execute("--unknown"); - - assertEquals(1, result.exitCode()); - assertTrue(result.stderr().contains("unknown option: --unknown")); - } - - private static CommandResult execute(String... arguments) { - MiniPdfCommand commandLine = MiniPdfCommand.createCommandLine(); - StringWriter stdout = new StringWriter(); - StringWriter stderr = new StringWriter(); - commandLine.setOut(new PrintWriter(stdout, true)); - commandLine.setErr(new PrintWriter(stderr, true)); - int exitCode = commandLine.execute(arguments); - return new CommandResult(exitCode, stdout.toString(), stderr.toString()); - } - - private static final class CommandResult { - private final int exitCode; - private final String stdout; - private final String stderr; - - private CommandResult(int exitCode, String stdout, String stderr) { - this.exitCode = exitCode; - this.stdout = stdout; - this.stderr = stderr; - } - - private int exitCode() { - return exitCode; - } - - private String stdout() { - return stdout; - } - - private String stderr() { - return stderr; - } - } -} \ No newline at end of file diff --git a/minipdf-java/minipdf-tests/src/test/java/io/github/minisoftware/minipdf/internal/FontEmbeddingPolicyTest.java b/minipdf-java/minipdf-tests/src/test/java/io/github/minisoftware/minipdf/internal/FontEmbeddingPolicyTest.java deleted file mode 100644 index 1c59d118..00000000 --- a/minipdf-java/minipdf-tests/src/test/java/io/github/minisoftware/minipdf/internal/FontEmbeddingPolicyTest.java +++ /dev/null @@ -1,17 +0,0 @@ -package io.github.minisoftware.minipdf.internal; - -import org.junit.jupiter.api.Test; - -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertTrue; - -class FontEmbeddingPolicyTest { - @Test - void disablesSubsettingOnlyForJdk10() { - assertTrue(FontEmbeddingPolicy.shouldSubset("1.8")); - assertTrue(FontEmbeddingPolicy.shouldSubset("9")); - assertFalse(FontEmbeddingPolicy.shouldSubset("10")); - assertTrue(FontEmbeddingPolicy.shouldSubset("11")); - assertTrue(FontEmbeddingPolicy.shouldSubset("25")); - } -} \ No newline at end of file diff --git a/minipdf-java/minipdf-tests/src/test/java/io/github/minisoftware/minipdf/internal/docx/PoiDocxRendererTest.java b/minipdf-java/minipdf-tests/src/test/java/io/github/minisoftware/minipdf/internal/docx/PoiDocxRendererTest.java deleted file mode 100644 index 01c2b22a..00000000 --- a/minipdf-java/minipdf-tests/src/test/java/io/github/minisoftware/minipdf/internal/docx/PoiDocxRendererTest.java +++ /dev/null @@ -1,325 +0,0 @@ -package io.github.minisoftware.minipdf.internal.docx; - -import org.apache.pdfbox.pdmodel.font.PDType1Font; -import org.apache.pdfbox.pdmodel.font.PDFont; -import org.apache.pdfbox.pdmodel.font.Standard14Fonts; -import org.apache.poi.xwpf.usermodel.LineSpacingRule; -import org.apache.poi.xwpf.usermodel.XWPFDocument; -import org.apache.poi.xwpf.usermodel.XWPFParagraph; -import org.apache.poi.xwpf.usermodel.XWPFRun; -import org.apache.poi.xwpf.usermodel.XWPFTableCell; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTPPr; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTBorder; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTP; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.STBorder; -import org.junit.jupiter.api.Test; - -import java.util.Arrays; -import java.util.List; -import java.util.stream.Collectors; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertNull; -import static org.junit.jupiter.api.Assertions.assertSame; - -class PoiDocxRendererTest { - @Test - void preservesExplicitlyBorderlessTableEdges() { - CTBorder noBorder = CTBorder.Factory.newInstance(); - noBorder.setVal(STBorder.NONE); - - assertEquals("none", PoiDocxRenderer.resolveBorderStyle(null, noBorder)); - assertEquals("none", PoiDocxRenderer.resolveBorderStyle(noBorder, null)); - assertNull(PoiDocxRenderer.resolveBorderStyle(null, null)); - } - - @Test - void carriesRunHighlightIntoParagraphSegments() throws Exception { - PDFont font = new PDType1Font(Standard14Fonts.FontName.TIMES_ROMAN); - PoiDocxRenderer.ParagraphFonts fonts = new PoiDocxRenderer.ParagraphFonts( - font, font, font, font, font, font, font, "Times New Roman", "SimSun"); - try (XWPFDocument document = new XWPFDocument()) { - XWPFParagraph paragraph = document.createParagraph(); - XWPFRun run = paragraph.createRun(); - run.setTextHighlightColor("yellow"); - run.setText("highlighted"); - - List segments = - PoiDocxRenderer.paragraphSegments(paragraph, fonts, 12.0f); - - assertNotNull(segments.get(0).highlight()); - } - } - - @Test - void rendersFootnoteReferencesAsNumbersWithoutInliningFootnoteText() throws Exception { - try (XWPFDocument document = new XWPFDocument()) { - XWPFRun run = document.createParagraph().createRun(); - run.getCTR().addNewFootnoteReference().setId(java.math.BigInteger.ONE); - - assertEquals("1", PoiDocxRenderer.runText(run)); - } - } - - @Test - void mapsWingdingsCheckSymbolToUnicode() throws Exception { - try (XWPFDocument document = new XWPFDocument()) { - XWPFRun run = document.createParagraph().createRun(); - org.openxmlformats.schemas.wordprocessingml.x2006.main.CTSym symbol = - run.getCTR().addNewSym(); - symbol.setFont("Wingdings"); - symbol.setChar(new byte[] {(byte) 0xf0, (byte) 0xfc}); - - assertEquals("\u2713", PoiDocxRenderer.runText(run)); - } - } - - @Test - void readsAnchoredCheckboxGeometryWithoutVmlFallbackDuplication() throws Exception { - String xml = "" - + "" - + "3314065" - + "208915" - + "" - + "" - + "" - + ""; - try (XWPFDocument document = new XWPFDocument()) { - XWPFParagraph paragraph = new XWPFParagraph(CTP.Factory.parse(xml), document); - - List checkboxes = - PoiDocxRenderer.floatingCheckboxes(paragraph); - - assertEquals(1, checkboxes.size()); - assertEquals(260.95f, checkboxes.get(0).offsetX(), 0.01f); - assertEquals(16.45f, checkboxes.get(0).offsetY(), 0.01f); - assertEquals(true, checkboxes.get(0).checked()); - } - } - - @Test - void preservesTabsAndAdvancesToDefaultWordTabStops() throws Exception { - try (XWPFDocument document = new XWPFDocument()) { - XWPFParagraph paragraph = document.createParagraph(); - paragraph.createRun().addTab(); - paragraph.createRun().addTab(); - - assertEquals("\t\t", PoiDocxRenderer.paragraphText(paragraph)); - assertEquals(36.0f, PoiDocxRenderer.nextDefaultTabStop(20.0f)); - assertEquals(72.0f, PoiDocxRenderer.nextDefaultTabStop(36.0f)); - } - } - - @Test - void centersTextWithinAsymmetricallyIndentedLineBox() { - assertEquals(250.0f, PoiDocxRenderer.centeredTextX(500.0f, 0.0f, -100.0f, 100.0f)); - assertEquals(200.0f, PoiDocxRenderer.centeredTextX(500.0f, 0.0f, 0.0f, 100.0f)); - } - - @Test - void preservesNegativeParagraphIndentsButNormalizesUnsetValue() { - assertEquals(-52.6f, PoiDocxRenderer.indentationToPoints(-1052)); - assertEquals(0.0f, PoiDocxRenderer.indentationToPoints(-1)); - } - - @Test - void reservesOneCellInsetFromWrappingWidth() { - assertEquals(78.4f, PoiDocxRenderer.cellContentWidth(83.8f, 5.4f)); - } - - @Test - void wrapsLatinTextAtHyphensAndSpacesBeforeSplittingCharacters() throws Exception { - PDFont font = new PDType1Font(Standard14Fonts.FontName.HELVETICA); - float fontSize = 10.5f; - float width = font.getStringWidth("88888888
") / 1000.0f * fontSize + 0.1f; - - assertEquals( - Arrays.asList("020-", "88888888
", "13888888888"), - PoiDocxRenderer.wrap(font, "020-88888888
13888888888", fontSize, width)); - } - - @Test - void countsEastAsianLatinAndDigitBoundaries() { - assertEquals(9, PoiDocxRenderer.eastAsianBoundaryCount("2025年11月26日14时40分")); - assertEquals(2, PoiDocxRenderer.eastAsianBoundaryCount("使用PECVD设备")); - assertEquals(0, PoiDocxRenderer.eastAsianBoundaryCount("纯中文")); - assertEquals(0, PoiDocxRenderer.eastAsianBoundaryCount("ASCII only")); - } - - @Test - void wrapsEastAsianParagraphsWithDocumentEastAsianFont() { - PDFont fallback = new PDType1Font(Standard14Fonts.FontName.HELVETICA); - PDFont simSun = new PDType1Font(Standard14Fonts.FontName.COURIER); - PoiDocxRenderer.ParagraphFonts fonts = new PoiDocxRenderer.ParagraphFonts( - fallback, - simSun, - fallback, - fallback, - fallback, - fallback, - fallback, - "Times New Roman", - "SimSun"); - - assertSame(simSun, PoiDocxRenderer.wrappingFont(fonts, "使用PECVD设备")); - assertSame(fallback, PoiDocxRenderer.wrappingFont(fonts, "ASCII only")); - } - - @Test - void resolvesFontAndBoldFromHomogeneousCellRuns() throws Exception { - PDFont fallback = new PDType1Font(Standard14Fonts.FontName.HELVETICA); - PDFont simHei = new PDType1Font(Standard14Fonts.FontName.COURIER); - PDFont times = new PDType1Font(Standard14Fonts.FontName.TIMES_ROMAN); - PoiDocxRenderer.ParagraphFonts fonts = new PoiDocxRenderer.ParagraphFonts( - fallback, - fallback, - simHei, - fallback, - fallback, - times, - fallback, - "Times New Roman", - "SimSun"); - try (XWPFDocument document = new XWPFDocument()) { - XWPFTableCell cell = document.createTable(1, 1).getRow(0).getCell(0); - XWPFRun run = cell.getParagraphs().get(0).createRun(); - run.setFontFamily("SimHei", org.apache.poi.xwpf.usermodel.XWPFRun.FontCharRange.eastAsia); - run.setText("中"); - - assertSame(simHei, PoiDocxRenderer.resolvedCellFont(cell, fonts, fallback)); - - run.setBold(true); - assertSame(fallback, PoiDocxRenderer.resolvedCellFont(cell, fonts, fallback)); - } - } - - @Test - void splitsInheritedMixedScriptRunByDocumentFontSlots() throws Exception { - PDFont fallback = new PDType1Font(Standard14Fonts.FontName.HELVETICA); - PDFont simSun = new PDType1Font(Standard14Fonts.FontName.COURIER); - PDFont times = new PDType1Font(Standard14Fonts.FontName.TIMES_ROMAN); - PoiDocxRenderer.ParagraphFonts fonts = new PoiDocxRenderer.ParagraphFonts( - fallback, - simSun, - fallback, - fallback, - fallback, - times, - fallback, - "Times New Roman", - "SimSun"); - try (XWPFDocument document = new XWPFDocument()) { - XWPFParagraph paragraph = document.createParagraph(); - paragraph.createRun().setText("A中B"); - - List segments = - PoiDocxRenderer.paragraphSegments(paragraph, fonts, 10.0f); - - assertEquals(Arrays.asList("A", "中", "B"), segments.stream() - .map(PoiDocxRenderer.RunSegment::text) - .collect(Collectors.toList())); - assertSame(times, segments.get(0).font()); - assertSame(simSun, segments.get(1).font()); - assertSame(times, segments.get(2).font()); - assertEquals(0.0f, segments.get(0).leadingSpacing()); - assertEquals(2.5f, segments.get(1).leadingSpacing()); - assertEquals(2.5f, segments.get(2).leadingSpacing()); - } - } - - @Test - void preservesBoldFontInParagraphSegments() throws Exception { - PDFont regular = new PDType1Font(Standard14Fonts.FontName.TIMES_ROMAN); - PDFont bold = new PDType1Font(Standard14Fonts.FontName.TIMES_BOLD); - PoiDocxRenderer.ParagraphFonts fonts = new PoiDocxRenderer.ParagraphFonts( - regular, - regular, - regular, - regular, - regular, - regular, - regular, - "Times New Roman", - "Times New Roman"); - try (XWPFDocument document = new XWPFDocument()) { - XWPFParagraph paragraph = document.createParagraph(); - XWPFRun run = paragraph.createRun(); - run.setBold(true); - run.setText("Heading"); - - List segments = - PoiDocxRenderer.paragraphSegments(paragraph, fonts, 12.0f, bold); - - assertSame(bold, segments.get(0).font()); - } - } - - @Test - void distributesJustifiedLineWidthAcrossSpaces() { - assertEquals(10.0f, PoiDocxRenderer.justifiedWordSpacing("one two three", 80.0f, 100.0f)); - assertEquals(0.0f, PoiDocxRenderer.justifiedWordSpacing("word", 80.0f, 100.0f)); - assertEquals(0.0f, PoiDocxRenderer.justifiedWordSpacing("one two", 110.0f, 100.0f)); - } - - @Test - void honorsExplicitAutoLineSpacingForLatinParagraphs() throws Exception { - try (XWPFDocument document = new XWPFDocument()) { - XWPFParagraph paragraph = document.createParagraph(); - paragraph.setSpacingBetween(1.15, LineSpacingRule.AUTO); - - assertEquals( - 15.8838f, - PoiDocxRenderer.paragraphLineHeight(paragraph, 12.0f, 14.4f, 18.0f, true), - 0.001f); - assertEquals( - 18.0f, - PoiDocxRenderer.paragraphLineHeight(paragraph, 12.0f, 14.4f, 18.0f, false), - 0.001f); - } - } - - @Test - void normalizesVietnameseCombiningMarksBeforeLayout() { - assertEquals( - "M\u1ee5c \u0111\u00edch", - PoiDocxRenderer.renderableText("Mu\u0323c \u0111i\u0301ch")); - } - - @Test - void positionsPageNumberAboveFooterBoundaryUsingFontMetrics() { - assertEquals(53.7719f, PoiDocxRenderer.pageNumberBaseline(36.0f, 13.0f, -216.0f), 0.001f); - } - - @Test - void suppressesMixedScriptSpacingWhenParagraphDisablesIt() throws Exception { - PDFont fallback = new PDType1Font(Standard14Fonts.FontName.HELVETICA); - PDFont simSun = new PDType1Font(Standard14Fonts.FontName.COURIER); - PoiDocxRenderer.ParagraphFonts fonts = new PoiDocxRenderer.ParagraphFonts( - fallback, - simSun, - fallback, - fallback, - fallback, - fallback, - fallback, - "Times New Roman", - "SimSun"); - try (XWPFDocument document = new XWPFDocument()) { - XWPFParagraph paragraph = document.createParagraph(); - CTPPr properties = paragraph.getCTP().addNewPPr(); - properties.addNewAutoSpaceDE().setVal(false); - properties.addNewAutoSpaceDN().setVal(false); - paragraph.createRun().setText("A中1"); - - List segments = - PoiDocxRenderer.paragraphSegments(paragraph, fonts, 10.0f); - - assertEquals(Arrays.asList(0.0f, 0.0f, 0.0f), segments.stream() - .map(PoiDocxRenderer.RunSegment::leadingSpacing) - .collect(Collectors.toList())); - } - } -} \ No newline at end of file diff --git a/minipdf-java/minipdf-tests/src/test/java/io/github/minisoftware/minipdf/internal/xlsx/PoiXlsxRendererTest.java b/minipdf-java/minipdf-tests/src/test/java/io/github/minisoftware/minipdf/internal/xlsx/PoiXlsxRendererTest.java deleted file mode 100644 index 0eae9785..00000000 --- a/minipdf-java/minipdf-tests/src/test/java/io/github/minisoftware/minipdf/internal/xlsx/PoiXlsxRendererTest.java +++ /dev/null @@ -1,171 +0,0 @@ -package io.github.minisoftware.minipdf.internal.xlsx; - -import io.github.minisoftware.minipdf.MiniPdf; -import org.apache.pdfbox.Loader; -import org.apache.pdfbox.contentstream.operator.Operator; -import org.apache.pdfbox.cos.COSArray; -import org.apache.pdfbox.cos.COSNumber; -import org.apache.pdfbox.pdfparser.PDFStreamParser; -import org.apache.pdfbox.pdmodel.PDDocument; -import org.apache.pdfbox.text.PDFTextStripper; -import org.apache.poi.ss.usermodel.BorderStyle; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.CellStyle; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.xssf.usermodel.XSSFClientAnchor; -import org.apache.poi.xssf.usermodel.XSSFDrawing; -import org.apache.poi.xssf.usermodel.XSSFSheet; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.Assumptions; -import org.junit.jupiter.api.Test; -import org.openxmlformats.schemas.drawingml.x2006.main.CTShapeProperties; -import org.openxmlformats.schemas.drawingml.x2006.main.STShapeType; - -import java.io.ByteArrayOutputStream; -import java.util.List; - -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertTrue; - -class PoiXlsxRendererTest { - - @AfterEach - void clearRegisteredFonts() { - MiniPdf.clearRegisteredFonts(); - } - - @Test - void rendersBallotBoxWithoutQuestionMarkFallback() throws Exception { - Assumptions.assumeTrue(System.getenv("WINDIR") != null, "requires Windows system fonts"); - try (XSSFWorkbook workbook = new XSSFWorkbook(); ByteArrayOutputStream output = new ByteArrayOutputStream()) { - XSSFSheet sheet = workbook.createSheet("Sheet1"); - Row row = sheet.createRow(0); - Cell cell = row.createCell(0); - cell.setCellValue("\u2610"); - workbook.write(output); - byte[] pdf = MiniPdf.convertBytesToPdf(output.toByteArray()); - try (PDDocument document = Loader.loadPDF(pdf)) { - String text = new PDFTextStripper().getText(document); - assertTrue(text.contains("\u2610"), "expected ballot box, got: " + text); - assertFalse(text.contains("?"), "unexpected glyph fallback: " + text); - } - } - } - - @Test - void rendersStandaloneRectangleShapeWithFill() throws Exception { - try (XSSFWorkbook workbook = new XSSFWorkbook(); ByteArrayOutputStream output = new ByteArrayOutputStream()) { - XSSFSheet sheet = workbook.createSheet("Sheet1"); - sheet.createRow(0).createCell(0).setCellValue("Cell"); - XSSFDrawing drawing = sheet.createDrawingPatriarch(); - XSSFClientAnchor anchor = new XSSFClientAnchor(0, 0, 0, 0, 0, 0, 1, 1); - CTShapeProperties properties = drawing.createSimpleShape(anchor).getCTShape().getSpPr(); - if (!properties.isSetPrstGeom()) { - properties.addNewPrstGeom(); - } - properties.getPrstGeom().setPrst(STShapeType.RECT); - properties.addNewSolidFill().addNewSrgbClr().setVal(new byte[]{(byte) 255, (byte) 153, (byte) 153}); - workbook.write(output); - byte[] pdf = MiniPdf.convertBytesToPdf(output.toByteArray()); - try (PDDocument document = Loader.loadPDF(pdf)) { - assertTrue(containsFillRect(document, 1.0f, 153.0f / 255.0f, 153.0f / 255.0f), - "expected a filled rectangle with the shape fill color"); - } - } - } - - @Test - void wrapsAtWordBoundariesWhenWhitespaceIsNearTheLineEnd() throws Exception { - try (XSSFWorkbook workbook = new XSSFWorkbook(); ByteArrayOutputStream output = new ByteArrayOutputStream()) { - XSSFSheet sheet = workbook.createSheet("Sheet1"); - sheet.setColumnWidth(0, 9 * 256); - Row row = sheet.createRow(0); - row.setHeightInPoints(36.0f); - Cell cell = row.createCell(0); - cell.setCellValue("one two three four"); - CellStyle style = workbook.createCellStyle(); - style.setWrapText(true); - cell.setCellStyle(style); - workbook.write(output); - - byte[] pdf = MiniPdf.convertBytesToPdf(output.toByteArray()); - try (PDDocument document = Loader.loadPDF(pdf)) { - String text = new PDFTextStripper().getText(document); - String normalized = text.replace("\r\n", "\n").replace('\r', '\n'); - assertTrue(normalized.contains("one two\nthree four"), "expected whole-word wrapping, got: " + text); - } - } - } - - @Test - void rendersDottedCellBorderWithPdfDashPattern() throws Exception { - try (XSSFWorkbook workbook = new XSSFWorkbook(); ByteArrayOutputStream output = new ByteArrayOutputStream()) { - XSSFSheet sheet = workbook.createSheet("Sheet1"); - Cell cell = sheet.createRow(0).createCell(0); - cell.setCellValue("Cell"); - CellStyle style = workbook.createCellStyle(); - style.setBorderBottom(BorderStyle.DOTTED); - cell.setCellStyle(style); - workbook.write(output); - - byte[] pdf = MiniPdf.convertBytesToPdf(output.toByteArray()); - try (PDDocument document = Loader.loadPDF(pdf)) { - assertTrue(containsDashPattern(document, 0.2f, 0.8f), "expected the dotted PDF dash pattern"); - } - } - } - - private static boolean containsFillRect(PDDocument document, float red, float green, float blue) - throws Exception { - PDFStreamParser parser = new PDFStreamParser(document.getPage(0)); - List tokens = parser.parse(); - for (int index = 0; index + 4 < tokens.size(); index++) { - if (tokens.get(index) instanceof COSNumber - && tokens.get(index + 1) instanceof COSNumber - && tokens.get(index + 2) instanceof COSNumber - && near(((COSNumber) tokens.get(index)).floatValue(), red) - && near(((COSNumber) tokens.get(index + 1)).floatValue(), green) - && near(((COSNumber) tokens.get(index + 2)).floatValue(), blue) - && tokens.get(index + 3) instanceof Operator - && ("rg".equals(((Operator) tokens.get(index + 3)).getName()) - || "sc".equals(((Operator) tokens.get(index + 3)).getName()))) { - for (int cursor = index + 4; cursor + 1 < tokens.size(); cursor++) { - if (tokens.get(cursor) instanceof Operator - && "re".equals(((Operator) tokens.get(cursor)).getName()) - && tokens.get(cursor + 1) instanceof Operator - && "f".equals(((Operator) tokens.get(cursor + 1)).getName())) { - return true; - } - } - } - } - return false; - } - - private static boolean containsDashPattern(PDDocument document, float dash, float gap) throws Exception { - PDFStreamParser parser = new PDFStreamParser(document.getPage(0)); - List tokens = parser.parse(); - for (int index = 0; index + 2 < tokens.size(); index++) { - if (!(tokens.get(index) instanceof COSArray) - || !(tokens.get(index + 1) instanceof COSNumber) - || !(tokens.get(index + 2) instanceof Operator) - || !"d".equals(((Operator) tokens.get(index + 2)).getName())) { - continue; - } - COSArray pattern = (COSArray) tokens.get(index); - if (pattern.size() == 2 - && pattern.getObject(0) instanceof COSNumber - && pattern.getObject(1) instanceof COSNumber - && near(((COSNumber) pattern.getObject(0)).floatValue(), dash) - && near(((COSNumber) pattern.getObject(1)).floatValue(), gap)) { - return true; - } - } - return false; - } - - private static boolean near(float actual, float expected) { - return Math.abs(actual - expected) < 0.01f; - } -} diff --git a/minipdf-java/minipdf/pom.xml b/minipdf-java/minipdf/pom.xml deleted file mode 100644 index a765f0ae..00000000 --- a/minipdf-java/minipdf/pom.xml +++ /dev/null @@ -1,34 +0,0 @@ - - - 4.0.0 - - - io.github.mini-software - minipdf-java-parent - 0.4.1 - - - minipdf - MiniPdf Java Library - - - - org.apache.pdfbox - pdfbox - - - de.rototor.pdfbox - graphics2d - - - org.apache.poi - poi-ooxml - - - org.apache.poi - poi-scratchpad - - - \ No newline at end of file diff --git a/minipdf-java/minipdf/src/main/java/io/github/minisoftware/minipdf/ConversionOptions.java b/minipdf-java/minipdf/src/main/java/io/github/minisoftware/minipdf/ConversionOptions.java deleted file mode 100644 index 2c029fd5..00000000 --- a/minipdf-java/minipdf/src/main/java/io/github/minisoftware/minipdf/ConversionOptions.java +++ /dev/null @@ -1,25 +0,0 @@ -package io.github.minisoftware.minipdf; - -import java.util.Optional; - -public final class ConversionOptions { - private static final ConversionOptions DEFAULTS = new ConversionOptions(null); - - private final PageSize pageSize; - - private ConversionOptions(PageSize pageSize) { - this.pageSize = pageSize; - } - - public static ConversionOptions defaults() { - return DEFAULTS; - } - - public static ConversionOptions withPageSize(PageSize pageSize) { - return new ConversionOptions(java.util.Objects.requireNonNull(pageSize, "pageSize")); - } - - public Optional pageSize() { - return Optional.ofNullable(pageSize); - } -} \ No newline at end of file diff --git a/minipdf-java/minipdf/src/main/java/io/github/minisoftware/minipdf/MiniPdf.java b/minipdf-java/minipdf/src/main/java/io/github/minisoftware/minipdf/MiniPdf.java deleted file mode 100644 index 045ef97a..00000000 --- a/minipdf-java/minipdf/src/main/java/io/github/minisoftware/minipdf/MiniPdf.java +++ /dev/null @@ -1,98 +0,0 @@ -package io.github.minisoftware.minipdf; - -import io.github.minisoftware.minipdf.internal.OfficePackageDetector; -import io.github.minisoftware.minipdf.internal.docx.DocxConverter; -import io.github.minisoftware.minipdf.internal.pptx.PptxConverter; -import io.github.minisoftware.minipdf.internal.xlsx.XlsxConverter; - -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Path; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.Objects; -import java.util.concurrent.CopyOnWriteArrayList; - -public final class MiniPdf { - private static final CopyOnWriteArrayList REGISTERED_FONTS = new CopyOnWriteArrayList<>(); - - private MiniPdf() { - } - - public static void registerFont(String name, byte[] fontData) { - if (name == null || name.trim().isEmpty()) { - throw new IllegalArgumentException("font name must not be blank"); - } - REGISTERED_FONTS.add(new RegisteredFont(name, fontData)); - } - - public static List registeredFonts() { - return Collections.unmodifiableList(new ArrayList<>(REGISTERED_FONTS)); - } - - public static void clearRegisteredFonts() { - REGISTERED_FONTS.clear(); - } - - public static OfficeFormat detectOfficeFormat(byte[] input) throws MiniPdfException { - return OfficePackageDetector.detect(Objects.requireNonNull(input, "input")); - } - - public static byte[] convertToPdfBytes(Path inputPath) throws MiniPdfException { - return convertToPdfBytes(inputPath, ConversionOptions.defaults()); - } - - public static byte[] convertToPdfBytes(Path inputPath, ConversionOptions options) throws MiniPdfException { - Objects.requireNonNull(inputPath, "inputPath"); - Objects.requireNonNull(options, "options"); - try { - return convertBytesToPdf(Files.readAllBytes(inputPath), options); - } catch (IOException exception) { - throw new MiniPdfException( - MiniPdfException.Kind.IO, - "I/O error: " + exception.getMessage(), - exception); - } - } - - public static byte[] convertBytesToPdf(byte[] input) throws MiniPdfException { - return convertBytesToPdf(input, ConversionOptions.defaults()); - } - - public static byte[] convertBytesToPdf(byte[] input, ConversionOptions options) throws MiniPdfException { - Objects.requireNonNull(options, "options"); - OfficeFormat format = detectOfficeFormat(input); - switch (format) { - case DOCX: - return DocxConverter.convert(input, options); - case XLSX: - return XlsxConverter.convert(input, options); - case PPTX: - return PptxConverter.convert(input, options); - case UNKNOWN: - default: - throw new MiniPdfException( - MiniPdfException.Kind.UNSUPPORTED_FORMAT, - "unsupported or unknown Office document format"); - } - } - - public static void convertToPdf(Path inputPath, Path outputPath) throws MiniPdfException { - convertToPdf(inputPath, outputPath, ConversionOptions.defaults()); - } - - public static void convertToPdf(Path inputPath, Path outputPath, ConversionOptions options) - throws MiniPdfException { - Objects.requireNonNull(outputPath, "outputPath"); - byte[] pdf = convertToPdfBytes(inputPath, options); - try { - Files.write(outputPath, pdf); - } catch (IOException exception) { - throw new MiniPdfException( - MiniPdfException.Kind.IO, - "I/O error: " + exception.getMessage(), - exception); - } - } -} \ No newline at end of file diff --git a/minipdf-java/minipdf/src/main/java/io/github/minisoftware/minipdf/MiniPdfException.java b/minipdf-java/minipdf/src/main/java/io/github/minisoftware/minipdf/MiniPdfException.java deleted file mode 100644 index 20a04a98..00000000 --- a/minipdf-java/minipdf/src/main/java/io/github/minisoftware/minipdf/MiniPdfException.java +++ /dev/null @@ -1,29 +0,0 @@ -package io.github.minisoftware.minipdf; - -import java.util.Objects; - -public final class MiniPdfException extends Exception { - public enum Kind { - IO, - ZIP_PACKAGE, - XML_PARSE, - UNSUPPORTED_FORMAT, - INVALID_INPUT - } - - private final Kind kind; - - public MiniPdfException(Kind kind, String message) { - super(message); - this.kind = Objects.requireNonNull(kind, "kind"); - } - - public MiniPdfException(Kind kind, String message, Throwable cause) { - super(message, cause); - this.kind = Objects.requireNonNull(kind, "kind"); - } - - public Kind kind() { - return kind; - } -} \ No newline at end of file diff --git a/minipdf-java/minipdf/src/main/java/io/github/minisoftware/minipdf/OfficeFormat.java b/minipdf-java/minipdf/src/main/java/io/github/minisoftware/minipdf/OfficeFormat.java deleted file mode 100644 index 11d96431..00000000 --- a/minipdf-java/minipdf/src/main/java/io/github/minisoftware/minipdf/OfficeFormat.java +++ /dev/null @@ -1,8 +0,0 @@ -package io.github.minisoftware.minipdf; - -public enum OfficeFormat { - UNKNOWN, - XLSX, - DOCX, - PPTX -} \ No newline at end of file diff --git a/minipdf-java/minipdf/src/main/java/io/github/minisoftware/minipdf/PageSize.java b/minipdf-java/minipdf/src/main/java/io/github/minisoftware/minipdf/PageSize.java deleted file mode 100644 index 47535d77..00000000 --- a/minipdf-java/minipdf/src/main/java/io/github/minisoftware/minipdf/PageSize.java +++ /dev/null @@ -1,55 +0,0 @@ -package io.github.minisoftware.minipdf; - -import java.util.Objects; - -public final class PageSize { - public static final PageSize A4 = new PageSize(595.28f, 841.89f); - public static final PageSize LETTER = new PageSize(612.0f, 792.0f); - - private final float width; - private final float height; - - private PageSize(float width, float height) { - this.width = width; - this.height = height; - } - - public static PageSize of(float width, float height) throws MiniPdfException { - if (!Float.isFinite(width) || !Float.isFinite(height) || width <= 0.0f || height <= 0.0f) { - throw new MiniPdfException( - MiniPdfException.Kind.INVALID_INPUT, - "page width and height must be positive finite values"); - } - return new PageSize(width, height); - } - - public float width() { - return width; - } - - public float height() { - return height; - } - - @Override - public boolean equals(Object value) { - if (this == value) { - return true; - } - if (!(value instanceof PageSize)) { - return false; - } - PageSize other = (PageSize) value; - return Float.compare(width, other.width) == 0 && Float.compare(height, other.height) == 0; - } - - @Override - public int hashCode() { - return Objects.hash(width, height); - } - - @Override - public String toString() { - return "PageSize[width=" + width + ", height=" + height + ']'; - } -} \ No newline at end of file diff --git a/minipdf-java/minipdf/src/main/java/io/github/minisoftware/minipdf/PdfColor.java b/minipdf-java/minipdf/src/main/java/io/github/minisoftware/minipdf/PdfColor.java deleted file mode 100644 index 095a3ff0..00000000 --- a/minipdf-java/minipdf/src/main/java/io/github/minisoftware/minipdf/PdfColor.java +++ /dev/null @@ -1,63 +0,0 @@ -package io.github.minisoftware.minipdf; - -import java.util.Objects; - -public final class PdfColor { - public static final PdfColor BLACK = new PdfColor(0.0f, 0.0f, 0.0f); - public static final PdfColor WHITE = new PdfColor(1.0f, 1.0f, 1.0f); - - private final float red; - private final float green; - private final float blue; - - public PdfColor(float red, float green, float blue) { - validate(red, "red"); - validate(green, "green"); - validate(blue, "blue"); - this.red = red; - this.green = green; - this.blue = blue; - } - - public float red() { - return red; - } - - public float green() { - return green; - } - - public float blue() { - return blue; - } - - private static void validate(float component, String name) { - if (!Float.isFinite(component) || component < 0.0f || component > 1.0f) { - throw new IllegalArgumentException(name + " must be a finite value from 0 to 1"); - } - } - - @Override - public boolean equals(Object value) { - if (this == value) { - return true; - } - if (!(value instanceof PdfColor)) { - return false; - } - PdfColor other = (PdfColor) value; - return Float.compare(red, other.red) == 0 - && Float.compare(green, other.green) == 0 - && Float.compare(blue, other.blue) == 0; - } - - @Override - public int hashCode() { - return Objects.hash(red, green, blue); - } - - @Override - public String toString() { - return "PdfColor[red=" + red + ", green=" + green + ", blue=" + blue + ']'; - } -} \ No newline at end of file diff --git a/minipdf-java/minipdf/src/main/java/io/github/minisoftware/minipdf/PdfDocument.java b/minipdf-java/minipdf/src/main/java/io/github/minisoftware/minipdf/PdfDocument.java deleted file mode 100644 index 45eb6909..00000000 --- a/minipdf-java/minipdf/src/main/java/io/github/minisoftware/minipdf/PdfDocument.java +++ /dev/null @@ -1,237 +0,0 @@ -package io.github.minisoftware.minipdf; - -import java.io.ByteArrayOutputStream; -import java.nio.charset.Charset; -import java.nio.charset.StandardCharsets; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.Locale; -import java.util.SortedSet; -import java.util.TreeSet; - -public final class PdfDocument { - private static final Charset PDF_TEXT_ENCODING = Charset.forName("windows-1252"); - - private final List pages = new ArrayList<>(); - - public PdfPage addPage(float width, float height) { - if (!Float.isFinite(width) || !Float.isFinite(height) || width <= 0.0f || height <= 0.0f) { - throw new IllegalArgumentException("page width and height must be positive finite values"); - } - PdfPage page = new PdfPage(width, height); - pages.add(page); - return page; - } - - public List pages() { - return Collections.unmodifiableList(new ArrayList<>(pages)); - } - - public byte[] toBytes() { - TrueTypeFontData embeddedFont = findEmbeddedFont(); - SortedSet unicodeCodePoints = unicodeCodePoints(embeddedFont); - int embeddedFontObjectCount = embeddedFont == null ? 0 : 6; - int firstPageObjectNumber = 5 + embeddedFontObjectCount; - int objectCount = 4 + embeddedFontObjectCount + pages.size() * 2; - List objects = new ArrayList<>(objectCount); - objects.add(ascii("<< /Type /Catalog /Pages 2 0 R >>")); - objects.add(ascii(pagesObject(firstPageObjectNumber))); - objects.add(ascii("<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>")); - objects.add(ascii("<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica-Bold /Encoding /WinAnsiEncoding >>")); - - if (embeddedFont != null) { - byte[] fontBytes = embeddedFont.data(); - objects.add(streamObject(embeddedFont.toUnicode(unicodeCodePoints))); - objects.add(ascii("<< /Type /FontDescriptor /FontName /" + embeddedFont.pdfName() - + " /Flags 32 /FontBBox [" + embeddedFont.boundingBox() + "]" - + " /ItalicAngle 0 /Ascent " + embeddedFont.ascent() - + " /Descent " + embeddedFont.descent() - + " /CapHeight " + embeddedFont.capHeight() - + " /StemV 80 /FontFile2 9 0 R >>")); - objects.add(ascii("<< /Type /Font /Subtype /CIDFontType2 /BaseFont /" + embeddedFont.pdfName() - + " /CIDSystemInfo << /Registry (Adobe) /Ordering (Identity) /Supplement 0 >>" - + " /FontDescriptor 6 0 R /W " + embeddedFont.widths(unicodeCodePoints) - + " /CIDToGIDMap 10 0 R >>")); - objects.add(ascii("<< /Type /Font /Subtype /Type0 /BaseFont /" + embeddedFont.pdfName() - + " /Encoding /Identity-H /DescendantFonts [7 0 R] /ToUnicode 5 0 R >>")); - objects.add(streamObject(fontBytes, "/Length1 " + fontBytes.length)); - objects.add(streamObject(embeddedFont.cidToGidMap(unicodeCodePoints))); - } - - for (int index = 0; index < pages.size(); index++) { - PdfPage page = pages.get(index); - int contentObjectNumber = firstPageObjectNumber + index * 2 + 1; - objects.add(ascii(pageObject(page, contentObjectNumber, embeddedFont != null))); - objects.add(streamObject(pageContent(page, embeddedFont))); - } - - ByteArrayOutputStream output = new ByteArrayOutputStream(); - write(output, "%PDF-1.4\n"); - write(output, new byte[]{'%', (byte) 0xE2, (byte) 0xE3, (byte) 0xCF, (byte) 0xD3, '\n'}); - - List offsets = new ArrayList<>(objectCount); - for (int index = 0; index < objects.size(); index++) { - offsets.add(output.size()); - write(output, (index + 1) + " 0 obj\n"); - write(output, objects.get(index)); - write(output, "\nendobj\n"); - } - - int xrefOffset = output.size(); - write(output, "xref\n0 " + (objectCount + 1) + "\n"); - write(output, "0000000000 65535 f \n"); - for (int offset : offsets) { - write(output, String.format(Locale.ROOT, "%010d 00000 n \n", offset)); - } - write(output, "trailer\n<< /Size " + (objectCount + 1) + " /Root 1 0 R >>\n"); - write(output, "startxref\n" + xrefOffset + "\n%%EOF\n"); - return output.toByteArray(); - } - - private String pagesObject(int firstPageObjectNumber) { - StringBuilder kids = new StringBuilder(); - for (int index = 0; index < pages.size(); index++) { - kids.append(firstPageObjectNumber + index * 2).append(" 0 R "); - } - return "<< /Type /Pages /Kids [ " + kids + "] /Count " + pages.size() + " >>"; - } - - private static String pageObject(PdfPage page, int contentObjectNumber, boolean hasEmbeddedFont) { - return "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 " - + number(page.width()) + ' ' + number(page.height()) - + "] /Resources << /Font << /F1 3 0 R /F2 4 0 R" - + (hasEmbeddedFont ? " /F3 8 0 R" : "") - + " >> >> /Contents " - + contentObjectNumber + " 0 R >>"; - } - - private static byte[] pageContent(PdfPage page, TrueTypeFontData embeddedFont) { - ByteArrayOutputStream content = new ByteArrayOutputStream(); - for (PdfPage.TextOperation operation : page.operations()) { - boolean useEmbeddedFont = embeddedFont != null - && requiresUnicode(operation.text()) - && embeddedFont.supports(codePoints(operation.text())); - write(content, "BT\n"); - write(content, useEmbeddedFont - ? "/F3 " + number(operation.size()) + " Tf\n" - : (operation.bold() ? "/F2 " : "/F1 ") + number(operation.size()) + " Tf\n"); - write(content, number(operation.color().red()) + ' ' - + number(operation.color().green()) + ' ' - + number(operation.color().blue()) + " rg\n"); - write(content, "1 0 0 1 " + number(operation.x()) + ' ' + number(operation.y()) + " Tm\n"); - if (useEmbeddedFont) { - write(content, '<' + unicodeHex(operation.text()) + "> Tj\nET\n"); - } else { - write(content, "("); - write(content, escapeText(operation.text())); - write(content, ") Tj\nET\n"); - } - } - return content.toByteArray(); - } - - private SortedSet unicodeCodePoints(TrueTypeFontData font) { - SortedSet codePoints = new TreeSet<>(); - if (font == null) { - return codePoints; - } - for (PdfPage page : pages) { - for (PdfPage.TextOperation operation : page.operations()) { - if (requiresUnicode(operation.text()) && font.supports(codePoints(operation.text()))) { - operation.text().codePoints().forEach(codePoints::add); - } - } - } - return codePoints; - } - - private TrueTypeFontData findEmbeddedFont() { - for (RegisteredFont registeredFont : MiniPdf.registeredFonts()) { - try { - TrueTypeFontData font = TrueTypeFontData.parse(registeredFont.name(), registeredFont.data()); - for (PdfPage page : pages) { - for (PdfPage.TextOperation operation : page.operations()) { - if (requiresUnicode(operation.text()) && font.supports(codePoints(operation.text()))) { - return font; - } - } - } - } catch (IllegalArgumentException ignored) { - // Try the next registered font. - } - } - return null; - } - - private static SortedSet codePoints(String text) { - SortedSet codePoints = new TreeSet<>(); - text.codePoints().forEach(codePoints::add); - return codePoints; - } - - private static boolean requiresUnicode(String text) { - return text.codePoints().anyMatch(codePoint -> codePoint > 255); - } - - private static String unicodeHex(String text) { - StringBuilder result = new StringBuilder(text.length() * 4); - for (int index = 0; index < text.length(); index++) { - result.append(String.format(Locale.ROOT, "%04X", (int) text.charAt(index))); - } - return result.toString(); - } - - private static byte[] escapeText(String text) { - byte[] encoded = text.getBytes(PDF_TEXT_ENCODING); - ByteArrayOutputStream escaped = new ByteArrayOutputStream(encoded.length); - for (byte value : encoded) { - int unsigned = Byte.toUnsignedInt(value); - if (unsigned == '(' || unsigned == ')' || unsigned == '\\') { - escaped.write('\\'); - escaped.write(unsigned); - } else if (unsigned == '\r') { - write(escaped, ascii("\\r")); - } else if (unsigned == '\n') { - write(escaped, ascii("\\n")); - } else { - escaped.write(unsigned); - } - } - return escaped.toByteArray(); - } - - private static byte[] streamObject(byte[] stream) { - return streamObject(stream, ""); - } - - private static byte[] streamObject(byte[] stream, String additionalEntries) { - ByteArrayOutputStream object = new ByteArrayOutputStream(); - write(object, "<< /Length " + stream.length - + (additionalEntries.isEmpty() ? "" : " " + additionalEntries) - + " >>\nstream\n"); - write(object, stream); - write(object, "\nendstream"); - return object.toByteArray(); - } - - private static String number(float value) { - if (value == Math.rint(value)) { - return Long.toString((long) value); - } - String text = String.format(Locale.ROOT, "%.4f", value); - return text.replaceFirst("0+$", "").replaceFirst("\\.$", ""); - } - - private static byte[] ascii(String value) { - return value.getBytes(StandardCharsets.ISO_8859_1); - } - - private static void write(ByteArrayOutputStream output, String value) { - write(output, ascii(value)); - } - - private static void write(ByteArrayOutputStream output, byte[] value) { - output.write(value, 0, value.length); - } -} \ No newline at end of file diff --git a/minipdf-java/minipdf/src/main/java/io/github/minisoftware/minipdf/PdfPage.java b/minipdf-java/minipdf/src/main/java/io/github/minisoftware/minipdf/PdfPage.java deleted file mode 100644 index 4635117b..00000000 --- a/minipdf-java/minipdf/src/main/java/io/github/minisoftware/minipdf/PdfPage.java +++ /dev/null @@ -1,83 +0,0 @@ -package io.github.minisoftware.minipdf; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.Objects; - -public final class PdfPage { - private final float width; - private final float height; - private final List operations = new ArrayList<>(); - - PdfPage(float width, float height) { - this.width = width; - this.height = height; - } - - public float width() { - return width; - } - - public float height() { - return height; - } - - public void addText(String text, float x, float y, float size, PdfColor color, boolean bold) { - Objects.requireNonNull(text, "text"); - Objects.requireNonNull(color, "color"); - if (!Float.isFinite(x) || !Float.isFinite(y)) { - throw new IllegalArgumentException("text coordinates must be finite"); - } - if (!Float.isFinite(size) || size <= 0.0f) { - throw new IllegalArgumentException("text size must be a positive finite value"); - } - operations.add(new TextOperation(text, x, y, size, color, bold)); - } - - List operations() { - return Collections.unmodifiableList(new ArrayList<>(operations)); - } - - static final class TextOperation { - private final String text; - private final float x; - private final float y; - private final float size; - private final PdfColor color; - private final boolean bold; - - TextOperation(String text, float x, float y, float size, PdfColor color, boolean bold) { - this.text = text; - this.x = x; - this.y = y; - this.size = size; - this.color = color; - this.bold = bold; - } - - String text() { - return text; - } - - float x() { - return x; - } - - float y() { - return y; - } - - float size() { - return size; - } - - PdfColor color() { - return color; - } - - boolean bold() { - return bold; - } - } -} \ No newline at end of file diff --git a/minipdf-java/minipdf/src/main/java/io/github/minisoftware/minipdf/RegisteredFont.java b/minipdf-java/minipdf/src/main/java/io/github/minisoftware/minipdf/RegisteredFont.java deleted file mode 100644 index 86ea5865..00000000 --- a/minipdf-java/minipdf/src/main/java/io/github/minisoftware/minipdf/RegisteredFont.java +++ /dev/null @@ -1,39 +0,0 @@ -package io.github.minisoftware.minipdf; - -import java.util.Arrays; -import java.util.Objects; - -public final class RegisteredFont { - private final String name; - private final byte[] data; - - RegisteredFont(String name, byte[] data) { - this.name = Objects.requireNonNull(name, "name"); - this.data = Objects.requireNonNull(data, "data").clone(); - } - - public String name() { - return name; - } - - public byte[] data() { - return data.clone(); - } - - @Override - public boolean equals(Object value) { - if (this == value) { - return true; - } - if (!(value instanceof RegisteredFont)) { - return false; - } - RegisteredFont other = (RegisteredFont) value; - return name.equals(other.name) && Arrays.equals(data, other.data); - } - - @Override - public int hashCode() { - return 31 * name.hashCode() + Arrays.hashCode(data); - } -} \ No newline at end of file diff --git a/minipdf-java/minipdf/src/main/java/io/github/minisoftware/minipdf/TrueTypeFontData.java b/minipdf-java/minipdf/src/main/java/io/github/minisoftware/minipdf/TrueTypeFontData.java deleted file mode 100644 index 0a5886ae..00000000 --- a/minipdf-java/minipdf/src/main/java/io/github/minisoftware/minipdf/TrueTypeFontData.java +++ /dev/null @@ -1,518 +0,0 @@ -package io.github.minisoftware.minipdf; - -import java.nio.charset.StandardCharsets; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; - -final class TrueTypeFontData { - private final String pdfName; - private final byte[] data; - private final Map cmap; - private final int[] advances; - private final int unitsPerEm; - private final int ascent; - private final int descent; - private final int capHeight; - private final int[] boundingBox; - - private TrueTypeFontData( - String name, - byte[] data, - Map cmap, - int[] advances, - int unitsPerEm, - int ascent, - int descent, - int capHeight, - int[] boundingBox) { - this.pdfName = sanitizeName(name); - this.data = data.clone(); - this.cmap = cmap; - this.advances = advances; - this.unitsPerEm = unitsPerEm; - this.ascent = scale(ascent, unitsPerEm); - this.descent = scale(descent, unitsPerEm); - this.capHeight = scale(capHeight, unitsPerEm); - this.boundingBox = new int[]{ - scale(boundingBox[0], unitsPerEm), - scale(boundingBox[1], unitsPerEm), - scale(boundingBox[2], unitsPerEm), - scale(boundingBox[3], unitsPerEm) - }; - } - - static TrueTypeFontData parse(String name, byte[] data) { - if (isTrueTypeCollection(data)) { - data = extractFirstFont(data); - } - if (data.length < 12) { - throw new IllegalArgumentException("font is shorter than a TrueType header"); - } - Map tables = readTables(data); - Table os2 = tables.get("OS/2"); - if (os2 != null && os2.length >= 10) { - int embeddingFlags = readU16(data, os2.offset + 8); - if ((embeddingFlags & 0x0002) != 0 || (embeddingFlags & 0x0200) != 0) { - throw new IllegalArgumentException("font license does not permit editable outline embedding"); - } - } - - Table head = requiredTable(tables, "head"); - Table hhea = requiredTable(tables, "hhea"); - Table maxp = requiredTable(tables, "maxp"); - Table hmtx = requiredTable(tables, "hmtx"); - requireTableLength(head, 44); - requireTableLength(hhea, 36); - requireTableLength(maxp, 6); - - int unitsPerEm = readU16(data, head.offset + 18); - int numberOfMetrics = readU16(data, hhea.offset + 34); - int glyphCount = readU16(data, maxp.offset + 4); - if (unitsPerEm <= 0 || numberOfMetrics <= 0 || glyphCount <= 0 || numberOfMetrics > glyphCount) { - throw new IllegalArgumentException("font contains invalid horizontal metrics"); - } - requireTableLength(hmtx, numberOfMetrics * 4); - - Map cmap = readCmap(data, requiredTable(tables, "cmap")); - if (cmap.isEmpty()) { - throw new IllegalArgumentException("font does not contain a supported Unicode cmap"); - } - for (int glyph : cmap.values()) { - if (glyph <= 0 || glyph >= glyphCount) { - throw new IllegalArgumentException("font cmap references an invalid glyph"); - } - } - int[] advances = new int[glyphCount]; - int lastAdvance = 0; - for (int glyph = 0; glyph < numberOfMetrics; glyph++) { - lastAdvance = readU16(data, hmtx.offset + glyph * 4); - advances[glyph] = lastAdvance; - } - for (int glyph = numberOfMetrics; glyph < glyphCount; glyph++) { - advances[glyph] = lastAdvance; - } - - int[] box = new int[]{ - readS16(data, head.offset + 36), - readS16(data, head.offset + 38), - readS16(data, head.offset + 40), - readS16(data, head.offset + 42) - }; - int ascent = readS16(data, hhea.offset + 4); - int descent = readS16(data, hhea.offset + 6); - int capHeight = ascent; - if (os2 != null && os2.length >= 72) { - ascent = readS16(data, os2.offset + 68); - descent = readS16(data, os2.offset + 70); - if (os2.length >= 90) { - capHeight = readS16(data, os2.offset + 88); - } else { - capHeight = ascent; - } - } - return new TrueTypeFontData( - name, data, cmap, advances, unitsPerEm, ascent, descent, capHeight, box); - } - - private static boolean isTrueTypeCollection(byte[] data) { - return data.length >= 4 - && data[0] == 't' - && data[1] == 't' - && data[2] == 'c' - && data[3] == 'f'; - } - - private static byte[] extractFirstFont(byte[] collection) { - requireRange(collection, 0, 16); - long fontCount = readU32(collection, 8); - if (fontCount <= 0 || fontCount > 1024) { - throw new IllegalArgumentException("font collection contains an invalid face count"); - } - requireRange(collection, 12, (int) fontCount * 4); - long faceOffsetValue = readU32(collection, 12); - if (faceOffsetValue > Integer.MAX_VALUE) { - throw new IllegalArgumentException("font collection face offset is too large"); - } - int faceOffset = (int) faceOffsetValue; - requireRange(collection, faceOffset, 12); - int tableCount = readU16(collection, faceOffset + 4); - requireRange(collection, faceOffset + 12, tableCount * 16); - - List tables = new ArrayList<>(tableCount); - long outputLength = 12L + tableCount * 16L; - for (int index = 0; index < tableCount; index++) { - int record = faceOffset + 12 + index * 16; - long sourceOffsetValue = readU32(collection, record + 8); - long lengthValue = readU32(collection, record + 12); - if (sourceOffsetValue > Integer.MAX_VALUE || lengthValue > Integer.MAX_VALUE) { - throw new IllegalArgumentException("font collection table is too large"); - } - int sourceOffset = (int) sourceOffsetValue; - int length = (int) lengthValue; - requireRange(collection, sourceOffset, length); - outputLength = align4(outputLength); - if (outputLength > Integer.MAX_VALUE - length) { - throw new IllegalArgumentException("extracted font is too large"); - } - tables.add(new CollectionTable(record, sourceOffset, length, (int) outputLength)); - outputLength += length; - } - outputLength = align4(outputLength); - if (outputLength > Integer.MAX_VALUE) { - throw new IllegalArgumentException("extracted font is too large"); - } - - byte[] font = new byte[(int) outputLength]; - System.arraycopy(collection, faceOffset, font, 0, 12); - int headOffset = -1; - for (int index = 0; index < tables.size(); index++) { - CollectionTable table = tables.get(index); - int destinationRecord = 12 + index * 16; - System.arraycopy(collection, table.sourceRecord, font, destinationRecord, 8); - writeU32(font, destinationRecord + 8, table.destinationOffset); - writeU32(font, destinationRecord + 12, table.length); - System.arraycopy(collection, table.sourceOffset, font, table.destinationOffset, table.length); - if (font[destinationRecord] == 'h' - && font[destinationRecord + 1] == 'e' - && font[destinationRecord + 2] == 'a' - && font[destinationRecord + 3] == 'd') { - headOffset = table.destinationOffset; - } - } - if (headOffset >= 0) { - requireRange(font, headOffset, 12); - writeU32(font, headOffset + 8, 0); - writeU32(font, headOffset + 8, 0xB1B0AFBAL - checksum(font)); - } - return font; - } - - private static long align4(long value) { - return (value + 3L) & ~3L; - } - - private static long checksum(byte[] data) { - long sum = 0; - for (int offset = 0; offset < data.length; offset += 4) { - long value = (long) Byte.toUnsignedInt(data[offset]) << 24; - if (offset + 1 < data.length) { - value |= (long) Byte.toUnsignedInt(data[offset + 1]) << 16; - } - if (offset + 2 < data.length) { - value |= (long) Byte.toUnsignedInt(data[offset + 2]) << 8; - } - if (offset + 3 < data.length) { - value |= Byte.toUnsignedInt(data[offset + 3]); - } - sum = (sum + value) & 0xFFFFFFFFL; - } - return sum; - } - - boolean supports(Set codePoints) { - for (int codePoint : codePoints) { - Integer glyph = cmap.get(codePoint); - if (codePoint > 0xFFFF || glyph == null || glyph <= 0 || glyph >= advances.length) { - return false; - } - } - return true; - } - - String pdfName() { - return pdfName; - } - - byte[] data() { - return data.clone(); - } - - int ascent() { - return ascent; - } - - int descent() { - return descent; - } - - int capHeight() { - return capHeight; - } - - String boundingBox() { - return boundingBox[0] + " " + boundingBox[1] + " " + boundingBox[2] + " " + boundingBox[3]; - } - - String widths(Set codePoints) { - StringBuilder result = new StringBuilder("["); - for (int codePoint : codePoints) { - Integer glyph = cmap.get(codePoint); - if (glyph != null && glyph < advances.length) { - result.append(codePoint).append(" [") - .append((int) (advances[glyph] * 1000L / unitsPerEm)) - .append("] "); - } - } - return result.append(']').toString(); - } - - byte[] cidToGidMap(Set codePoints) { - byte[] mapping = new byte[65536 * 2]; - for (int codePoint : codePoints) { - Integer glyph = cmap.get(codePoint); - if (glyph != null) { - mapping[codePoint * 2] = (byte) (glyph >> 8); - mapping[codePoint * 2 + 1] = (byte) (glyph & 0xFF); - } - } - return mapping; - } - - byte[] toUnicode(Set codePoints) { - StringBuilder result = new StringBuilder(); - result.append("/CIDInit /ProcSet findresource begin\n") - .append("12 dict begin\nbegincmap\n") - .append("/CIDSystemInfo << /Registry (Adobe) /Ordering (UCS) /Supplement 0 >> def\n") - .append("/CMapName /Adobe-Identity-UCS def\n/CMapType 2 def\n") - .append("1 begincodespacerange\n<0000> \nendcodespacerange\n"); - int offset = 0; - Integer[] points = codePoints.toArray(new Integer[0]); - while (offset < points.length) { - int count = Math.min(100, points.length - offset); - result.append(count).append(" beginbfchar\n"); - for (int index = 0; index < count; index++) { - int codePoint = points[offset + index]; - result.append(String.format("<%04X> <%04X>\n", codePoint, codePoint)); - } - result.append("endbfchar\n"); - offset += count; - } - result.append("endcmap\nCMapName currentdict /CMap defineresource pop\nend\nend\n"); - return result.toString().getBytes(StandardCharsets.ISO_8859_1); - } - - private static Map readTables(byte[] data) { - int tableCount = readU16(data, 4); - requireRange(data, 12, tableCount * 16); - Map tables = new HashMap<>(); - for (int index = 0; index < tableCount; index++) { - int record = 12 + index * 16; - String tag = new String(data, record, 4, StandardCharsets.ISO_8859_1); - long offset = readU32(data, record + 8); - long length = readU32(data, record + 12); - if (offset > Integer.MAX_VALUE || length > Integer.MAX_VALUE) { - throw new IllegalArgumentException("font table is too large"); - } - requireRange(data, (int) offset, (int) length); - tables.put(tag, new Table((int) offset, (int) length)); - } - return tables; - } - - private static Map readCmap(byte[] data, Table cmapTable) { - requireTableLength(cmapTable, 4); - int count = readU16(data, cmapTable.offset + 2); - requireTableRange(cmapTable, 4, count * 8); - int tableEnd = cmapTable.offset + cmapTable.length; - for (int pass = 0; pass < 2; pass++) { - for (int index = 0; index < count; index++) { - int record = cmapTable.offset + 4 + index * 8; - int platform = readU16(data, record); - int encoding = readU16(data, record + 2); - long relative = readU32(data, record + 4); - if (relative > Integer.MAX_VALUE || relative >= cmapTable.length) { - throw new IllegalArgumentException("font contains an invalid cmap subtable offset"); - } - int offset = cmapTable.offset + (int) relative; - requireTableRange(cmapTable, (int) relative, 2); - int format = readU16(data, offset); - boolean preferred = pass == 0 - ? format == 12 && ((platform == 3 && encoding == 10) || platform == 0) - : format == 4 && ((platform == 3 && encoding == 1) || platform == 0); - if (preferred) { - Map mapping = format == 12 - ? readCmapFormat12(data, offset, tableEnd) - : readCmapFormat4(data, offset, tableEnd); - if (!mapping.isEmpty()) { - return mapping; - } - } - } - } - return new HashMap<>(); - } - - private static Map readCmapFormat4(byte[] data, int offset, int tableEnd) { - requireBoundedRange(data, offset, 16, tableEnd); - int length = readU16(data, offset + 2); - requireBoundedRange(data, offset, length, tableEnd); - int segmentCount = readU16(data, offset + 6) / 2; - int endCodes = offset + 14; - int startCodes = endCodes + segmentCount * 2 + 2; - int deltas = startCodes + segmentCount * 2; - int rangeOffsets = deltas + segmentCount * 2; - requireBoundedRange(data, rangeOffsets, segmentCount * 2, offset + length); - Map mapping = new HashMap<>(); - int previousEnd = -1; - for (int segment = 0; segment < segmentCount; segment++) { - int end = readU16(data, endCodes + segment * 2); - int start = readU16(data, startCodes + segment * 2); - int delta = readS16(data, deltas + segment * 2); - int rangeOffset = readU16(data, rangeOffsets + segment * 2); - if (start == 0xFFFF) { - break; - } - if (start > end || start <= previousEnd) { - throw new IllegalArgumentException("font contains overlapping cmap segments"); - } - previousEnd = end; - for (int codePoint = start; codePoint <= end; codePoint++) { - int glyph; - if (rangeOffset == 0) { - glyph = (codePoint + delta) & 0xFFFF; - } else { - int glyphOffset = rangeOffsets + segment * 2 + rangeOffset + (codePoint - start) * 2; - if (glyphOffset + 2 > offset + length) { - continue; - } - glyph = readU16(data, glyphOffset); - if (glyph != 0) { - glyph = (glyph + delta) & 0xFFFF; - } - } - if (glyph != 0) { - mapping.put(codePoint, glyph); - } - } - } - return mapping; - } - - private static Map readCmapFormat12(byte[] data, int offset, int tableEnd) { - requireBoundedRange(data, offset, 16, tableEnd); - long length = readU32(data, offset + 4); - long groupCount = readU32(data, offset + 12); - if (length > Integer.MAX_VALUE || groupCount > (length - 16) / 12) { - throw new IllegalArgumentException("font contains an invalid format 12 cmap"); - } - requireBoundedRange(data, offset, (int) length, tableEnd); - Map mapping = new HashMap<>(); - long previousEnd = -1; - for (int group = 0; group < (int) groupCount; group++) { - int groupOffset = offset + 16 + group * 12; - long start = readU32(data, groupOffset); - long declaredEnd = readU32(data, groupOffset + 4); - long firstGlyph = readU32(data, groupOffset + 8); - if (start > declaredEnd || start <= previousEnd) { - throw new IllegalArgumentException("font contains overlapping cmap groups"); - } - previousEnd = declaredEnd; - long end = Math.min(declaredEnd, 0xFFFFL); - for (long codePoint = start; codePoint <= end; codePoint++) { - long glyphValue = firstGlyph + codePoint - start; - if (glyphValue > Integer.MAX_VALUE) { - throw new IllegalArgumentException("font cmap glyph index is too large"); - } - int glyph = (int) glyphValue; - if (glyph != 0) { - mapping.put((int) codePoint, glyph); - } - } - } - return mapping; - } - - private static Table requiredTable(Map tables, String name) { - Table table = tables.get(name); - if (table == null) { - throw new IllegalArgumentException("font is missing the " + name + " table"); - } - return table; - } - - private static void requireTableLength(Table table, int requiredLength) { - if (requiredLength < 0 || table.length < requiredLength) { - throw new IllegalArgumentException("font table is shorter than required"); - } - } - - private static void requireTableRange(Table table, int relativeOffset, int length) { - if (relativeOffset < 0 || length < 0 || relativeOffset > table.length - length) { - throw new IllegalArgumentException("font read exceeds its declared table"); - } - } - - private static void requireBoundedRange(byte[] data, int offset, int length, int end) { - requireRange(data, offset, length); - if (offset > end - length) { - throw new IllegalArgumentException("font read exceeds its declared table"); - } - } - - private static int readU16(byte[] data, int offset) { - requireRange(data, offset, 2); - return (Byte.toUnsignedInt(data[offset]) << 8) | Byte.toUnsignedInt(data[offset + 1]); - } - - private static int readS16(byte[] data, int offset) { - return (short) readU16(data, offset); - } - - private static long readU32(byte[] data, int offset) { - requireRange(data, offset, 4); - return ((long) Byte.toUnsignedInt(data[offset]) << 24) - | ((long) Byte.toUnsignedInt(data[offset + 1]) << 16) - | ((long) Byte.toUnsignedInt(data[offset + 2]) << 8) - | Byte.toUnsignedInt(data[offset + 3]); - } - - private static void writeU32(byte[] data, int offset, long value) { - requireRange(data, offset, 4); - data[offset] = (byte) (value >> 24); - data[offset + 1] = (byte) (value >> 16); - data[offset + 2] = (byte) (value >> 8); - data[offset + 3] = (byte) value; - } - - private static void requireRange(byte[] data, int offset, int length) { - if (offset < 0 || length < 0 || offset > data.length - length) { - throw new IllegalArgumentException("font contains an invalid table range"); - } - } - - private static int scale(int value, int unitsPerEm) { - return (int) Math.round(value * 1000.0 / unitsPerEm); - } - - private static String sanitizeName(String name) { - String sanitized = name.trim().replaceAll("[^A-Za-z0-9_-]+", "-"); - return sanitized.isEmpty() ? "RegisteredFont" : sanitized; - } - - private static final class Table { - private final int offset; - private final int length; - - private Table(int offset, int length) { - this.offset = offset; - this.length = length; - } - } - - private static final class CollectionTable { - private final int sourceRecord; - private final int sourceOffset; - private final int length; - private final int destinationOffset; - - private CollectionTable(int sourceRecord, int sourceOffset, int length, int destinationOffset) { - this.sourceRecord = sourceRecord; - this.sourceOffset = sourceOffset; - this.length = length; - this.destinationOffset = destinationOffset; - } - } -} \ No newline at end of file diff --git a/minipdf-java/minipdf/src/main/java/io/github/minisoftware/minipdf/internal/FontEmbeddingPolicy.java b/minipdf-java/minipdf/src/main/java/io/github/minisoftware/minipdf/internal/FontEmbeddingPolicy.java deleted file mode 100644 index a91dfdda..00000000 --- a/minipdf-java/minipdf/src/main/java/io/github/minisoftware/minipdf/internal/FontEmbeddingPolicy.java +++ /dev/null @@ -1,14 +0,0 @@ -package io.github.minisoftware.minipdf.internal; - -public final class FontEmbeddingPolicy { - private FontEmbeddingPolicy() { - } - - public static boolean shouldSubset() { - return shouldSubset(System.getProperty("java.specification.version")); - } - - static boolean shouldSubset(String javaSpecificationVersion) { - return !"10".equals(javaSpecificationVersion); - } -} \ No newline at end of file diff --git a/minipdf-java/minipdf/src/main/java/io/github/minisoftware/minipdf/internal/OfficePackageDetector.java b/minipdf-java/minipdf/src/main/java/io/github/minisoftware/minipdf/internal/OfficePackageDetector.java deleted file mode 100644 index 6b4d3678..00000000 --- a/minipdf-java/minipdf/src/main/java/io/github/minisoftware/minipdf/internal/OfficePackageDetector.java +++ /dev/null @@ -1,28 +0,0 @@ -package io.github.minisoftware.minipdf.internal; - -import io.github.minisoftware.minipdf.MiniPdfException; -import io.github.minisoftware.minipdf.OfficeFormat; - -import java.util.Locale; - -public final class OfficePackageDetector { - private OfficePackageDetector() { - } - - public static OfficeFormat detect(byte[] input) throws MiniPdfException { - OoxmlPackage archive = OoxmlPackage.open(input); - for (String entryName : archive.entryNames()) { - String name = entryName.toLowerCase(Locale.ROOT); - if (name.startsWith("word/")) { - return OfficeFormat.DOCX; - } - if (name.startsWith("xl/")) { - return OfficeFormat.XLSX; - } - if (name.startsWith("ppt/")) { - return OfficeFormat.PPTX; - } - } - return OfficeFormat.UNKNOWN; - } -} \ No newline at end of file diff --git a/minipdf-java/minipdf/src/main/java/io/github/minisoftware/minipdf/internal/OoxmlPackage.java b/minipdf-java/minipdf/src/main/java/io/github/minisoftware/minipdf/internal/OoxmlPackage.java deleted file mode 100644 index 83490a7b..00000000 --- a/minipdf-java/minipdf/src/main/java/io/github/minisoftware/minipdf/internal/OoxmlPackage.java +++ /dev/null @@ -1,120 +0,0 @@ -package io.github.minisoftware.minipdf.internal; - -import io.github.minisoftware.minipdf.MiniPdfException; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.nio.charset.StandardCharsets; -import java.util.Collections; -import java.util.LinkedHashMap; -import java.util.Map; -import java.util.Optional; -import java.util.Set; -import java.util.zip.ZipEntry; -import java.util.zip.ZipException; -import java.util.zip.ZipInputStream; - -public final class OoxmlPackage { - private static final int MAX_ENTRIES = 10_000; - private static final long MAX_ENTRY_SIZE = 128L * 1024L * 1024L; - private static final long MAX_TOTAL_SIZE = 512L * 1024L * 1024L; - private static final long MAX_EXPANSION_RATIO = 200L; - - private final Map entries; - - private OoxmlPackage(Map entries) { - this.entries = Collections.unmodifiableMap(entries); - } - - public static OoxmlPackage open(byte[] input) throws MiniPdfException { - if (!hasZipSignature(input)) { - throw invalidPackage("input is not a ZIP package"); - } - - Map entries = new LinkedHashMap<>(); - long totalSize = 0; - try (ZipInputStream archive = new ZipInputStream(new ByteArrayInputStream(input))) { - ZipEntry entry; - while ((entry = archive.getNextEntry()) != null) { - if (entries.size() >= MAX_ENTRIES) { - throw invalidPackage("ZIP package contains too many entries"); - } - String name = normalizeEntryName(entry.getName()); - if (entry.isDirectory()) { - continue; - } - if (entries.containsKey(name)) { - throw invalidPackage("ZIP package contains duplicate entry: " + name); - } - - ByteArrayOutputStream content = new ByteArrayOutputStream(); - byte[] buffer = new byte[8192]; - int read; - while ((read = archive.read(buffer)) != -1) { - if ((long) content.size() + read > MAX_ENTRY_SIZE) { - throw invalidPackage("ZIP entry expands beyond the configured limit: " + name); - } - content.write(buffer, 0, read); - } - byte[] bytes = content.toByteArray(); - totalSize += bytes.length; - if (totalSize > MAX_TOTAL_SIZE - || (input.length > 0 && totalSize / input.length > MAX_EXPANSION_RATIO)) { - throw invalidPackage("ZIP package expands beyond the configured limit"); - } - entries.put(name, bytes); - } - } catch (ZipException exception) { - throw new MiniPdfException( - MiniPdfException.Kind.ZIP_PACKAGE, - "invalid ZIP package: " + exception.getMessage(), - exception); - } catch (IOException exception) { - throw new MiniPdfException( - MiniPdfException.Kind.IO, - "I/O error while reading ZIP package: " + exception.getMessage(), - exception); - } - return new OoxmlPackage(entries); - } - - public Set entryNames() { - return entries.keySet(); - } - - public Optional entry(String name) { - byte[] bytes = entries.get(name); - return bytes == null ? Optional.empty() : Optional.of(bytes.clone()); - } - - public Optional text(String name) { - return entry(name).map(bytes -> new String(bytes, StandardCharsets.UTF_8)); - } - - private static String normalizeEntryName(String entryName) throws MiniPdfException { - String normalized = entryName.replace('\\', '/'); - if (normalized.startsWith("/") || normalized.contains(":") || normalized.indexOf('\0') >= 0) { - throw invalidPackage("ZIP package contains an unsafe entry path: " + entryName); - } - for (String segment : normalized.split("/")) { - if (segment.equals("..")) { - throw invalidPackage("ZIP package contains an unsafe entry path: " + entryName); - } - } - return normalized; - } - - private static boolean hasZipSignature(byte[] input) { - if (input == null || input.length < 4 || input[0] != 'P' || input[1] != 'K') { - return false; - } - return (input[2] == 3 && input[3] == 4) - || (input[2] == 5 && input[3] == 6) - || (input[2] == 7 && input[3] == 8); - } - - private static MiniPdfException invalidPackage(String message) { - return new MiniPdfException(MiniPdfException.Kind.ZIP_PACKAGE, message); - } -} \ No newline at end of file diff --git a/minipdf-java/minipdf/src/main/java/io/github/minisoftware/minipdf/internal/SecureXml.java b/minipdf-java/minipdf/src/main/java/io/github/minisoftware/minipdf/internal/SecureXml.java deleted file mode 100644 index 2c563d87..00000000 --- a/minipdf-java/minipdf/src/main/java/io/github/minisoftware/minipdf/internal/SecureXml.java +++ /dev/null @@ -1,31 +0,0 @@ -package io.github.minisoftware.minipdf.internal; - -import io.github.minisoftware.minipdf.MiniPdfException; - -import javax.xml.stream.XMLInputFactory; -import javax.xml.stream.XMLStreamException; -import javax.xml.stream.XMLStreamReader; -import java.io.ByteArrayInputStream; - -public final class SecureXml { - private SecureXml() { - } - - public static XMLStreamReader reader(byte[] xml) throws MiniPdfException { - XMLInputFactory factory = XMLInputFactory.newFactory(); - factory.setProperty(XMLInputFactory.SUPPORT_DTD, false); - factory.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, false); - try { - return factory.createXMLStreamReader(new ByteArrayInputStream(xml)); - } catch (XMLStreamException exception) { - throw parseError(exception); - } - } - - public static MiniPdfException parseError(XMLStreamException exception) { - return new MiniPdfException( - MiniPdfException.Kind.XML_PARSE, - "XML parse error: " + exception.getMessage(), - exception); - } -} \ No newline at end of file diff --git a/minipdf-java/minipdf/src/main/java/io/github/minisoftware/minipdf/internal/SimplePdfTextRenderer.java b/minipdf-java/minipdf/src/main/java/io/github/minisoftware/minipdf/internal/SimplePdfTextRenderer.java deleted file mode 100644 index 6ffa3093..00000000 --- a/minipdf-java/minipdf/src/main/java/io/github/minisoftware/minipdf/internal/SimplePdfTextRenderer.java +++ /dev/null @@ -1,454 +0,0 @@ -package io.github.minisoftware.minipdf.internal; - -import io.github.minisoftware.minipdf.ConversionOptions; -import io.github.minisoftware.minipdf.MiniPdf; -import io.github.minisoftware.minipdf.MiniPdfException; -import io.github.minisoftware.minipdf.PageSize; -import io.github.minisoftware.minipdf.PdfColor; -import io.github.minisoftware.minipdf.PdfDocument; -import io.github.minisoftware.minipdf.PdfPage; -import io.github.minisoftware.minipdf.RegisteredFont; -import org.apache.fontbox.ttf.TTFParser; -import org.apache.fontbox.ttf.TrueTypeCollection; -import org.apache.fontbox.ttf.TrueTypeFont; -import org.apache.pdfbox.pdmodel.PDDocument; -import org.apache.pdfbox.pdmodel.PDPage; -import org.apache.pdfbox.pdmodel.PDPageContentStream; -import org.apache.pdfbox.pdmodel.common.PDRectangle; -import org.apache.pdfbox.pdmodel.font.PDFont; -import org.apache.pdfbox.pdmodel.font.PDType0Font; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.nio.file.DirectoryStream; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.nio.charset.StandardCharsets; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Locale; -import java.util.Map; - -public final class SimplePdfTextRenderer { - private static final float MARGIN = 54.0f; - private static final float FONT_SIZE = 11.0f; - private static final float LINE_HEIGHT = 15.0f; - - private SimplePdfTextRenderer() { - } - - public static byte[] render(List sourceLines, ConversionOptions options) throws MiniPdfException { - return renderPages(Collections.singletonList(sourceLines), options, PageSize.A4); - } - - public static byte[] renderPages( - List> sourcePages, - ConversionOptions options, - PageSize defaultPageSize) throws MiniPdfException { - PageSize size = options.pageSize().orElse(defaultPageSize); - byte[] nativePdf = renderNative(sourcePages, size); - if (usesNativeRegisteredFont(nativePdf, sourcePages, size)) { - return nativePdf; - } - byte[] unicodeFontPdf = renderWithUnicodeFont(sourcePages, size); - if (unicodeFontPdf != null) { - return unicodeFontPdf; - } - return nativePdf; - } - - private static byte[] renderNative(List> sourcePages, PageSize size) { - PdfDocument document = new PdfDocument(); - int maxCharacters = Math.max(1, (int) ((size.width() - MARGIN * 2.0f) / (FONT_SIZE * 0.52f))); - - for (List sourcePage : sourcePages) { - PdfPage page = document.addPage(size.width(), size.height()); - float y = size.height() - MARGIN; - for (String sourceLine : sourcePage) { - for (String line : wrap(sourceLine, maxCharacters)) { - if (y < MARGIN) { - page = document.addPage(size.width(), size.height()); - y = size.height() - MARGIN; - } - page.addText(line, MARGIN, y, FONT_SIZE, PdfColor.BLACK, false); - y -= LINE_HEIGHT; - } - } - } - return document.toBytes(); - } - - private static boolean usesNativeRegisteredFont( - byte[] pdf, - List> sourcePages, - PageSize size) { - if (MiniPdf.registeredFonts().isEmpty()) { - return false; - } - String raw = new String(pdf, StandardCharsets.ISO_8859_1); - if (!raw.contains("/Subtype /Type0")) { - return false; - } - int maxCharacters = Math.max(1, (int) ((size.width() - MARGIN * 2.0f) / (FONT_SIZE * 0.52f))); - boolean hasUnicode = false; - for (List sourcePage : sourcePages) { - for (String sourceLine : sourcePage) { - for (String line : wrap(sourceLine, maxCharacters)) { - if (line.codePoints().anyMatch(codePoint -> codePoint > 255)) { - hasUnicode = true; - if (!raw.contains('<' + unicodeHex(line) + "> Tj")) { - return false; - } - } - } - } - } - return hasUnicode; - } - - private static String unicodeHex(String text) { - StringBuilder result = new StringBuilder(text.length() * 4); - for (int index = 0; index < text.length(); index++) { - result.append(String.format(Locale.ROOT, "%04X", (int) text.charAt(index))); - } - return result.toString(); - } - - private static byte[] renderWithUnicodeFont(List> sourcePages, PageSize size) - throws MiniPdfException { - boolean requiresSystemFont = sourcePages.stream() - .flatMap(List::stream) - .flatMapToInt(String::codePoints) - .anyMatch(codePoint -> codePoint > 255); - if (MiniPdf.registeredFonts().isEmpty() && !requiresSystemFont) { - return null; - } - try (PDDocument document = new PDDocument()) { - PDFont font = loadFont(document, sourcePages); - if (font == null) { - return null; - } - - int maxCharacters = Math.max(1, (int) ((size.width() - MARGIN * 2.0f) / (FONT_SIZE * 0.52f))); - for (List sourcePage : sourcePages) { - PDPage page = addPage(document, size); - PDPageContentStream content = new PDPageContentStream(document, page); - try { - float y = size.height() - MARGIN; - for (String sourceLine : sourcePage) { - for (String line : wrap(sourceLine, maxCharacters)) { - if (y < MARGIN) { - PDPageContentStream completedContent = content; - content = null; - completedContent.close(); - page = addPage(document, size); - content = new PDPageContentStream(document, page); - y = size.height() - MARGIN; - } - content.beginText(); - content.setFont(font, FONT_SIZE); - content.newLineAtOffset(MARGIN, y); - content.showText(line); - content.endText(); - y -= LINE_HEIGHT; - } - } - } finally { - if (content != null) { - content.close(); - } - } - } - - ByteArrayOutputStream output = new ByteArrayOutputStream(); - document.save(output); - return output.toByteArray(); - } catch (IOException exception) { - throw new MiniPdfException( - MiniPdfException.Kind.IO, - "failed to render PDF with a registered font: " + exception.getMessage(), - exception); - } - } - - public static PDFont loadFont(PDDocument document, List> sourcePages) { - for (RegisteredFont registeredFont : MiniPdf.registeredFonts()) { - try { - PDFont font = PDType0Font.load( - document, - new ByteArrayInputStream(registeredFont.data()), - FontEmbeddingPolicy.shouldSubset()); - if (supports(font, sourcePages)) { - return font; - } - } catch (IOException | IllegalArgumentException ignored) { - // Try the next registered font. - } - } - return loadSystemFont( - document, - sourcePages, - "simsun.ttc", - "msyh.ttc", - "mingliu.ttc", - "arialuni.ttf"); - } - - public static PDFont loadSystemFont( - PDDocument document, - List> sourcePages, - String... fileNames) { - for (Path path : systemFontPaths(fileNames)) { - if (!Files.isRegularFile(path)) { - continue; - } - try { - PDFont font = path.getFileName().toString().toLowerCase().endsWith(".ttc") - ? loadCollectionFont(document, path, sourcePages) - : PDType0Font.load( - document, - Files.newInputStream(path), - FontEmbeddingPolicy.shouldSubset()); - if (font != null && supports(font, sourcePages)) { - return font; - } - } catch (IOException | IllegalArgumentException ignored) { - // Try the next system font. - } - } - return null; - } - - /** - * Loads a font by family name instead of file name, mirroring MiniPdf for - * .NET's FindOfficeCloudFontByPreferredName: searches the Microsoft 365 - * cloud font cache (under %LOCALAPPDATA%/Microsoft/FontCache, in the - * per-version CloudFonts family subfolder) and a small Windows/Fonts - * file-name map. The requested name may carry a weight suffix ("Source - * Sans Pro Bold") to prefer the matching sub-family face. - */ - public static PDFont loadSystemFontByFamily( - PDDocument document, - List> sourcePages, - String... familyNames) { - for (String family : familyNames) { - for (Path path : familyFontPaths(family)) { - if (!Files.isRegularFile(path)) { - continue; - } - try { - PDFont font = PDType0Font.load( - document, - Files.newInputStream(path), - FontEmbeddingPolicy.shouldSubset()); - if (font != null && supports(font, sourcePages)) { - return font; - } - } catch (IOException | IllegalArgumentException ignored) { - // Try the next candidate. - } - } - } - return null; - } - - /** - * Well-known Windows font families and their file names. Cloud font - * families resolve through {@link #familyFontPaths} instead. - */ - private static final Map WINDOWS_FONT_FILES = new HashMap<>(); - - static { - WINDOWS_FONT_FILES.put("impact", "impact.ttf"); - } - - /** - * Resolves a family name (optionally suffixed with " Regular" / " Bold") to - * candidate font file paths. Exact sub-family matches win over a plain - * family match, mirroring Word's font selection. - */ - private static List familyFontPaths(String family) { - List paths = new ArrayList<>(); - if (family == null || family.trim().isEmpty()) { - return paths; - } - String requested = family.trim(); - String base = requested; - String wantedSubFamily = ""; - for (String suffix : new String[] {" Bold Italic", " Bold", " Italic", " Regular"}) { - if (requested.toLowerCase(Locale.ROOT).endsWith(suffix.toLowerCase(Locale.ROOT))) { - wantedSubFamily = suffix.trim(); - base = requested.substring(0, requested.length() - suffix.length()).trim(); - break; - } - } - // Windows\Fonts: exact known file names. - String windows = System.getenv("WINDIR"); - if (windows != null) { - String mapped = WINDOWS_FONT_FILES.get(base.toLowerCase(Locale.ROOT)); - if (mapped != null) { - paths.add(Paths.get(windows, "Fonts", mapped)); - } - } - // Microsoft 365 cloud font cache. - String localAppData = System.getenv("LOCALAPPDATA"); - if (localAppData == null) { - return paths; - } - Path cacheRoot = Paths.get(localAppData, "Microsoft", "FontCache"); - if (!Files.isDirectory(cacheRoot)) { - return paths; - } - Path exact = null; - Path familyFallback = null; - try (DirectoryStream versions = Files.newDirectoryStream(cacheRoot)) { - for (Path version : versions) { - Path familyDir = version.resolve("CloudFonts").resolve(base); - if (!Files.isDirectory(familyDir)) { - continue; - } - try (DirectoryStream files = Files.newDirectoryStream(familyDir)) { - for (Path file : files) { - if (!isFontFile(file)) { - continue; - } - String[] names = fontNames(file); - String subFamily = names[0]; - String postScript = names[1]; - if (wantedSubFamily.isEmpty()) { - if (subFamily != null && subFamily.equalsIgnoreCase("regular") - || postScript != null - && postScript.toLowerCase(Locale.ROOT).contains("regular")) { - exact = file; - } else if (familyFallback == null) { - familyFallback = file; - } - } else if (subFamily != null && subFamily.equalsIgnoreCase(wantedSubFamily)) { - exact = file; - } - } - } - if (exact != null) { - break; - } - } - } catch (IOException ignored) { - // Cloud cache unavailable; keep whatever was found. - } - if (exact != null) { - paths.add(exact); - } else if (familyFallback != null) { - paths.add(familyFallback); - } - return paths; - } - - private static boolean isFontFile(Path path) { - String name = path.getFileName().toString().toLowerCase(Locale.ROOT); - return name.endsWith(".ttf") || name.endsWith(".otf"); - } - - /** - * Reads {sub-family, postscript} names from a TrueType/OpenType file. - */ - private static String[] fontNames(Path path) { - try (InputStream stream = Files.newInputStream(path)) { - TrueTypeFont font = new TTFParser().parseEmbedded(stream); - return new String[] { - font.getNaming().getFontSubFamily(), - font.getNaming().getPostScriptName() - }; - } catch (IOException ignored) { - return new String[] {null, null}; - } - } - - private static PDFont loadCollectionFont( - PDDocument document, - Path path, - List> sourcePages) throws IOException { - PDFont[] supported = new PDFont[1]; - try (TrueTypeCollection collection = new TrueTypeCollection(path.toFile())) { - collection.processAllFonts(font -> { - if (supported[0] == null) { - PDFont candidate = PDType0Font.load( - document, - font, - FontEmbeddingPolicy.shouldSubset()); - if (supports(candidate, sourcePages)) { - supported[0] = candidate; - } - } - }); - } - return supported[0]; - } - - private static List systemFontPaths(String... names) { - List paths = new ArrayList<>(); - String windows = System.getenv("WINDIR"); - if (windows != null) { - Path fonts = Paths.get(windows, "Fonts"); - for (String name : names) { - paths.add(fonts.resolve(name)); - } - } - for (String name : names) { - paths.add(Paths.get("/usr/share/fonts/truetype/noto", name)); - paths.add(Paths.get("/usr/share/fonts/opentype/noto", name)); - paths.add(Paths.get("/System/Library/Fonts", name)); - paths.add(Paths.get("/System/Library/Fonts/Supplemental", name)); - } - return paths; - } - - private static boolean supports(PDFont font, List> sourcePages) { - try { - for (List sourcePage : sourcePages) { - for (String line : sourcePage) { - font.getStringWidth(line); - } - } - return true; - } catch (IOException | IllegalArgumentException exception) { - return false; - } - } - - private static PDPage addPage(PDDocument document, PageSize size) { - PDPage page = new PDPage(new PDRectangle(size.width(), size.height())); - document.addPage(page); - return page; - } - - private static List wrap(String value, int maxCharacters) { - if (value.isEmpty()) { - return Collections.singletonList(""); - } - List lines = new ArrayList<>(); - String remaining = value; - while (remaining.length() > maxCharacters) { - int split = remaining.lastIndexOf(' ', maxCharacters); - if (split <= 0) { - split = maxCharacters; - } - lines.add(remaining.substring(0, split)); - remaining = stripLeading(remaining.substring(split)); - } - lines.add(remaining); - return lines; - } - - private static String stripLeading(String value) { - int index = 0; - while (index < value.length() && Character.isWhitespace(value.charAt(index))) { - index++; - } - return value.substring(index); - } -} \ No newline at end of file diff --git a/minipdf-java/minipdf/src/main/java/io/github/minisoftware/minipdf/internal/docx/DocxConverter.java b/minipdf-java/minipdf/src/main/java/io/github/minisoftware/minipdf/internal/docx/DocxConverter.java deleted file mode 100644 index 7aab5725..00000000 --- a/minipdf-java/minipdf/src/main/java/io/github/minisoftware/minipdf/internal/docx/DocxConverter.java +++ /dev/null @@ -1,187 +0,0 @@ -package io.github.minisoftware.minipdf.internal.docx; - -import io.github.minisoftware.minipdf.ConversionOptions; -import io.github.minisoftware.minipdf.MiniPdfException; -import io.github.minisoftware.minipdf.PageSize; -import io.github.minisoftware.minipdf.internal.OoxmlPackage; -import io.github.minisoftware.minipdf.internal.SecureXml; -import io.github.minisoftware.minipdf.internal.SimplePdfTextRenderer; - -import javax.xml.stream.XMLStreamConstants; -import javax.xml.stream.XMLStreamException; -import javax.xml.stream.XMLStreamReader; -import java.util.ArrayList; -import java.util.List; - -public final class DocxConverter { - private DocxConverter() { - } - - public static byte[] convert(byte[] input, ConversionOptions options) throws MiniPdfException { - OoxmlPackage document = OoxmlPackage.open(input); - byte[] documentXml = document.entry("word/document.xml") - .orElseThrow(() -> new MiniPdfException( - MiniPdfException.Kind.INVALID_INPUT, - "DOCX package does not contain word/document.xml")); - DocxContent content = readDocument(documentXml); - if (content.tableCount() > 0) { - byte[] structured = PoiDocxRenderer.render(input, options, content.pageSize()); - if (structured != null) { - return structured; - } - } - return SimplePdfTextRenderer.renderPages(content.pages(), options, content.pageSize()); - } - - private static DocxContent readDocument(byte[] documentXml) throws MiniPdfException { - List> pages = new ArrayList<>(); - List page = new ArrayList<>(); - StringBuilder paragraph = null; - float pageWidth = 0.0f; - float pageHeight = 0.0f; - boolean inParagraphSectionProperties = false; - boolean sectionBreakAfterParagraph = false; - boolean paragraphSectionChangesOrientation = false; - int tableCount = 0; - int drawingCount = 0; - try { - XMLStreamReader reader = SecureXml.reader(documentXml); - while (reader.hasNext()) { - int event = reader.next(); - if (event == XMLStreamConstants.START_ELEMENT && reader.getLocalName().equals("pgSz")) { - boolean landscape = "landscape".equals(attribute(reader, "orient")); - if (inParagraphSectionProperties && landscape) { - paragraphSectionChangesOrientation = true; - } - pageWidth = floatAttribute(reader, "w") / 20.0f; - pageHeight = floatAttribute(reader, "h") / 20.0f; - } else if (event == XMLStreamConstants.START_ELEMENT && reader.getLocalName().equals("p")) { - paragraph = new StringBuilder(); - sectionBreakAfterParagraph = false; - paragraphSectionChangesOrientation = false; - } else if (event == XMLStreamConstants.START_ELEMENT && reader.getLocalName().equals("tbl")) { - tableCount++; - } else if (event == XMLStreamConstants.START_ELEMENT && reader.getLocalName().equals("drawing")) { - drawingCount++; - } else if (event == XMLStreamConstants.START_ELEMENT - && reader.getLocalName().equals("sectPr") && paragraph != null) { - inParagraphSectionProperties = true; - sectionBreakAfterParagraph = true; - } else if (event == XMLStreamConstants.START_ELEMENT - && reader.getLocalName().equals("type") && inParagraphSectionProperties) { - sectionBreakAfterParagraph = !"continuous".equals(attribute(reader, "val")); - } else if (event == XMLStreamConstants.START_ELEMENT - && reader.getLocalName().equals("t") && paragraph != null) { - paragraph.append(reader.getElementText()); - } else if (event == XMLStreamConstants.START_ELEMENT - && reader.getLocalName().equals("tab") && paragraph != null) { - paragraph.append(" "); - } else if (event == XMLStreamConstants.START_ELEMENT - && (reader.getLocalName().equals("br") || reader.getLocalName().equals("cr")) - && paragraph != null) { - if (isPageBreak(reader)) { - page.add(paragraph.toString()); - pages.add(page); - page = new ArrayList<>(); - paragraph = new StringBuilder(); - } else if (isLineBreak(reader)) { - page.add(paragraph.toString()); - paragraph = new StringBuilder(); - } else { - paragraph.append(' '); - } - } else if (event == XMLStreamConstants.END_ELEMENT - && reader.getLocalName().equals("sectPr") && inParagraphSectionProperties) { - inParagraphSectionProperties = false; - } else if (event == XMLStreamConstants.END_ELEMENT - && reader.getLocalName().equals("p") && paragraph != null) { - page.add(paragraph.toString()); - paragraph = null; - if (sectionBreakAfterParagraph && !paragraphSectionChangesOrientation && !page.isEmpty()) { - pages.add(page); - page = new ArrayList<>(); - } - } - } - reader.close(); - if (!page.isEmpty() || pages.isEmpty()) { - pages.add(page); - } - PageSize pageSize = pageWidth > 0.0f && pageHeight > 0.0f - ? PageSize.of(pageWidth, pageHeight) - : PageSize.A4; - return new DocxContent(pages, pageSize, tableCount, drawingCount); - } catch (XMLStreamException exception) { - throw SecureXml.parseError(exception); - } - } - - private static float floatAttribute(XMLStreamReader reader, String localName) { - String value = attribute(reader, localName); - if (value == null) { - return 0.0f; - } - try { - return Float.parseFloat(value); - } catch (NumberFormatException ignored) { - return 0.0f; - } - } - - private static String attribute(XMLStreamReader reader, String localName) { - for (int index = 0; index < reader.getAttributeCount(); index++) { - if (reader.getAttributeLocalName(index).equals(localName)) { - return reader.getAttributeValue(index); - } - } - return null; - } - - private static boolean isPageBreak(XMLStreamReader reader) { - for (int index = 0; index < reader.getAttributeCount(); index++) { - if (reader.getAttributeLocalName(index).equals("type") - && reader.getAttributeValue(index).equals("page")) { - return true; - } - } - return false; - } - - private static boolean isLineBreak(XMLStreamReader reader) { - if (reader.getLocalName().equals("cr")) { - return true; - } - String type = attribute(reader, "type"); - return type == null || type.equals("textWrapping"); - } - - private static final class DocxContent { - private final List> pages; - private final PageSize pageSize; - private final int tableCount; - private final int drawingCount; - - private DocxContent(List> pages, PageSize pageSize, int tableCount, int drawingCount) { - this.pages = pages; - this.pageSize = pageSize; - this.tableCount = tableCount; - this.drawingCount = drawingCount; - } - - private List> pages() { - return pages; - } - - private PageSize pageSize() { - return pageSize; - } - - private int tableCount() { - return tableCount; - } - - private int drawingCount() { - return drawingCount; - } - } -} \ No newline at end of file diff --git a/minipdf-java/minipdf/src/main/java/io/github/minisoftware/minipdf/internal/docx/PoiDocxRenderer.java b/minipdf-java/minipdf/src/main/java/io/github/minisoftware/minipdf/internal/docx/PoiDocxRenderer.java deleted file mode 100644 index 6af0f6cf..00000000 --- a/minipdf-java/minipdf/src/main/java/io/github/minisoftware/minipdf/internal/docx/PoiDocxRenderer.java +++ /dev/null @@ -1,4964 +0,0 @@ -package io.github.minisoftware.minipdf.internal.docx; - -import io.github.minisoftware.minipdf.ConversionOptions; -import io.github.minisoftware.minipdf.MiniPdfException; -import io.github.minisoftware.minipdf.PageSize; -import io.github.minisoftware.minipdf.internal.SimplePdfTextRenderer; -import org.apache.pdfbox.pdmodel.PDDocument; -import org.apache.pdfbox.pdmodel.PDPage; -import org.apache.pdfbox.pdmodel.PDPageContentStream; -import org.apache.pdfbox.pdmodel.common.PDRectangle; -import org.apache.pdfbox.pdmodel.font.PDFont; -import org.apache.pdfbox.pdmodel.font.PDType0Font; -import org.apache.pdfbox.pdmodel.font.PDType1Font; -import org.apache.pdfbox.pdmodel.font.Standard14Fonts; -import org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject; -import org.apache.pdfbox.pdmodel.graphics.image.LosslessFactory; -import org.apache.poi.common.usermodel.fonts.FontInfo; -import org.apache.poi.hemf.usermodel.HemfPicture; -import org.apache.poi.sl.draw.DrawFontManager; -import org.apache.poi.sl.draw.DrawFontManagerDefault; -import org.apache.poi.sl.draw.Drawable; -import org.apache.poi.xwpf.usermodel.IBodyElement; -import org.apache.poi.xwpf.usermodel.LineSpacingRule; -import org.apache.poi.xwpf.usermodel.ParagraphAlignment; -import org.apache.poi.xwpf.usermodel.XWPFDocument; -import org.apache.poi.xwpf.usermodel.XWPFFooter; -import org.apache.poi.xwpf.usermodel.XWPFFootnote; -import org.apache.poi.xwpf.usermodel.XWPFHeader; -import org.apache.poi.xwpf.usermodel.XWPFNumbering; -import org.apache.poi.xwpf.usermodel.XWPFAbstractNum; -import org.apache.poi.xwpf.usermodel.XWPFParagraph; -import org.apache.poi.xwpf.usermodel.XWPFPicture; -import org.apache.poi.xwpf.usermodel.XWPFRun; -import org.apache.poi.xwpf.usermodel.XWPFStyle; -import org.apache.poi.xwpf.usermodel.XWPFStyles; -import org.apache.poi.xwpf.usermodel.XWPFTable; -import org.apache.poi.xwpf.usermodel.XWPFTableCell; -import org.apache.poi.xwpf.usermodel.XWPFTableRow; -import org.apache.poi.openxml4j.opc.PackagePart; -import org.apache.xmlbeans.XmlCursor; -import org.apache.xmlbeans.XmlObject; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTBody; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTBorder; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTOnOff; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTParaRPr; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTFonts; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTPageMar; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTPPr; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTRPr; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTSectPr; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTStyles; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTSpacing; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTSym; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTP; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.STLineSpacingRule; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.STDocGrid; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTStyle; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.STBorder; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTblBorders; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTblGridCol; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTcBorders; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTAbstractNum; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTLvl; -import org.w3c.dom.Document; -import org.w3c.dom.NamedNodeMap; -import org.w3c.dom.Node; -import org.w3c.dom.NodeList; - -import javax.xml.parsers.DocumentBuilderFactory; -import java.awt.Color; -import java.awt.Font; -import java.awt.Graphics2D; -import java.awt.geom.Rectangle2D; -import java.awt.image.BufferedImage; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.math.BigInteger; -import java.text.Normalizer; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Comparator; -import java.util.HashMap; -import java.util.HashSet; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.Set; -import java.util.regex.Matcher; -import java.util.regex.Pattern; -import java.util.stream.Collectors; - -final class PoiDocxRenderer { - private static final float DEFAULT_MARGIN = 54.0f; - private static final float DEFAULT_FONT_SIZE = 11.0f; - private static final float DEFAULT_TABLE_FONT_SIZE = 10.5f; - private static final float CELL_HORIZONTAL_PADDING = 5.4f; - private static final float CELL_VERTICAL_PADDING = 2.0f; - private static final float EMUS_PER_POINT = 12_700.0f; - private static final Pattern PAGE_FIELD = Pattern.compile("(?i)^PAGE(?:\\s|$)"); - private static final Pattern CACHED_PAGE_NUMBER = Pattern.compile("^(.*?)(\\d+)(.*)$"); - private static final AutoSpacing DEFAULT_AUTO_SPACING = new AutoSpacing(true, true); - // Per-render flags mirroring DocxToPdfConverter state: whether the - // document's default Latin font (Normal style) is Calibri-like, and - // whether it is a serif family. - private static final ThreadLocal CALIBRI_DEFAULT = new ThreadLocal<>(); - private static final ThreadLocal SERIF_DEFAULT = new ThreadLocal<>(); - - // Times-Roman (Times New Roman Regular) character widths for ASCII 32..126, - // sourced from Adobe Type 1 Times-Roman AFM (matches Times New Roman TTF - // advances within ~1 unit). Mirrors DocxToPdfConverter.TimesRomanWidths. - private static final int[] TIMES_ROMAN_WIDTHS = { - 250, 333, 408, 500, 500, 833, 778, 180, 333, 333, // ' ' to ) - 500, 564, 250, 333, 250, 278, // * to / - 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, // 0-9 - 278, 278, 564, 564, 564, 444, 921, // : to @ - 722, 667, 667, 722, 611, 556, 722, 722, 333, // A-I - 389, 722, 611, 889, 722, 722, 556, 722, 667, 556, // J-S - 611, 722, 722, 944, 722, 722, 611, // T-Z - 333, 278, 333, 469, 500, 333, // [ to ` - 444, 500, 444, 500, 444, 333, 500, 500, 278, // a-i - 278, 500, 278, 778, 500, 500, 500, 500, 333, 389, // j-s - 278, 500, 500, 722, 500, 500, 444, // t-z - 480, 200, 480, 541, // { to ~ - }; - - // Helvetica (Arial) character widths for ASCII 32..126 (per 1000 em). - // Mirrors DocxToPdfConverter.HelveticaWidths: the raw-width path for - // documents whose default font is not Calibri. - private static final int[] HELVETICA_WIDTHS = { - 278, 278, 355, 556, 556, 889, 667, 191, 333, 333, // ' ' to ) - 389, 584, 278, 333, 278, 278, // * to / - 556, 556, 556, 556, 556, 556, 556, 556, 556, 556, // 0-9 - 278, 278, 584, 584, 584, 556, 1015, // : to @ - 667, 667, 722, 722, 667, 611, 778, 722, 278, // A-I - 500, 667, 556, 833, 722, 778, 667, 778, 722, 667, // J-S - 611, 722, 667, 944, 667, 667, 611, // T-Z - 278, 278, 278, 469, 556, 333, // [ to ` - 556, 556, 500, 556, 556, 278, 556, 556, 222, // a-i - 222, 500, 222, 833, 556, 556, 556, 556, 333, 500, // j-s - 278, 556, 500, 722, 500, 500, 500, // t-z - 334, 260, 334, 584, // { to ~ - }; - - // Calibri Regular character widths for ASCII 32..126 (UPM=2048 scaled to - // 1000). Mirrors DocxToPdfConverter.CalibrWidths. - private static final int[] CALIBRI_WIDTHS = { - 226, 326, 401, 498, 507, 715, 682, 221, 303, 303, // ' ' to ) - 498, 498, 250, 306, 252, 386, // * to / - 507, 507, 507, 507, 507, 507, 507, 507, 507, 507, // 0-9 - 268, 268, 498, 498, 498, 463, 894, // : to @ - 579, 544, 533, 615, 488, 459, 631, 623, 252, // A-I - 319, 520, 420, 855, 646, 662, 517, 673, 543, 459, // J-S - 487, 642, 567, 890, 519, 487, 468, // T-Z - 307, 386, 307, 498, 498, 291, // [ to ` - 479, 525, 423, 525, 498, 305, 471, 525, 229, // a-i - 239, 455, 229, 799, 525, 527, 525, 525, 349, 391, // j-s - 335, 525, 452, 715, 433, 453, 395, // t-z - 314, 460, 314, 498, // { to ~ - }; - - private PoiDocxRenderer() { - } - - static byte[] render(byte[] input, ConversionOptions options, PageSize documentPageSize) - throws MiniPdfException { - PageSize pageSize = options.pageSize().orElse(documentPageSize); - try (XWPFDocument source = new XWPFDocument(new ByteArrayInputStream(input)); - PDDocument output = new PDDocument()) { - if (source.getBodyElements().stream() - .anyMatch(element -> !(element instanceof XWPFParagraph) - && !(element instanceof XWPFTable))) { - return null; - } - List> text = Collections.singletonList(source.getBodyElements().stream() - .map(element -> element instanceof XWPFTable - ? ((XWPFTable) element).getText() - : paragraphText((XWPFParagraph) element)) - .map(value -> value.replace('\n', ' ').replace('\t', ' ')) - .collect(Collectors.toList())); - // Mirror DocxReader.cs: choose the layout path from the document text, - // not from which font happens to load. CJK fonts (SimSun etc.) render - // Latin glyphs too, so a font-based check would misroute Latin documents - // into the CJK grid/margin path. Only actual East Asian characters - // (Han/Kana/Hangul slots) route into the CJK path — Latin documents - // with curly quotes, ligatures, or symbols (★) keep the Word - // paragraph layout (e.g. the OSCAR WARD letterhead). - boolean requiresCjkFont = text.stream() - .flatMap(List::stream) - .flatMapToInt(String::codePoints) - .anyMatch(PoiDocxRenderer::usesEastAsianFontSlot); - String[] themeLatin = themeLatinFonts(source); - String themeMajor = themeLatin[0] == null ? "" : themeLatin[0].toLowerCase(); - String defaultAsciiFamily = defaultFontFamily(source, XWPFRun.FontCharRange.ascii); - // When Normal does not pin a Latin font, Word falls back to the - // theme's minorFont (body) typeface, e.g. Franklin Gothic Book. - // CJK theme fonts (DengXian, SimSun...) must not replace it — - // those documents keep the CJK layout path. - if (defaultAsciiFamily == null) { - String minorFont = themeLatin[1]; - if (minorFont != null && !cjkFamilyName(minorFont.toLowerCase())) { - defaultAsciiFamily = minorFont; - } - } - String defaultFamily = defaultAsciiFamily == null ? "" : defaultAsciiFamily.toLowerCase(); - CALIBRI_DEFAULT.set(defaultFamily.contains("calibri")); - SERIF_DEFAULT.set(serifFamily(defaultFamily)); - List> paragraphText = Collections.singletonList(source.getParagraphs().stream() - .map(XWPFParagraph::getText) - .collect(Collectors.toList())); - List> latinText = Collections.singletonList(paragraphText.get(0).stream() - .map(PoiDocxRenderer::latinText) - .collect(Collectors.toList())); - // Office ships Franklin Gothic Book (FRABK.TTF) and Demi - // (FRADM.TTF); use them when the theme asks for them so headings - // and body text render with the same faces as Word. - PDFont franklinBook = null; - PDFont franklinDemi = null; - if (defaultFamily.contains("franklin")) { - franklinDemi = SimplePdfTextRenderer.loadSystemFont( - output, latinText, "fradm.ttf"); - franklinBook = SimplePdfTextRenderer.loadSystemFont( - output, latinText, "frabk.ttf", "framd.ttf"); - } - // Microsoft 365 letterhead themes request Impact (major) and - // Source Sans Pro (minor) — cloud fonts cached under - // %LOCALAPPDATA%\Microsoft\FontCache, not in C:\Windows\Fonts. - // Load them by family so headings and body text use the same - // faces as Word (mirrors PdfWriter.FindOfficeCloudFontByPreferredName). - PDFont impact = themeMajor.contains("impact") - ? SimplePdfTextRenderer.loadSystemFontByFamily(output, text, "Impact") - : null; - PDFont sourceSans = defaultFamily.contains("source sans pro") - ? SimplePdfTextRenderer.loadSystemFontByFamily(output, text, "Source Sans Pro") - : null; - PDFont sourceSansBold = defaultFamily.contains("source sans pro") - ? SimplePdfTextRenderer.loadSystemFontByFamily(output, text, "Source Sans Pro Bold") - : null; - PDFont font = requiresCjkFont ? SimplePdfTextRenderer.loadFont(output, text) : null; - boolean usesDocumentLatinFont = false; - if (font == null) { - font = loadDocumentLatinFont(output, text, defaultAsciiFamily); - usesDocumentLatinFont = font != null; - } - if (font == null) { - // Latin documents whose text contains symbols that the Latin - // fallback faces cannot encode (★, ☺, …) would otherwise drop - // to the plain-text renderer and lose all formatting. Fall - // back to the registered/CJK font chain so the document still - // renders through the CJK layout path, exactly like the - // pre-cloud-font behavior. - font = SimplePdfTextRenderer.loadFont(output, text); - } - if (font == null && franklinBook != null) { - font = franklinBook; - usesDocumentLatinFont = true; - } - if (font == null && text.stream().flatMap(List::stream) - .flatMapToInt(String::codePoints).allMatch(codePoint -> codePoint <= 255)) { - font = new PDType1Font(Standard14Fonts.FontName.HELVETICA); - } - if (font == null) { - return null; - } - // Load a bold face matching the document script: CJK documents use - // SimSun/Microsoft YaHei Bold, Latin documents use Times/Arial Bold. - // Loading SimSun Bold first misroutes Latin bold runs (Times) into a - // CJK face, whose half-width Latin glyphs distort wrap widths. - PDFont boldFont = requiresCjkFont || !usesDocumentLatinFont - ? SimplePdfTextRenderer.loadSystemFont( - output, text, "simsunb.ttf", "msyhbd.ttc", "NotoSansCJK-Bold.ttc") - : SimplePdfTextRenderer.loadSystemFont( - output, text, "timesbd.ttf", "arialbd.ttf", "simsunb.ttf", "msyhbd.ttc"); - if (boldFont == null) { - boldFont = font; - } - if (franklinDemi != null) { - boldFont = franklinDemi; - } - if (sourceSansBold != null) { - boldFont = sourceSansBold; - } - PDFont paragraphFont = SimplePdfTextRenderer.loadSystemFont( - output, - paragraphText, - "simhei.ttf", - "msyh.ttc", - "NotoSansCJK-Regular.ttc"); - if (paragraphFont == null) { - paragraphFont = font; - } - PDFont timesFont = SimplePdfTextRenderer.loadSystemFont( - output, - latinText, - "times.ttf"); - if (timesFont == null) { - timesFont = font; - } - PDFont arialFont = SimplePdfTextRenderer.loadSystemFont( - output, - latinText, - "arial.ttf"); - if (arialFont == null) { - arialFont = timesFont; - } - PDFont kaiFont = SimplePdfTextRenderer.loadSystemFont( - output, - paragraphText, - "simkai.ttf"); - PDFont fangSongFont = SimplePdfTextRenderer.loadSystemFont( - output, - paragraphText, - "simfang.ttf"); - ParagraphFonts paragraphFonts = new ParagraphFonts( - paragraphFont, - font, - paragraphFont, - kaiFont == null ? paragraphFont : kaiFont, - fangSongFont == null ? paragraphFont : fangSongFont, - timesFont, - arialFont, - franklinBook, - franklinDemi, - impact, - sourceSans, - defaultAsciiFamily, - defaultFontFamily(source, XWPFRun.FontCharRange.eastAsia)); - - boolean landscape = pageSize.width() > pageSize.height(); - PageMargins margins = pageMargins( - source, DEFAULT_MARGIN, landscape, usesDocumentLatinFont); - float linePitch = documentLinePitch(source); - PageNumberFooter pageNumberFooter = pageNumberFooter(source); - // Header parts render their behindDoc anchored shapes (e.g. - // full-page border frames) on every page, behind the body text. - List headerParagraphs = new ArrayList<>(); - for (XWPFHeader header : source.getHeaderList()) { - headerParagraphs.addAll(header.getParagraphs()); - } - PageContext context = new PageContext( - output, - pageSize, - margins.left(), - margins.top(), - margins.bottom(), - linePitch, - margins.firstPageTopOffset(), - pageNumberFooter == null ? null : timesFont, - pageNumberFooter, - pageFooterDistance(source, margins.bottom()), - footnotes(source, timesFont), - themeColors(source), - headerParagraphs); - // Pre-process contextualSpacing the way Word does: between two - // consecutive paragraphs of the same style, when either has - // contextualSpacing, the first paragraph's spacing-after collapses. - Set suppressContextualAfter = new HashSet<>(); - List bodyElements = source.getBodyElements(); - for (int index = 0; index < bodyElements.size() - 1; index++) { - if (!(bodyElements.get(index) instanceof XWPFParagraph) - || !(bodyElements.get(index + 1) instanceof XWPFParagraph)) { - continue; - } - XWPFParagraph current = (XWPFParagraph) bodyElements.get(index); - XWPFParagraph next = (XWPFParagraph) bodyElements.get(index + 1); - String currentStyle = current.getStyle(); - if (currentStyle != null - && currentStyle.equals(next.getStyle()) - && (paragraphContextualSpacing(current) || paragraphContextualSpacing(next)) - && effectiveSpacing(current).after() > 0.0) { - suppressContextualAfter.add(current); - } - } - for (int index = 0; index < bodyElements.size(); index++) { - IBodyElement element = bodyElements.get(index); - if (element instanceof XWPFParagraph) { - XWPFParagraph paragraph = (XWPFParagraph) element; - IBodyElement next = index + 1 < bodyElements.size() - ? bodyElements.get(index + 1) - : null; - if (next instanceof XWPFParagraph - && usesDocumentLatinFont - && paragraphKeepNext(paragraph)) { - // keepNext: prevent an orphaned heading at the bottom - // of a page. Word keeps the heading together with the - // following paragraph's first lines (widow/orphan - // control), so reserve the heading plus up to three - // follow lines. - XWPFParagraph follow = (XWPFParagraph) next; - float headingFontSize = paragraphFontSize(paragraph, DEFAULT_FONT_SIZE); - float headingLineHeight = paragraphLineHeight( - paragraph, headingFontSize, headingFontSize * 1.2f, linePitch, - usesDocumentLatinFont, false, - wrappingFont(paragraphFonts, paragraphText(paragraph))); - float headingSpacingBefore = usesDocumentLatinFont - ? twipsToPoints(effectiveSpacing(paragraph).before()) - : twipsToPoints(paragraph.getSpacingBefore()); - float followFontSize = paragraphFontSize(follow, DEFAULT_FONT_SIZE); - String followText = paragraphText(follow); - PDFont followFont = wrappingFont(paragraphFonts, followText); - float followLineHeight = paragraphLineHeight( - follow, followFontSize, followFontSize * 1.2f, linePitch, - usesDocumentLatinFont, false, followFont); - int followLines = wrap( - followFont, - followText.replace('\t', ' '), - followFontSize, - context.pageSize.width() - context.margin * 2.0f).size(); - float needed = headingSpacingBefore + headingLineHeight - + Math.min(followLines, 3) * followLineHeight; - context.keepNextBeforeParagraph(needed); - } - renderParagraph( - context, - paragraph, - paragraphFonts, - usesDocumentLatinFont ? boldFont : null, - usesDocumentLatinFont, - suppressContextualAfter.contains(paragraph)); - } else if (element instanceof XWPFTable) { - XWPFTable table = (XWPFTable) element; - renderTable(context, table, paragraphFonts, boldFont, source); - } - } - context.close(); - ByteArrayOutputStream bytes = new ByteArrayOutputStream(); - output.save(bytes); - return bytes.toByteArray(); - } catch (IOException | RuntimeException exception) { - throw new MiniPdfException( - MiniPdfException.Kind.IO, - "failed to render structured DOCX: " + exception.getMessage(), - exception); - } finally { - CALIBRI_DEFAULT.remove(); - SERIF_DEFAULT.remove(); - } - } - - private static void renderParagraph( - PageContext context, - XWPFParagraph paragraph, - ParagraphFonts fonts, - PDFont boldFont, - boolean useWordParagraphLayout, - boolean suppressContextualAfter) - throws IOException { - context.registerFootnotes(paragraph); - boolean alignCheckboxLabels = context.consumeCheckboxLabelAlignment(); - boolean topOfPage = context.consumeTopOfPage(); - // Paragraphs that only host behindDoc anchored shapes are positioned - // absolutely and consume no flow space (mirrors the .NET - // isShapeOnlyParagraph behavior — Word keeps such paragraph marks - // from pushing following content down). - if (isShapeOnlyParagraph(paragraph)) { - renderAnchoredBehindDocShapes(context, paragraph); - return; - } - // An empty paragraph that ends a section only carries an invisible - // paragraph mark: Word places the break after it without pushing - // content onto a fresh page first, so don't consume a line. - if (startsNewSection(paragraph) - && paragraph.getRuns().stream().allMatch(run -> run.text().isEmpty()) - && floatingCheckboxes(paragraph).isEmpty()) { - context.newPage(); - return; - } - float fontSize = paragraphFontSize(paragraph, DEFAULT_FONT_SIZE); - float spacingBefore = useWordParagraphLayout - ? twipsToPoints(effectiveSpacing(paragraph).before()) - : twipsToPoints(paragraph.getSpacingBefore()); - if (useWordParagraphLayout) { - // Word suppresses spacing-before at the top of a page. - if (!topOfPage) { - context.moveToParagraph(spacingBefore); - } - } else { - if (!topOfPage) { - context.moveDown(spacingBefore); - } - } - float paragraphTop = context.y; - String bullet = paragraphBullet(paragraph); - String text = alignCheckboxLabels - ? paragraphText(paragraph) - : renderableText(paragraphText(paragraph)); - if (bullet != null) { - text = bullet + " " + text; - } - float leftIndent = indentationToPoints(paragraph.getIndentationLeft()); - float rightIndent = indentationToPoints(paragraph.getIndentationRight()); - float firstLineIndent = useWordParagraphLayout - ? indentationToPoints(paragraph.getIndentationFirstLine()) - - indentationToPoints(paragraph.getIndentationHanging()) - : 0.0f; - float availableWidth = context.pageSize.width() - context.margin * 2.0f - leftIndent - rightIndent; - float firstLineWidth = availableWidth - firstLineIndent; - AutoSpacing autoSpacing = paragraphAutoSpacing(paragraph); - List segments = paragraphSegments( - paragraph, fonts, fontSize, boldFont, alignCheckboxLabels); - if (bullet != null && !segments.isEmpty()) { - for (int index = 0; index < segments.size(); index++) { - RunSegment first = segments.get(index); - if (!first.tab()) { - segments.set(index, first.prepend(bullet + " ")); - break; - } - } - } - float segmentWidth = 0.0f; - for (RunSegment segment : segments) { - if (segment.tab()) { - segmentWidth = nextDefaultTabStop(segmentWidth); - continue; - } - segmentWidth += segment.leadingSpacing() - + textWidth(segment.font(), segment.text(), segment.fontSize(), autoSpacing, segment.bold()); - } - // Mirror DocxToPdfConverter: center/right alignment positions text with - // the actual font advances (measured width), not the wrap estimate. - float actualSegmentWidth = 0.0f; - for (RunSegment segment : segments) { - if (segment.tab()) { - actualSegmentWidth = nextDefaultTabStop(actualSegmentWidth); - continue; - } - actualSegmentWidth += segment.leadingSpacing() - + segment.font().getStringWidth(segment.text()) / 1000.0f * segment.fontSize(); - } - boolean hasPictures = paragraph.getRuns().stream() - .anyMatch(run -> !run.getEmbeddedPictures().isEmpty()); - // Picture-only paragraphs (e.g. an inline EMF signature under - // "Warm regards,"): the image itself advances the flow, mirroring - // DocxToPdfConverter — the empty paragraph mark must not add an - // extra text line on top of the image height. - if (segments.isEmpty() && hasPictures) { - renderPictureOnlyParagraph(context, paragraph, fontSize, leftIndent, topOfPage); - renderFloatingCheckboxes(context, paragraph, paragraphTop); - finishParagraph(context, paragraph, useWordParagraphLayout, suppressContextualAfter); - if (startsNewSection(paragraph)) { - context.newPage(); - } - return; - } - if (!segments.isEmpty() - && !hasPictures - && segments.stream().map(RunSegment::text).reduce("", String::concat).equals(text) - && segmentWidth <= firstLineWidth) { - float maxFontSize = segments.stream() - .map(RunSegment::fontSize) - .max(Float::compare) - .orElse(fontSize); - RunSegment tallest = segments.stream() - .max(Comparator.comparing(RunSegment::fontSize)) - .orElse(null); - float naturalLineHeight = maxFontSize * 1.2f; - float lineHeight = paragraphLineHeight( - paragraph, maxFontSize, naturalLineHeight, context.linePitch, - useWordParagraphLayout, bullet != null, - tallest == null ? null : tallest.font()); - context.ensureSpace(lineHeight); - float leading = Math.max(0.0f, lineHeight - naturalLineHeight) / 2.0f; - float firstBaselineOffset = maxFontSize; - if (topOfPage) { - if (tallest != null) { - firstBaselineOffset = maxFontSize * fontAscentRatio(tallest.font()); - } - } - float baseline = context.y - leading - firstBaselineOffset; - float x = context.margin + leftIndent + firstLineIndent; - if (paragraph.getAlignment() == ParagraphAlignment.CENTER) { - x = centeredTextX( - context.pageSize.width(), leftIndent + firstLineIndent, rightIndent, actualSegmentWidth); - } else if (paragraph.getAlignment() == ParagraphAlignment.RIGHT) { - x = context.pageSize.width() - context.margin - rightIndent - actualSegmentWidth; - } - for (RunSegment segment : segments) { - if (segment.tab()) { - x = context.margin + leftIndent + firstLineIndent - + nextDefaultTabStop(x - context.margin - leftIndent - firstLineIndent); - continue; - } - x += segment.leadingSpacing(); - drawRunHighlight( - context.content, - segment.highlight(), - x, - baseline, - textWidth(segment.font(), segment.text(), segment.fontSize(), autoSpacing), - segment.fontSize()); - applyTextColor(context.content, segment.color()); - showText( - context.content, - segment.font(), - segment.fontSize(), - segment.text(), - x, - baseline, - autoSpacing); - x += textWidth(segment.font(), segment.text(), segment.fontSize(), autoSpacing); - } - context.content.setNonStrokingColor(0.0f, 0.0f, 0.0f); - renderFloatingCheckboxes(context, paragraph, paragraphTop); - context.y -= lineHeight; - finishParagraph(context, paragraph, useWordParagraphLayout, suppressContextualAfter); - if (startsNewSection(paragraph)) { - context.newPage(); - } - return; - } - PDFont font = wrappingFont(fonts, text); - // Mirrors DocxReader: a wrapped paragraph renders with the first - // explicit run color, falling back to the paragraph style color - // (e.g. the Heading2 4F81BD blue). - String paragraphColor = paragraphStyleColor(paragraph); - if (paragraphColor == null) { - for (XWPFRun run : paragraph.getRuns()) { - paragraphColor = runColor(run); - if (paragraphColor != null) { - break; - } - } - } - // Calibrated wrap widths already match Word/LibreOffice metrics, so no - // extra per-line tolerance is needed. The old fontSize tolerance let - // bold headings like "A Novel Approach to Document Conversion" fit on a - // single line and collapse pagination. - float wrapTolerance = 0.0f; - boolean paragraphBold = paragraph.getRuns().stream() - .anyMatch(run -> !run.text().isEmpty() && run.isBold()); - List lines = wrap( - font, - text.replace('\t', ' '), - fontSize, - firstLineWidth + wrapTolerance, - availableWidth + wrapTolerance, - autoSpacing, - paragraphBold); - float lineHeight = paragraphLineHeight( - paragraph, fontSize, fontSize * 1.2f, context.linePitch, useWordParagraphLayout, - bullet != null, font); - if (useWordParagraphLayout) { - context.avoidWidowOrphanSplit(lineHeight, lines.size()); - } - float firstBaseline = 0.0f; - applyTextColor(context.content, paragraphColor); - for (int index = 0; index < lines.size(); index++) { - context.ensureSpace(lineHeight); - if (index == 0) { - // behindDoc anchored drawing shapes (e.g. a full-page sidebar or - // decorative freeforms) render at absolute page positions on the - // anchor paragraph's page, before the following content. - renderAnchoredBehindDocShapes(context, paragraph); - } - float baseline = context.y - (topOfPage && index == 0 - ? fontSize * fontAscentRatio(font) - : fontSize); - if (index == 0) { - firstBaseline = baseline; - } - String line = lines.get(index); - float estimatedWidth = textWidth(font, line, fontSize, autoSpacing); - float width = paragraph.getAlignment() == ParagraphAlignment.CENTER - || paragraph.getAlignment() == ParagraphAlignment.RIGHT - ? font.getStringWidth(line) / 1000.0f * fontSize - : estimatedWidth; - float lineLeftIndent = index == 0 ? leftIndent + firstLineIndent : leftIndent; - float lineWidth = index == 0 ? firstLineWidth : availableWidth; - float x = context.margin + lineLeftIndent; - if (paragraph.getAlignment() == ParagraphAlignment.CENTER) { - x = centeredTextX(context.pageSize.width(), lineLeftIndent, rightIndent, width); - } else if (paragraph.getAlignment() == ParagraphAlignment.RIGHT) { - x = context.pageSize.width() - context.margin - rightIndent - width; - } - float wordSpacing = paragraph.getAlignment() == ParagraphAlignment.BOTH - && useWordParagraphLayout - && index < lines.size() - 1 - ? justifiedWordSpacing(line, estimatedWidth, lineWidth) - : 0.0f; - showText(context.content, font, fontSize, line, x, baseline, autoSpacing, wordSpacing); - context.y -= lineHeight; - } - context.content.setNonStrokingColor(0.0f, 0.0f, 0.0f); - renderPictures(context, paragraph, firstBaseline); - renderFloatingCheckboxes(context, paragraph, paragraphTop); - finishParagraph(context, paragraph, useWordParagraphLayout, suppressContextualAfter); - if (startsNewSection(paragraph)) { - context.newPage(); - } - } - - private static void finishParagraph( - PageContext context, - XWPFParagraph paragraph, - boolean useWordParagraphLayout, - boolean suppressContextualAfter) throws IOException { - float spacingAfter = suppressContextualAfter - ? 0.0f - : useWordParagraphLayout - ? twipsToPoints(effectiveSpacing(paragraph).after()) - : twipsToPoints(paragraph.getSpacingAfter()); - if (useWordParagraphLayout) { - context.finishParagraph(spacingAfter); - } else { - context.moveDown(spacingAfter); - } - } - - private static boolean startsNewSection(XWPFParagraph paragraph) { - if (!paragraph.getCTP().isSetPPr() || !paragraph.getCTP().getPPr().isSetSectPr()) { - return false; - } - CTSectPr section = paragraph.getCTP().getPPr().getSectPr(); - return !section.isSetType() - || section.getType().getVal() == null - || !"continuous".equals(section.getType().getVal().toString()); - } - - private static void renderPictureOnlyParagraph( - PageContext context, - XWPFParagraph paragraph, - float fontSize, - float leftIndent, - boolean topOfPage) throws IOException { - // behindDoc anchored shapes on the anchor paragraph's page render - // before the paragraph's images, mirroring the wrap-path flow. - renderAnchoredBehindDocShapes(context, paragraph); - ParagraphAlignment alignment = paragraph.getAlignment(); - for (XWPFRun run : paragraph.getRuns()) { - for (XWPFPicture picture : run.getEmbeddedPictures()) { - if (picture.getPictureData() == null || pictureAnchored(picture)) { - continue; - } - // XWPFPicture#getWidth/getDepth already return points. - float width = (float) picture.getWidth(); - float height = (float) picture.getDepth(); - if (width < 1.0f || height < 1.0f) { - width = 52.0f; - height = 32.0f; - } - // Word keeps an inline image intact rather than clipping it - // at the bottom of the page (mirrors RenderImage in - // DocxToPdfConverter). - if (!topOfPage) { - context.ensureSpace(height + 1.0f); - } - float x = context.margin + leftIndent; - if (alignment == ParagraphAlignment.CENTER) { - x = context.margin + leftIndent - + (context.pageSize.width() - context.margin * 2.0f - width) / 2.0f; - } else if (alignment == ParagraphAlignment.RIGHT) { - x = context.pageSize.width() - context.margin - width; - } - // Word aligns the inline image top with the paragraph's line - // top: the flow cursor IS the image top, so the image bottom - // sits one image height below it. The old extra fontSize*0.8 - // offset pushed signatures like OSCAR WARD ~19pt below Word. - float bottom = context.y - height; - float[] crop = pictureCrop(picture); - PDImageXObject image = decodePicture(context, picture, crop); - if (image != null) { - context.content.drawImage(image, x, bottom, width, height); - } - context.y -= height + 1.0f; - } - } - } - - private static void renderPictures(PageContext context, XWPFParagraph paragraph, float baseline) - throws IOException { - for (XWPFRun run : paragraph.getRuns()) { - for (XWPFPicture picture : run.getEmbeddedPictures()) { - if (picture.getPictureData() == null) { - continue; - } - // XWPFPicture#getWidth/getDepth already return points. - float width = (float) picture.getWidth(); - float height = (float) picture.getDepth(); - if (width < 1.0f || height < 1.0f) { - width = 52.0f; - height = 32.0f; - } - PDImageXObject image = decodePicture(context, picture, pictureCrop(picture)); - if (image == null) { - continue; - } - float marginLeft = stylePoints(run.getCTR().xmlText(), "margin-left"); - float x = Float.isNaN(marginLeft) - ? context.pageSize.width() - context.margin - width - : context.margin + marginLeft + 7.0f; - context.content.drawImage(image, x, baseline - height * 0.15f - 7.0f, width, height); - } - } - } - - /** - * Decodes picture data into a PDF image, rasterizing vector EMF/WMF - * signatures the way DocxToPdfConverter.TryConvertMetafileToPng does: - * the metafile canvas is rendered at the cropped aspect ratio, then the - * srcRect crop is applied in canvas space. - */ - private static PDImageXObject decodePicture(PageContext context, XWPFPicture picture, float[] crop) - throws IOException { - byte[] data = picture.getPictureData().getData(); - if (isEmfPicture(picture)) { - BufferedImage raster = rasterizeEmf(data, crop); - if (raster != null) { - return LosslessFactory.createFromImage(context.document, raster); - } - } - try { - return PDImageXObject.createFromByteArray(context.document, data, picture.getDescription()); - } catch (IOException | IllegalArgumentException exception) { - return null; - } - } - - private static boolean isEmfPicture(XWPFPicture picture) { - String name = null; - try { - name = picture.getPictureData().getFileName(); - if (name == null || name.isEmpty()) { - name = picture.getPictureData().getPackagePart().getPartName().getName(); - } - } catch (RuntimeException ignored) { - // The part may be unavailable; fall through to the byte signature. - } - if (name != null) { - String lower = name.toLowerCase(Locale.ROOT); - if (lower.endsWith(".emf") || lower.endsWith(".wmf")) { - return true; - } - } - byte[] data = picture.getPictureData().getData(); - return data != null && data.length >= 4 - && (data[0] == 1 && data[1] == 0 && data[2] == 0 && data[3] == 0 - || (data[0] & 0xff) == 0xd7 && (data[1] & 0xff) == 0xcd); - } - - private static BufferedImage rasterizeEmf(byte[] data, float[] crop) { - try { - HemfPicture emf = new HemfPicture(new ByteArrayInputStream(data)); - Rectangle2D bounds = emf.getBounds(); - double canvasW = bounds.getWidth(); - double canvasH = bounds.getHeight(); - if (canvasW <= 0.0 || canvasH <= 0.0) { - return null; - } - double keptW = canvasW * (1.0 - crop[0] - crop[2]); - double keptH = canvasH * (1.0 - crop[1] - crop[3]); - if (keptW <= 0.0 || keptH <= 0.0) { - return null; - } - boolean hasCrop = crop[0] > 0.0f || crop[1] > 0.0f || crop[2] > 0.0f || crop[3] > 0.0f; - if (!hasCrop) { - // No srcRect: the whole canvas stretches into the picture - // extent, exactly like Word. - int fullWidth = Math.max(1, (int) Math.round(512.0 * canvasW / canvasH)); - int fullHeight = 512; - if (fullWidth > 4096) { - fullWidth = 4096; - fullHeight = Math.max(1, (int) Math.round(4096.0 * canvasH / canvasW)); - } - return renderEmfCanvas(emf, fullWidth, fullHeight); - } - int rasterWidth = Math.max(1, (int) Math.round(512.0 * keptW / keptH)); - int rasterHeight = 512; - if (rasterWidth > 4096) { - rasterWidth = 4096; - rasterHeight = Math.max(1, (int) Math.round(4096.0 * keptH / keptW)); - } - BufferedImage canvas = renderEmfCanvas(emf, rasterWidth, rasterHeight); - // The spec crop is authored for the EMF's own font metrics. A - // substituted script face (Segoe Script for Cochocib Script) can - // be wider, so expand the kept box to the rendered ink bounds to - // avoid clipping the signature tail. Content fully inside the - // spec crop is unaffected. - int[] ink = inkBounds(canvas); - if (ink == null) { - return canvas; - } - int specX0 = (int) Math.round(rasterWidth * crop[0]); - int specY0 = (int) Math.round(rasterHeight * crop[1]); - int specX1 = rasterWidth - (int) Math.round(rasterWidth * crop[2]); - int specY1 = rasterHeight - (int) Math.round(rasterHeight * crop[3]); - int cropX0 = Math.min(specX0, ink[0]); - int cropY0 = Math.min(specY0, ink[1]); - int cropX1 = Math.max(specX1, ink[2]); - int cropY1 = Math.max(specY1, ink[3]); - cropX0 = Math.max(0, Math.min(cropX0, rasterWidth - 1)); - cropY0 = Math.max(0, Math.min(cropY0, rasterHeight - 1)); - cropX1 = Math.max(cropX0 + 1, Math.min(cropX1, rasterWidth)); - cropY1 = Math.max(cropY0 + 1, Math.min(cropY1, rasterHeight)); - if (cropX0 == specX0 && cropY0 == specY0 && cropX1 == specX1 && cropY1 == specY1) { - return canvas.getSubimage(cropX0, cropY0, cropX1 - cropX0, cropY1 - cropY0); - } - // Re-render at the expanded box aspect so the cropped raster keeps - // the glyph proportions when stretched into the picture extent. - int expandedWidth = Math.max(1, (int) Math.round(512.0 * (cropX1 - cropX0) / (cropY1 - cropY0))); - int expandedHeight = 512; - if (expandedWidth > 4096) { - expandedWidth = 4096; - expandedHeight = Math.max(1, (int) Math.round(4096.0 * (cropY1 - cropY0) / (cropX1 - cropX0))); - } - BufferedImage reraster = renderEmfCanvas(emf, expandedWidth, expandedHeight); - int rerasterX0 = (int) Math.round(expandedWidth * cropX0 / (double) rasterWidth); - int rerasterY0 = (int) Math.round(expandedHeight * cropY0 / (double) rasterHeight); - int rerasterX1 = (int) Math.round(expandedWidth * cropX1 / (double) rasterWidth); - int rerasterY1 = (int) Math.round(expandedHeight * cropY1 / (double) rasterHeight); - rerasterX1 = Math.max(rerasterX0 + 1, Math.min(rerasterX1, expandedWidth)); - rerasterY1 = Math.max(rerasterY0 + 1, Math.min(rerasterY1, expandedHeight)); - return reraster.getSubimage(rerasterX0, rerasterY0, rerasterX1 - rerasterX0, rerasterY1 - rerasterY0); - } catch (RuntimeException exception) { - return null; - } - } - - private static BufferedImage renderEmfCanvas(HemfPicture emf, int width, int height) { - BufferedImage canvas = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); - Graphics2D graphics = canvas.createGraphics(); - try { - graphics.setColor(Color.WHITE); - graphics.fillRect(0, 0, width, height); - // Script/signature faces (e.g. "Cochocib Script Latin Pro") - // rarely exist on the system; map them to Segoe Script the - // way LibreOffice substitutes SegoeScript for such EMFs. - graphics.setRenderingHint(Drawable.FONT_HANDLER, SCRIPT_FONT_MAPPER); - emf.draw(graphics, new Rectangle2D.Double(0.0, 0.0, width, height)); - } finally { - graphics.dispose(); - } - return canvas; - } - - /** - * Returns the bounding box {x0, y0, x1, y1} of non-white pixels, or null - * when the canvas is empty. - */ - private static int[] inkBounds(BufferedImage canvas) { - int minX = Integer.MAX_VALUE; - int minY = Integer.MAX_VALUE; - int maxX = -1; - int maxY = -1; - int width = canvas.getWidth(); - int height = canvas.getHeight(); - for (int y = 0; y < height; y++) { - for (int x = 0; x < width; x++) { - int rgb = canvas.getRGB(x, y); - int alpha = (rgb >>> 24) & 0xff; - int red = (rgb >>> 16) & 0xff; - int green = (rgb >>> 8) & 0xff; - int blue = rgb & 0xff; - if (alpha > 0 && (red < 245 || green < 245 || blue < 245)) { - if (x < minX) { - minX = x; - } - if (y < minY) { - minY = y; - } - if (x > maxX) { - maxX = x; - } - if (y > maxY) { - maxY = y; - } - } - } - } - return maxX < 0 ? null : new int[] {minX, minY, maxX + 1, maxY + 1}; - } - - /** - * Parses a:srcRect crop percentages (1/1000th of a percent per the - * OOXML spec) into l/t/r/b fractions, mirroring LibreOffice's - * CropQuotientsFromSrcRect. - */ - private static float[] pictureCrop(XWPFPicture picture) { - float[] crop = new float[4]; - Node dom = picture.getCTPicture().getDomNode(); - Node blipFill = firstDescendant(dom, "blipFill"); - Node srcRect = blipFill == null ? null : directChild(blipFill, "srcRect"); - if (srcRect == null) { - return crop; - } - crop[0] = attributeFraction(srcRect, "l"); - crop[1] = attributeFraction(srcRect, "t"); - crop[2] = attributeFraction(srcRect, "r"); - crop[3] = attributeFraction(srcRect, "b"); - return crop; - } - - private static float attributeFraction(Node node, String localName) { - String value = attribute(node, localName); - if (value == null || value.isEmpty()) { - return 0.0f; - } - try { - return Float.parseFloat(value) / 100_000.0f; - } catch (NumberFormatException ignored) { - return 0.0f; - } - } - - private static boolean pictureAnchored(XWPFPicture picture) { - Node node = picture.getCTPicture().getDomNode(); - while (node != null) { - if ("anchor".equals(node.getLocalName())) { - return true; - } - if ("inline".equals(node.getLocalName())) { - return false; - } - node = node.getParentNode(); - } - return false; - } - - /** - * Maps EMF script faces to the installed Segoe Script family so vector - * signatures render as handwriting instead of a generic sans font. All - * other fonts delegate to POI's default mapping. - */ - private static final DrawFontManager SCRIPT_FONT_MAPPER = new DrawFontManager() { - private final DrawFontManager delegate = new DrawFontManagerDefault(); - - @Override - public FontInfo getMappedFont(Graphics2D graphics, FontInfo fontInfo) { - String typeface = fontInfo.getTypeface(); - if (typeface != null) { - String lower = typeface.toLowerCase(Locale.ROOT); - if (lower.contains("script") || lower.contains("cochocib")) { - return fontInfo("Segoe Script"); - } - } - return delegate.getMappedFont(graphics, fontInfo); - } - - @Override - public FontInfo getFallbackFont(Graphics2D graphics, FontInfo fontInfo) { - return delegate.getFallbackFont(graphics, fontInfo); - } - - @Override - public String mapFontCharset(Graphics2D graphics, FontInfo fontInfo, String text) { - return delegate.mapFontCharset(graphics, fontInfo, text); - } - - @Override - public Font createAWTFont( - Graphics2D graphics, - FontInfo fontInfo, - double size, - boolean bold, - boolean italic) { - return delegate.createAWTFont(graphics, fontInfo, size, bold, italic); - } - }; - - private static FontInfo fontInfo(String typeface) { - return new FontInfo() { - @Override - public String getTypeface() { - return typeface; - } - }; - } - - private static void renderFloatingCheckboxes( - PageContext context, - XWPFParagraph paragraph, - float paragraphTop) throws IOException { - List checkboxes = floatingCheckboxes(paragraph); - for (FloatingCheckbox checkbox : checkboxes) { - float x = "column".equals(checkbox.horizontalRelative) - ? context.margin + checkbox.offsetX - : checkbox.offsetX; - float top = paragraphTop - checkbox.offsetY; - float bottom = top - checkbox.height; - float right = x + checkbox.width; - context.content.setStrokingColor(0, 0, 0); - context.content.setLineWidth(checkbox.lineWidth); - context.content.addRect(x, bottom, checkbox.width, checkbox.height); - context.content.stroke(); - if (checkbox.checked) { - context.content.setLineWidth(Math.max(0.8f, checkbox.lineWidth * 1.6f)); - context.content.moveTo(x + checkbox.width * 0.20f, bottom + checkbox.height * 0.52f); - context.content.lineTo(x + checkbox.width * 0.40f, bottom + checkbox.height * 0.25f); - context.content.lineTo(right - checkbox.width * 0.16f, top - checkbox.height * 0.18f); - context.content.stroke(); - } - } - if (!checkboxes.isEmpty()) { - context.expectCheckboxLabelAlignment(); - } - } - - static List floatingCheckboxes(XWPFParagraph paragraph) { - List checkboxes = new ArrayList<>(); - collectFloatingCheckboxes(paragraph.getCTP().getDomNode(), checkboxes); - return checkboxes; - } - - private static void collectFloatingCheckboxes(Node node, List checkboxes) { - if ("anchor".equals(node.getLocalName()) && firstDescendant(node, "txbxContent") != null) { - Node positionH = directChild(node, "positionH"); - Node positionV = directChild(node, "positionV"); - Node extent = directChild(node, "extent"); - if (positionH != null && extent != null) { - Node offset = directChild(positionH, "posOffset"); - float offsetX = emuToPoints(nodeText(offset)); - Node verticalOffset = directChild(positionV, "posOffset"); - float offsetY = emuToPoints(nodeText(verticalOffset)); - float width = emuToPoints(attribute(extent, "cx")); - float height = emuToPoints(attribute(extent, "cy")); - Node line = firstDescendant(node, "ln"); - float lineWidth = Math.max(0.5f, emuToPoints(attribute(line, "w"))); - if (width > 0.0f && height > 0.0f) { - checkboxes.add(new FloatingCheckbox( - offsetX, - offsetY, - width, - height, - lineWidth, - attribute(positionH, "relativeFrom"), - containsWingdingsCheck(firstDescendant(node, "txbxContent")))); - } - } - return; - } - NodeList children = node.getChildNodes(); - for (int index = 0; index < children.getLength(); index++) { - collectFloatingCheckboxes(children.item(index), checkboxes); - } - } - - private static boolean containsWingdingsCheck(Node node) { - if (node == null) { - return false; - } - if ("sym".equals(node.getLocalName()) - && "Wingdings".equalsIgnoreCase(attribute(node, "font")) - && "F0FC".equalsIgnoreCase(attribute(node, "char"))) { - return true; - } - NodeList children = node.getChildNodes(); - for (int index = 0; index < children.getLength(); index++) { - if (containsWingdingsCheck(children.item(index))) { - return true; - } - } - return false; - } - - private static Node directChild(Node node, String localName) { - if (node == null) { - return null; - } - NodeList children = node.getChildNodes(); - for (int index = 0; index < children.getLength(); index++) { - Node child = children.item(index); - if (localName.equals(child.getLocalName())) { - return child; - } - } - return null; - } - - private static Node firstDescendant(Node node, String localName) { - if (node == null) { - return null; - } - NodeList children = node.getChildNodes(); - for (int index = 0; index < children.getLength(); index++) { - Node child = children.item(index); - if (localName.equals(child.getLocalName())) { - return child; - } - Node descendant = firstDescendant(child, localName); - if (descendant != null) { - return descendant; - } - } - return null; - } - - private static String nodeText(Node node) { - if (node == null) { - return null; - } - StringBuilder text = new StringBuilder(); - NodeList children = node.getChildNodes(); - for (int index = 0; index < children.getLength(); index++) { - Node child = children.item(index); - if (child.getNodeType() == Node.TEXT_NODE || child.getNodeType() == Node.CDATA_SECTION_NODE) { - text.append(child.getNodeValue()); - } else { - String childText = nodeText(child); - if (childText != null) { - text.append(childText); - } - } - } - return text.toString(); - } - - private static String attribute(Node node, String localName) { - if (node == null || node.getAttributes() == null) { - return null; - } - NamedNodeMap attributes = node.getAttributes(); - for (int index = 0; index < attributes.getLength(); index++) { - Node attribute = attributes.item(index); - if (localName.equals(attribute.getLocalName()) || localName.equals(attribute.getNodeName())) { - return attribute.getNodeValue(); - } - } - return null; - } - - private static float emuToPoints(String value) { - if (value == null || value.isEmpty()) { - return 0.0f; - } - try { - return Long.parseLong(value) / EMUS_PER_POINT; - } catch (NumberFormatException ignored) { - return 0.0f; - } - } - - /** - * Reads the theme color scheme (dk1/lt1/dk2/lt2/accent1..6) from the - * document's theme part, mirroring DocxReader's themeColors map. - */ - private static Map themeColors(XWPFDocument source) { - Map colors = new LinkedHashMap<>(); - try { - for (PackagePart part : source.getPackage().getParts()) { - if (!part.getPartName().getName().contains("/theme/")) { - continue; - } - try (InputStream stream = part.getInputStream()) { - DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); - // localName-based lookups below require namespace processing. - factory.setNamespaceAware(true); - Document theme = factory.newDocumentBuilder().parse(stream); - Node scheme = firstDescendant(theme.getDocumentElement(), "clrScheme"); - if (scheme == null) { - continue; - } - NodeList entries = scheme.getChildNodes(); - for (int index = 0; index < entries.getLength(); index++) { - Node entry = entries.item(index); - if (entry.getNodeType() != Node.ELEMENT_NODE) { - continue; - } - Node srgb = firstDescendant(entry, "srgbClr"); - Node sys = firstDescendant(entry, "sysClr"); - String value = attribute(srgb, "val"); - if (value == null && sys != null) { - value = attribute(sys, "lastClr"); - if (value == null) { - value = attribute(sys, "val"); - } - } - if (value != null && !value.isEmpty()) { - colors.put(entry.getLocalName(), value); - } - } - // schemeClr values like "tx2" resolve through the theme's - // color map (clrMap). When the map is absent the OOXML - // defaults apply: tx1/bg1 -> dk1/lt1, tx2/bg2 -> dk2/lt2 - // (Word's letterhead sidebars use tx2 fills). - Node clrMap = firstDescendant(theme.getDocumentElement(), "clrMap"); - for (String alias : new String[] {"tx1", "bg1", "tx2", "bg2"}) { - String target = clrMap == null - ? null - : attribute(clrMap, alias); - if (target == null) { - target = "tx1".equals(alias) ? "dk1" - : "bg1".equals(alias) ? "lt1" - : "tx2".equals(alias) ? "dk2" - : "lt2"; - } - if (colors.containsKey(target)) { - colors.put(alias, colors.get(target)); - } - } - } - break; - } - } catch (Exception ignored) { - // A missing or malformed theme part must not abort conversion. - } - return colors; - } - - /** - * Reads the theme font scheme's Latin typefaces as {major, minor}. - * majorFont faces headings (e.g. Franklin Gothic Demi), minorFont faces - * body text (e.g. Franklin Gothic Book). - */ - private static String[] themeLatinFonts(XWPFDocument source) { - String[] fonts = {null, null}; - try { - for (PackagePart part : source.getPackage().getParts()) { - if (!part.getPartName().getName().contains("/theme/")) { - continue; - } - try (InputStream stream = part.getInputStream()) { - DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); - factory.setNamespaceAware(true); - Document theme = factory.newDocumentBuilder().parse(stream); - Node scheme = firstDescendant(theme.getDocumentElement(), "fontScheme"); - if (scheme != null) { - fonts[0] = themeTypeface(firstDescendant(scheme, "majorFont")); - fonts[1] = themeTypeface(firstDescendant(scheme, "minorFont")); - } - } - break; - } - } catch (Exception ignored) { - // A missing or malformed theme part must not abort conversion. - } - return fonts; - } - - private static String themeTypeface(Node fontNode) { - if (fontNode == null) { - return null; - } - String face = attribute(directChild(fontNode, "latin"), "typeface"); - return face == null || face.isEmpty() ? null : face; - } - - /** - * True when a paragraph's only visual content is behindDoc anchored - * drawing shapes (no runs, no pictures). - */ - private static boolean isShapeOnlyParagraph(XWPFParagraph paragraph) { - // Runs that only host w:drawing content carry no text and must not - // make the paragraph consume flow space. - for (XWPFRun run : paragraph.getRuns()) { - if (!run.text().isEmpty() || !run.getEmbeddedPictures().isEmpty()) { - return false; - } - } - List drawings = new ArrayList<>(); - collectDescendants(paragraph.getCTP().getDomNode(), "drawing", drawings); - for (Node drawing : drawings) { - Node anchor = directChild(drawing, "anchor"); - if (anchor != null && "1".equals(attribute(anchor, "behindDoc"))) { - return true; - } - } - return false; - } - - /** - * Renders behindDoc anchored DrawingML group shapes (sidebars, decorative - * freeforms) and standalone shapes (full-page frames) at absolute page - * positions. Mirrors DocxReader.ReadAnchorShapes and - * DocxToPdfConverter.RenderShape. - */ - private static void renderAnchoredBehindDocShapes(PageContext context, XWPFParagraph paragraph) - throws IOException { - // Mirrors DocxToPdfConverter.RenderShape: body shapes anchor from - // (pageHeight - topMargin), header shapes from the page top. - renderAnchoredBehindDocShapes( - context, paragraph, context.pageSize.height() - context.topMargin); - } - - private static void renderAnchoredBehindDocShapes( - PageContext context, - XWPFParagraph paragraph, - float paragraphTopY) throws IOException { - List drawings = new ArrayList<>(); - collectDescendants(paragraph.getCTP().getDomNode(), "drawing", drawings); - for (Node drawing : drawings) { - Node anchor = directChild(drawing, "anchor"); - if (anchor == null || !"1".equals(attribute(anchor, "behindDoc"))) { - continue; - } - Node group = firstDescendant(anchor, "wgp"); - if (group == null) { - // A standalone shape (not nested in a group), e.g. the - // full-page rounded "frame" border of a letterhead header. - Node wsp = firstDescendant(anchor, "wsp"); - if (wsp != null) { - renderStandaloneWsp(context, wsp, anchor, paragraphTopY); - } - continue; - } - if (group != null) { - long offsetX = emuValue(directChild(directChild(anchor, "positionH"), "posOffset")); - long offsetY = emuValue(directChild(directChild(anchor, "positionV"), "posOffset")); - Node grpSpPr = directChild(group, "grpSpPr"); - Node xfrm = grpSpPr == null ? null : directChild(grpSpPr, "xfrm"); - Node extNode = directChild(xfrm, "ext"); - long extCx = attributeEmu(extNode, "cx"); - long extCy = attributeEmu(extNode, "cy"); - long chOffX = attributeEmu(directChild(xfrm, "chOff"), "x"); - long chOffY = attributeEmu(directChild(xfrm, "chOff"), "y"); - long chExtCx = attributeEmu(directChild(xfrm, "chExt"), "cx"); - long chExtCy = attributeEmu(directChild(xfrm, "chExt"), "cy"); - if (extCx <= 0) { - extCx = 1; - } - if (extCy <= 0) { - extCy = 1; - } - if (chExtCx <= 0) { - chExtCx = 1; - } - if (chExtCy <= 0) { - chExtCy = 1; - } - float[] groupFill = fillOf(grpSpPr, context.themeColors, null); - renderGroupChildren( - context, - group, - groupFill, - offsetX, - offsetY, - chOffX, - chOffY, - extCx, - extCy, - chExtCx, - chExtCy); - } - } - } - - /** - * Renders a standalone (non-grouped) behindDoc anchored shape, such as - * the full-page rounded "frame" of a letterhead header. Word exports - * that frame as an even-odd filled band inset by min(w,h)*adj1/100000 - * (the LibreOffice preset-geometry formula). - */ - private static void renderStandaloneWsp( - PageContext context, - Node wsp, - Node anchor, - float paragraphTopY) throws IOException { - Node spPr = directChild(wsp, "spPr"); - if (spPr == null) { - return; - } - float[] fill = fillOf(spPr, context.themeColors, null); - if (fill == null) { - return; - } - Node xfrm = directChild(spPr, "xfrm"); - long extCx = attributeEmu(directChild(xfrm, "ext"), "cx"); - long extCy = attributeEmu(directChild(xfrm, "ext"), "cy"); - if (extCx <= 0) { - extCx = 1; - } - if (extCy <= 0) { - extCy = 1; - } - long offsetX = emuValue(directChild(directChild(anchor, "positionH"), "posOffset")); - long offsetY = emuValue(directChild(directChild(anchor, "positionV"), "posOffset")); - float width = extCx / EMUS_PER_POINT; - float height = extCy / EMUS_PER_POINT; - String horizontalRelative = attribute(directChild(anchor, "positionH"), "relativeFrom"); - String verticalRelative = attribute(directChild(anchor, "positionV"), "relativeFrom"); - float x = "column".equals(horizontalRelative) - ? context.margin + offsetX / EMUS_PER_POINT - : offsetX / EMUS_PER_POINT; - float top = "paragraph".equals(verticalRelative) - ? paragraphTopY - offsetY / EMUS_PER_POINT - : context.pageSize.height() - offsetY / EMUS_PER_POINT; - float bottom = top - height; - // Alpha-blend the fill over white, mirroring - // DocxToPdfConverter.RenderShape. - float alpha = fill.length > 3 ? fill[3] : 1.0f; - context.content.setNonStrokingColor( - 1.0f + (fill[0] - 1.0f) * alpha, - 1.0f + (fill[1] - 1.0f) * alpha, - 1.0f + (fill[2] - 1.0f) * alpha); - Node prstGeom = firstDescendant(spPr, "prstGeom"); - if (prstGeom != null && "frame".equals(attribute(prstGeom, "prst"))) { - float radius = frameCornerRadius(prstGeom, width, height); - context.content.addRect(x, bottom, width, height); - context.content.addRect( - x + radius, bottom + radius, width - 2.0f * radius, height - 2.0f * radius); - context.content.fillEvenOdd(); - } else { - List> subpaths = customGeometryPaths(spPr, extCx, extCy); - if (subpaths != null && !subpaths.isEmpty()) { - for (List subpath : subpaths) { - if (subpath.size() < 3) { - continue; - } - float[] first = subpath.get(0); - context.content.moveTo( - x + first[0] * width, - bottom + height - first[1] * height); - for (int index = 1; index < subpath.size(); index++) { - float[] point = subpath.get(index); - context.content.lineTo( - x + point[0] * width, - bottom + height - point[1] * height); - } - context.content.closePath(); - } - context.content.fillEvenOdd(); - } else { - context.content.addRect(x, bottom, width, height); - context.content.fill(); - } - } - context.content.setNonStrokingColor(0.0f, 0.0f, 0.0f); - } - - /** - * prstGeom "frame": the corner radius is adj1/100000 of the shorter side - * (LibreOffice preset geometry: x1 = min(w,h) * adj1 / 100000, default - * adj1 = 12500). - */ - private static float frameCornerRadius(Node prstGeom, float width, float height) { - long adjustment = 12_500L; - Node avLst = directChild(prstGeom, "avLst"); - if (avLst != null) { - NodeList guides = avLst.getChildNodes(); - for (int index = 0; index < guides.getLength(); index++) { - Node guide = guides.item(index); - if (guide.getNodeType() == Node.ELEMENT_NODE - && "adj1".equals(attribute(guide, "name"))) { - String formula = attribute(guide, "fmla"); - if (formula != null && formula.startsWith("val ")) { - try { - adjustment = Long.parseLong(formula.substring(4).trim()); - } catch (NumberFormatException ignored) { - // Keep the preset default. - } - } - break; - } - } - } - return Math.min(width, height) * adjustment / 100_000.0f; - } - - private static void renderGroupChildren( - PageContext context, - Node groupElement, - float[] groupFill, - long anchorOffsetX, - long anchorOffsetY, - long chOffX, - long chOffY, - long groupExtCx, - long groupExtCy, - long chExtCx, - long chExtCy) throws IOException { - NodeList children = groupElement.getChildNodes(); - for (int index = 0; index < children.getLength(); index++) { - Node child = children.item(index); - if (child.getNodeType() != Node.ELEMENT_NODE) { - continue; - } - if ("wsp".equals(child.getLocalName())) { - renderWspShape( - context, - child, - groupFill, - anchorOffsetX, - anchorOffsetY, - chOffX, - chOffY, - groupExtCx, - groupExtCy, - chExtCx, - chExtCy); - } else if ("grpSp".equals(child.getLocalName())) { - Node subSpPr = directChild(child, "grpSpPr"); - Node subXfrm = subSpPr == null ? null : directChild(subSpPr, "xfrm"); - long subOffX = attributeEmu(directChild(subXfrm, "off"), "x"); - long subOffY = attributeEmu(directChild(subXfrm, "off"), "y"); - long subCx = attributeEmu(directChild(subXfrm, "ext"), "cx"); - long subCy = attributeEmu(directChild(subXfrm, "ext"), "cy"); - long subChOffX = attributeEmu(directChild(subXfrm, "chOff"), "x"); - long subChOffY = attributeEmu(directChild(subXfrm, "chOff"), "y"); - long subChCx = attributeEmu(directChild(subXfrm, "chExt"), "cx"); - long subChCy = attributeEmu(directChild(subXfrm, "chExt"), "cy"); - if (subCx <= 0) { - subCx = 1; - } - if (subCy <= 0) { - subCy = 1; - } - if (subChCx <= 0) { - subChCx = 1; - } - if (subChCy <= 0) { - subChCy = 1; - } - float[] subFill = fillOf(subSpPr, context.themeColors, groupFill); - long mappedAnchorX = anchorOffsetX + (subOffX - chOffX) * groupExtCx / chExtCx; - long mappedAnchorY = anchorOffsetY + (subOffY - chOffY) * groupExtCy / chExtCy; - long mappedExtCx = subCx * groupExtCx / chExtCx; - long mappedExtCy = subCy * groupExtCy / chExtCy; - renderGroupChildren( - context, - child, - subFill, - mappedAnchorX, - mappedAnchorY, - subChOffX, - subChOffY, - mappedExtCx, - mappedExtCy, - subChCx, - subChCy); - } - } - } - - private static void renderWspShape( - PageContext context, - Node wsp, - float[] groupFill, - long anchorOffsetX, - long anchorOffsetY, - long chOffX, - long chOffY, - long groupExtCx, - long groupExtCy, - long chExtCx, - long chExtCy) throws IOException { - Node spPr = directChild(wsp, "spPr"); - if (spPr == null) { - return; - } - float[] fill = fillOf(spPr, context.themeColors, groupFill); - if (fill == null) { - return; - } - Node xfrm = directChild(spPr, "xfrm"); - if (xfrm == null) { - return; - } - long childOffX = attributeEmu(directChild(xfrm, "off"), "x"); - long childOffY = attributeEmu(directChild(xfrm, "off"), "y"); - long childCx = attributeEmu(directChild(xfrm, "ext"), "cx"); - long childCy = attributeEmu(directChild(xfrm, "ext"), "cy"); - long pageX = anchorOffsetX + (childOffX - chOffX) * groupExtCx / chExtCx; - long pageY = anchorOffsetY + (childOffY - chOffY) * groupExtCy / chExtCy; - long pageW = childCx * groupExtCx / chExtCx; - long pageH = childCy * groupExtCy / chExtCy; - if (pageW <= 0 || pageH <= 0) { - return; - } - float x = context.margin + pageX / EMUS_PER_POINT; - float y = context.pageSize.height() - context.topMargin - pageY / EMUS_PER_POINT - - pageH / EMUS_PER_POINT; - float width = pageW / EMUS_PER_POINT; - float height = pageH / EMUS_PER_POINT; - // Alpha-blend the fill over white, mirroring DocxToPdfConverter.RenderShape. - float alpha = fill.length > 3 ? fill[3] : 1.0f; - context.content.setNonStrokingColor( - 1.0f + (fill[0] - 1.0f) * alpha, - 1.0f + (fill[1] - 1.0f) * alpha, - 1.0f + (fill[2] - 1.0f) * alpha); - List> subpaths = customGeometryPaths(spPr, childCx, childCy); - if (subpaths != null && !subpaths.isEmpty()) { - for (List subpath : subpaths) { - if (subpath.size() < 3) { - continue; - } - float[] first = subpath.get(0); - context.content.moveTo( - x + first[0] * width, y + height - first[1] * height); - for (int index = 1; index < subpath.size(); index++) { - float[] point = subpath.get(index); - context.content.lineTo( - x + point[0] * width, y + height - point[1] * height); - } - context.content.closePath(); - } - // Mirror DocxToPdfConverter: custom geometry paths use even-odd fill. - context.content.fillEvenOdd(); - } else { - context.content.addRect(x, y, width, height); - context.content.fill(); - } - context.content.setNonStrokingColor(0.0f, 0.0f, 0.0f); - } - - /** - * Resolves a shape's solidFill to RGB floats + alpha, honoring grpFill - * inheritance. Returns null when the shape has no fill. - */ - private static float[] fillOf(Node spPr, Map themeColors, float[] groupFill) { - if (spPr == null || directChild(spPr, "noFill") != null) { - return null; - } - Node solidFill = directChild(spPr, "solidFill"); - if (solidFill != null) { - return resolveSolidFill(solidFill, themeColors); - } - if (directChild(spPr, "grpFill") != null) { - return groupFill; - } - return null; - } - - private static float[] resolveSolidFill(Node solidFill, Map themeColors) { - Node srgb = directChild(solidFill, "srgbClr"); - Node scheme = srgb == null ? directChild(solidFill, "schemeClr") : null; - String hex = attribute(srgb, "val"); - if (hex == null) { - hex = themeColors == null ? null : themeColors.get(attribute(scheme, "val")); - } - if (hex == null || hex.length() < 6) { - return null; - } - try { - int rgb = Integer.parseInt(hex.substring(0, 6), 16); - float[] fill = new float[] { - ((rgb >> 16) & 0xff) / 255.0f, - ((rgb >> 8) & 0xff) / 255.0f, - (rgb & 0xff) / 255.0f, - 1.0f, - }; - // a:alpha is a positive fixed percentage (val/100000); honor it - // for both srgbClr and schemeClr fills (Word's letterhead frames - // use schemeClr accent1 with a low alpha). - Node colorNode = srgb != null ? srgb : scheme; - if (colorNode != null) { - Node alpha = directChild(colorNode, "alpha"); - long alphaValue = attributeEmu(alpha, "val"); - if (alphaValue > 0) { - fill[3] = Math.min(1.0f, alphaValue / 100000.0f); - } - // a:lumMod scales the color luminance (tx2 sidebar fills use - // 75% of dk2). - Node lumMod = directChild(colorNode, "lumMod"); - long lumValue = attributeEmu(lumMod, "val"); - if (lumValue > 0 && lumValue < 100000) { - float factor = lumValue / 100000.0f; - fill[0] *= factor; - fill[1] *= factor; - fill[2] *= factor; - } - } - return fill; - } catch (NumberFormatException ignored) { - return null; - } - } - - /** - * Parses custGeom freeform paths into normalized point subpaths, mirroring - * DocxReader.ParseCustomGeometryPaths. - */ - private static List> customGeometryPaths(Node spPr, long widthEmu, long heightEmu) { - Node custGeom = firstDescendant(spPr, "custGeom"); - if (custGeom == null) { - return null; - } - Node pathLst = directChild(custGeom, "pathLst"); - if (pathLst == null) { - return null; - } - List> subpaths = new ArrayList<>(); - NodeList paths = pathLst.getChildNodes(); - for (int pathIndex = 0; pathIndex < paths.getLength(); pathIndex++) { - Node path = paths.item(pathIndex); - if (path.getNodeType() != Node.ELEMENT_NODE || !"path".equals(path.getLocalName())) { - continue; - } - long pathW = widthEmu > 0 ? widthEmu : 1; - long pathH = heightEmu > 0 ? heightEmu : 1; - long parsedW = attributeEmu(path, "w"); - long parsedH = attributeEmu(path, "h"); - if (parsedW > 0) { - pathW = parsedW; - } - if (parsedH > 0) { - pathH = parsedH; - } - Map vars = new HashMap<>(); - vars.put("w", (double) pathW); - vars.put("h", (double) pathH); - Node gdLst = directChild(custGeom, "gdLst"); - if (gdLst != null) { - NodeList guides = gdLst.getChildNodes(); - for (int guideIndex = 0; guideIndex < guides.getLength(); guideIndex++) { - Node guide = guides.item(guideIndex); - if (guide.getNodeType() != Node.ELEMENT_NODE || !"gd".equals(guide.getLocalName())) { - continue; - } - String name = attribute(guide, "name"); - String formula = attribute(guide, "fmla"); - if (name != null && formula != null) { - vars.put(name, evaluateGuideFormula(formula, vars)); - } - } - } - List current = new ArrayList<>(); - NodeList commands = path.getChildNodes(); - for (int commandIndex = 0; commandIndex < commands.getLength(); commandIndex++) { - Node command = commands.item(commandIndex); - if (command.getNodeType() != Node.ELEMENT_NODE) { - continue; - } - String commandName = command.getLocalName(); - if ("moveTo".equals(commandName)) { - if (current.size() >= 3) { - subpaths.add(current); - } - current = new ArrayList<>(); - float[] point = pathPoint(directChild(command, "pt"), vars, pathW, pathH); - if (point != null) { - current.add(point); - } - } else if ("lnTo".equals(commandName)) { - float[] point = pathPoint(directChild(command, "pt"), vars, pathW, pathH); - if (point != null) { - current.add(point); - } - } else if ("close".equals(commandName)) { - if (current.size() >= 3) { - subpaths.add(current); - current = new ArrayList<>(); - } - } - } - if (current.size() >= 3) { - subpaths.add(current); - } - } - return subpaths.isEmpty() ? null : subpaths; - } - - private static float[] pathPoint(Node point, Map vars, long pathW, long pathH) { - if (point == null) { - return null; - } - String xToken = attribute(point, "x"); - String yToken = attribute(point, "y"); - if (xToken == null || yToken == null) { - return null; - } - double x = resolveGuideToken(xToken, vars); - double y = resolveGuideToken(yToken, vars); - if (pathW <= 0 || pathH <= 0) { - return null; - } - return new float[] { - (float) Math.max(-0.25, Math.min(1.25, x / pathW)), - (float) Math.max(-0.25, Math.min(1.25, y / pathH)), - }; - } - - private static double evaluateGuideFormula(String formula, Map vars) { - String[] tokens = formula.trim().split("\\s+"); - if (tokens.length == 0) { - return 0.0; - } - if ("val".equals(tokens[0]) && tokens.length >= 2) { - return resolveGuideToken(tokens[1], vars); - } - if ("*/".equals(tokens[0]) && tokens.length >= 4) { - double a = resolveGuideToken(tokens[1], vars); - double b = resolveGuideToken(tokens[2], vars); - double c = resolveGuideToken(tokens[3], vars); - return Math.abs(c) < 0.0001 ? 0.0 : a * b / c; - } - if ("+-".equals(tokens[0]) && tokens.length >= 4) { - return resolveGuideToken(tokens[1], vars) - + resolveGuideToken(tokens[2], vars) - - resolveGuideToken(tokens[3], vars); - } - return tokens.length == 1 ? resolveGuideToken(tokens[0], vars) : 0.0; - } - - private static double resolveGuideToken(String token, Map vars) { - try { - return Double.parseDouble(token); - } catch (NumberFormatException ignored) { - Double value = vars.get(token); - return value == null ? 0.0 : value; - } - } - - private static void collectDescendants(Node node, String localName, List result) { - if (node == null) { - return; - } - NodeList children = node.getChildNodes(); - for (int index = 0; index < children.getLength(); index++) { - Node child = children.item(index); - if (localName.equals(child.getLocalName())) { - result.add(child); - } - collectDescendants(child, localName, result); - } - } - - private static long emuValue(Node node) { - if (node == null) { - return 0L; - } - String text = nodeText(node); - if (text == null) { - return 0L; - } - try { - return Long.parseLong(text.trim()); - } catch (NumberFormatException ignored) { - return 0L; - } - } - - private static long attributeEmu(Node node, String localName) { - String value = attribute(node, localName); - if (value == null || value.isEmpty()) { - return 0L; - } - try { - return Long.parseLong(value.trim()); - } catch (NumberFormatException ignored) { - return 0L; - } - } - - private static void renderTable( - PageContext context, - XWPFTable table, - ParagraphFonts fonts, - PDFont boldFont, - XWPFDocument document) throws IOException { - PDFont font = fonts.simSun(); - float tableWidth = twipsToPoints(table.getWidth()); - boolean autoWidth = tableWidth <= 0.0f; - if (autoWidth) { - tableWidth = context.pageSize.width() - context.margin * 2.0f; - } - // Word applies a default table indent of -108 twips (one cell margin) - // to auto-width tables so the left cell margin lands on the text - // margin. Verified against Word and LibreOffice: the thesis table - // borders start 5.4pt left of the 90pt margin. - float x = autoWidth - ? context.margin - CELL_HORIZONTAL_PADDING - : (context.pageSize.width() - tableWidth) / 2.0f; - boolean compact = tableWidth < 200.0f; - boolean landscape = context.pageSize.width() > context.pageSize.height(); - List columnWidths = columnWidths(table, tableWidth); - float rowHeightPadding = compact ? 0.0f : columnWidths.size() > 2 - ? landscape ? 1.6f : 2.3f - : 1.5f; - List rowHeights = new ArrayList<>(); - for (XWPFTableRow row : table.getRows()) { - rowHeights.add(rowHeight( - row, fonts, boldFont, columnWidths, compact, rowHeightPadding, context.linePitch)); - } - float tableHeight = sum(rowHeights, rowHeights.size()); - // Word applies no spacing-before to tables: the visible gap comes from - // the surrounding paragraph spacing and line advances. A fixed offset - // pushed header tables (e.g. the OSCAR WARD letterhead) below Word's - // position. - context.ensureSpace(tableHeight); - - float rowTop = context.y; - for (int rowIndex = 0; rowIndex < table.getRows().size(); rowIndex++) { - XWPFTableRow row = table.getRows().get(rowIndex); - float rowHeight = rowHeights.get(rowIndex); - boolean firstRow = rowIndex == 0; - boolean lastRow = rowIndex == table.getRows().size() - 1; - float cellX = x; - int column = 0; - int cellCount = row.getTableCells().size(); - for (int cellIndex = 0; cellIndex < cellCount; cellIndex++) { - XWPFTableCell cell = row.getTableCells().get(cellIndex); - float width = twipsToPoints(cell.getWidth()); - if (width <= 0.0f) { - width = column < columnWidths.size() ? columnWidths.get(column) : tableWidth; - } - drawCellBorder( - context, - table, - cell, - cellX, - rowTop, - width, - rowHeight, - firstRow, - lastRow, - cellIndex == 0, - cellIndex == cellCount - 1, - document); - cellX += width; - while (column < columnWidths.size() && cellX > x + sum(columnWidths, column + 1) - 0.5f) { - column++; - } - } - rowTop -= rowHeight; - } - - rowTop = context.y; - Map mergeLines = new HashMap<>(); - for (int rowIndex = 0; rowIndex < table.getRows().size(); rowIndex++) { - XWPFTableRow row = table.getRows().get(rowIndex); - float cellX = x; - int column = 0; - for (int cellIndex = 0; cellIndex < row.getTableCells().size(); cellIndex++) { - XWPFTableCell cell = row.getTableCells().get(cellIndex); - float width = twipsToPoints(cell.getWidth()); - if (width <= 0.0f) { - width = column < columnWidths.size() ? columnWidths.get(column) : tableWidth; - } - if (compact && isVerticallyMerged(cell)) { - MergeLine mergeLine; - if (isMergeRestart(cell)) { - mergeLine = new MergeLine(cell, 0); - } else { - MergeLine previous = mergeLines.get(cellIndex); - mergeLine = previous == null - ? new MergeLine(cell, 0) - : new MergeLine(previous.cell(), previous.index() + 1); - } - mergeLines.put(cellIndex, mergeLine); - float mergeWidth = twipsToPoints(mergeLine.cell().getWidth()); - drawCompactMergeLine( - context, - mergeLine, - font, - boldFont, - cellX, - rowTop, - mergeWidth > 0.0f ? mergeWidth : width); - } else if (!isMergeContinuation(cell)) { - mergeLines.remove(cellIndex); - float height = isMergeRestart(cell) - ? mergedHeight(table, rowHeights, rowIndex, cellIndex) - : rowHeights.get(rowIndex); - drawCellText( - context, - cell, - fonts, - boldFont, - cellX, - rowTop, - width, - height, - compact); - } - cellX += width; - while (column < columnWidths.size() && cellX > x + sum(columnWidths, column + 1) - 0.5f) { - column++; - } - } - rowTop -= rowHeights.get(rowIndex); - } - context.y -= tableHeight; - // A table interrupts the paragraph chain: the next paragraph's - // spacing-before must not collapse with the spacing-after of the - // paragraph preceding the table (Word does not collapse across tables). - context.resetParagraphSpacingAfter(); - } - - private static void drawCompactMergeLine( - PageContext context, - MergeLine mergeLine, - PDFont font, - PDFont boldFont, - float x, - float top, - float width) throws IOException { - XWPFTableCell cell = mergeLine.cell(); - PDFont cellFont = isCellBold(cell) ? boldFont : font; - List lines = cellLines(cell, cellFont, width, 0.0f); - if (mergeLine.index() >= lines.size()) { - return; - } - CellLine line = lines.get(mergeLine.index()); - showText(context.content, cellFont, line.fontSize, line.text, x, top - line.fontSize); - } - - private static void drawCellBorder( - PageContext context, - XWPFTable table, - XWPFTableCell cell, - float x, - float top, - float width, - float height, - boolean firstRow, - boolean lastRow, - boolean firstColumn, - boolean lastColumn, - XWPFDocument document) throws IOException { - context.content.setStrokingColor(0, 0, 0); - context.content.setLineWidth(0.5f); - CTTcBorders borders = cell.getCTTc().isSetTcPr() - && cell.getCTTc().getTcPr().isSetTcBorders() - ? cell.getCTTc().getTcPr().getTcBorders() - : null; - CTTblBorders tableBorders = resolvedTableBorders(table, document); - if (borders == null && isBorderlessLayoutTable(table, tableBorders)) { - return; - } - String topStyle = resolveBorderStyle( - borders != null && borders.isSetTop() ? borders.getTop() : null, - tableBorders == null ? null : firstRow ? tableBorders.getTop() : tableBorders.getInsideH()); - String leftStyle = resolveBorderStyle( - borders != null && borders.isSetLeft() ? borders.getLeft() : null, - tableBorders == null ? null : firstColumn ? tableBorders.getLeft() : tableBorders.getInsideV()); - String bottomStyle = resolveBorderStyle( - borders != null && borders.isSetBottom() ? borders.getBottom() : null, - tableBorders == null ? null : lastRow ? tableBorders.getBottom() : tableBorders.getInsideH()); - String rightStyle = resolveBorderStyle( - borders != null && borders.isSetRight() ? borders.getRight() : null, - tableBorders == null ? null : lastColumn ? tableBorders.getRight() : tableBorders.getInsideV()); - if (isVisibleBorder(topStyle)) { - drawBorder(context, x, top, x + width, top, topStyle); - } - if (isVisibleBorder(leftStyle)) { - drawBorder(context, x, top, x, top - height, leftStyle); - } - if (isVisibleBorder(bottomStyle)) { - drawBorder(context, x, top - height, x + width, top - height, bottomStyle); - } - if (isVisibleBorder(rightStyle)) { - drawBorder(context, x + width, top, x + width, top - height, rightStyle); - } - } - - /** - * Resolves the table's effective borders the way Word does: explicit - * w:tblBorders wins, then the table style's tblBorders, then a built-in - * "Grid"-style heuristic for styles that are referenced but not embedded. - */ - private static CTTblBorders resolvedTableBorders(XWPFTable table, XWPFDocument document) { - CTTblBorders direct = table.getCTTbl().getTblPr().isSetTblBorders() - ? table.getCTTbl().getTblPr().getTblBorders() - : null; - if (direct != null) { - return direct; - } - CTTblBorders style = tableStyleBorders(table, document); - if (style != null) { - return style; - } - String styleId = table.getStyleID(); - if (styleId != null && styleId.toLowerCase().contains("grid")) { - return syntheticGridBorders(); - } - return null; - } - - private static CTTblBorders tableStyleBorders(XWPFTable table, XWPFDocument document) { - String styleId = table.getStyleID(); - if (styleId == null || styleId.isEmpty()) { - return null; - } - CTStyles styles = document.getStyles().getCtStyles(); - if (styles == null) { - return null; - } - for (CTStyle style : styles.getStyleList()) { - if (!styleId.equals(style.getStyleId())) { - continue; - } - // Read the style's w:tblPr/w:tblBorders through the DOM instead of - // CTStyle#getTblPr(), which materializes CTTblPrBase — a schema type - // only present in poi-ooxml-full, not poi-ooxml-lite. - Node tblPr = directChild(style.getDomNode(), "tblPr"); - Node tblBorders = tblPr == null ? null : directChild(tblPr, "tblBorders"); - if (tblBorders == null) { - return null; - } - CTTblBorders borders = CTTblBorders.Factory.newInstance(); - copyStyleBorderSide(borders, tblBorders, "top"); - copyStyleBorderSide(borders, tblBorders, "left"); - copyStyleBorderSide(borders, tblBorders, "bottom"); - copyStyleBorderSide(borders, tblBorders, "right"); - copyStyleBorderSide(borders, tblBorders, "insideH"); - copyStyleBorderSide(borders, tblBorders, "insideV"); - return borders; - } - return null; - } - - private static void copyStyleBorderSide(CTTblBorders borders, Node tblBorders, String side) { - Node sideNode = directChild(tblBorders, side); - if (sideNode == null) { - return; - } - String value = attribute(sideNode, "val"); - if (value == null || value.isEmpty()) { - return; - } - STBorder.Enum borderValue; - try { - borderValue = STBorder.Enum.forString(value); - } catch (IllegalArgumentException ignored) { - return; - } - CTBorder border; - switch (side) { - case "top": - border = borders.addNewTop(); - break; - case "left": - border = borders.addNewLeft(); - break; - case "bottom": - border = borders.addNewBottom(); - break; - case "right": - border = borders.addNewRight(); - break; - case "insideH": - border = borders.addNewInsideH(); - break; - case "insideV": - border = borders.addNewInsideV(); - break; - default: - return; - } - border.setVal(borderValue); - } - - private static CTTblBorders syntheticGridBorders() { - CTTblBorders borders = CTTblBorders.Factory.newInstance(); - for (CTBorder side : new CTBorder[] { - borders.addNewTop(), - borders.addNewLeft(), - borders.addNewBottom(), - borders.addNewRight(), - borders.addNewInsideH(), - borders.addNewInsideV()}) { - side.setVal(STBorder.SINGLE); - } - return borders; - } - - static String resolveBorderStyle(CTBorder cellBorder, CTBorder tableBorder) { - CTBorder border = cellBorder == null ? tableBorder : cellBorder; - return border == null || border.getVal() == null ? null : border.getVal().toString(); - } - - private static boolean explicitlyBorderless(CTTblBorders borders) { - return borders != null - && !isVisibleBorder(resolveBorderStyle(borders.getTop(), null)) - && !isVisibleBorder(resolveBorderStyle(borders.getLeft(), null)) - && !isVisibleBorder(resolveBorderStyle(borders.getBottom(), null)) - && !isVisibleBorder(resolveBorderStyle(borders.getRight(), null)) - && !isVisibleBorder(resolveBorderStyle(borders.getInsideH(), null)) - && !isVisibleBorder(resolveBorderStyle(borders.getInsideV(), null)); - } - - private static boolean isBorderlessLayoutTable(XWPFTable table, CTTblBorders borders) { - return table.getRows().size() == 1 - && table.getRows().get(0).getTableCells().size() == 1 - && explicitlyBorderless(borders); - } - - private static void drawBorder( - PageContext context, - float startX, - float startY, - float endX, - float endY, - String style) throws IOException { - if (style.toLowerCase().contains("dash") || style.toLowerCase().contains("dot")) { - context.content.setLineDashPattern(new float[] {1.0f, 1.0f}, 0.0f); - } - context.content.moveTo(startX, startY); - context.content.lineTo(endX, endY); - context.content.stroke(); - context.content.setLineDashPattern(new float[0], 0.0f); - } - - private static boolean isVisibleBorder(String style) { - return style != null && !"nil".equalsIgnoreCase(style) && !"none".equalsIgnoreCase(style); - } - - private static void drawCellText( - PageContext context, - XWPFTableCell cell, - ParagraphFonts fonts, - PDFont boldFont, - float x, - float top, - float width, - float height, - boolean compact) throws IOException { - PDFont cellFont = resolvedCellFont(cell, fonts, boldFont); - float horizontalPadding = compact ? 0.0f : CELL_HORIZONTAL_PADDING; - // Word's default table cell margin is 0 top/bottom (only left/right - // default to 108 twips), so no vertical padding is added. - float verticalPadding = 0.0f; - List paragraphs = cellParagraphs(cell); - List items = cellItems(cell, fonts, boldFont, width, horizontalPadding, context.linePitch); - float contentHeight = 0.0f; - for (CellItem item : items) { - contentHeight += item.line() != null - ? item.line().advance(context.linePitch) - : item.picture() != null - ? item.pictureHeight() - : item.spacing(); - } - // Cursor tracks the top of the current content line (or image). - // Top-aligned content starts at the cell top: Word's glyph offset for - // the first line is already matched by the baseline placement, and the - // style spacing-before contributes to the ROW height (rowHeight) but - // must not push the first baseline down twice. - float cursor = top - verticalPadding; - if (cell.getVerticalAlignment() == XWPFTableCell.XWPFVertAlign.CENTER) { - cursor -= (height - contentHeight) / 2.0f; - } else if (cell.getVerticalAlignment() == XWPFTableCell.XWPFVertAlign.BOTTOM) { - cursor -= height - contentHeight; - } - ParagraphAlignment alignment = paragraphs.isEmpty() - ? ParagraphAlignment.LEFT - : paragraphs.get(0).getAlignment(); - boolean highlighted = paragraphs.stream() - .flatMap(paragraph -> paragraph.getRuns().stream()) - .anyMatch(run -> run.getTextHighlightColor() != null - && "yellow".equalsIgnoreCase(run.getTextHighlightColor().toString())); - for (CellItem item : items) { - if (item.picture() == null && item.line() == null) { - cursor -= item.spacing(); - continue; - } - if (item.line() == null) { - XWPFPicture picture = item.picture(); - // XWPFPicture#getWidth/getDepth already return points. - float imageWidth = (float) picture.getWidth(); - float imageHeight = (float) picture.getDepth(); - float imageX = x + horizontalPadding; - if (alignment == ParagraphAlignment.CENTER) { - imageX = x + (width - imageWidth) / 2.0f; - } else if (alignment == ParagraphAlignment.RIGHT) { - imageX = x + width - horizontalPadding - imageWidth; - } - try { - PDImageXObject image = decodePicture(context, picture, pictureCrop(picture)); - if (image != null) { - context.content.drawImage(image, imageX, cursor - imageHeight, imageWidth, imageHeight); - } - } catch (IOException | IllegalArgumentException ignored) { - // Unsupported image data must not abort cell rendering. - } - cursor -= imageHeight; - continue; - } - CellLine line = item.line(); - PDFont lineFont = line.font == null ? cellFont : line.font; - float lineWidth = textWidth(lineFont, line.text, line.fontSize); - float lineX = x + horizontalPadding; - if (alignment == ParagraphAlignment.CENTER) { - lineX = x + (width - lineWidth) / 2.0f; - } else if (alignment == ParagraphAlignment.RIGHT) { - lineX = x + width - horizontalPadding - lineWidth; - } - if (highlighted && !line.text.isEmpty()) { - context.content.setNonStrokingColor(1.0f, 1.0f, 0.0f); - context.content.addRect(lineX, cursor - line.fontSize - 1.0f, lineWidth, line.fontSize + 2.0f); - context.content.fill(); - } - applyTextColor(context.content, line.color); - showText(context.content, lineFont, line.fontSize, line.text, lineX, cursor - line.fontSize); - cursor -= line.advance(context.linePitch); - } - context.content.setNonStrokingColor(0.0f, 0.0f, 0.0f); - } - - /** - * Returns the paragraphs that make up a cell's content: direct w:p - * children plus paragraphs inside block-level w:sdt content controls, in - * document order. POI's XWPFTableCell#getParagraphs() only surfaces direct - * w:p children, so SDT-wrapped body text (e.g. Word newsletter templates) - * would otherwise disappear. - */ - static List cellParagraphs(XWPFTableCell cell) { - List paragraphs = new ArrayList<>(); - XmlCursor cursor = cell.getCTTc().newCursor(); - try { - if (cursor.toFirstChild()) { - do { - if (cursor.isStart()) { - collectCellParagraphs(cursor.getObject(), cell, paragraphs); - } - } while (cursor.toNextSibling()); - } - } finally { - cursor.dispose(); - } - if (paragraphs.isEmpty()) { - paragraphs.addAll(cell.getParagraphs()); - } - return paragraphs; - } - - private static void collectCellParagraphs(XmlObject object, XWPFTableCell cell, List paragraphs) { - if (object instanceof CTP) { - // Copy so the wrapped paragraph is independent of the document's - // live typed tree (copy preserves the child element types). - paragraphs.add(new XWPFParagraph((CTP) object.copy(), cell)); - return; - } - // Block-level SDTs wrap their paragraphs in w:sdtContent. - XmlCursor cursor = object.newCursor(); - try { - if (cursor.toFirstChild()) { - do { - if (!cursor.isStart()) { - continue; - } - String name = cursor.getName() == null ? null : cursor.getName().getLocalPart(); - if ("sdtContent".equals(name)) { - XmlCursor inner = cursor.getObject().newCursor(); - try { - if (inner.toFirstChild()) { - do { - if (inner.isStart()) { - collectCellParagraphs(inner.getObject(), cell, paragraphs); - } - } while (inner.toNextSibling()); - } - } finally { - inner.dispose(); - } - } - } while (cursor.toNextSibling()); - } - } finally { - cursor.dispose(); - } - } - - private static final class CellItem { - private final XWPFPicture picture; - private final CellLine line; - private final float spacing; - - private CellItem(XWPFPicture picture, CellLine line, float spacing) { - this.picture = picture; - this.line = line; - this.spacing = spacing; - } - - static CellItem image(XWPFPicture picture) { - return new CellItem(picture, null, 0.0f); - } - - static CellItem text(CellLine line) { - return new CellItem(null, line, 0.0f); - } - - static CellItem spacing(float gap) { - return new CellItem(null, null, gap); - } - - XWPFPicture picture() { - return picture; - } - - CellLine line() { - return line; - } - - float spacing() { - return spacing; - } - - float pictureHeight() { - // XWPFPicture#getDepth already returns points. - return picture == null ? 0.0f : Math.max(1.0f, (float) picture.getDepth()); - } - } - - private static List cellItems( - XWPFTableCell cell, - ParagraphFonts fonts, - PDFont boldFont, - float width, - float padding, - float linePitch) throws IOException { - List items = new ArrayList<>(); - boolean noWrap = cell.getCTTc().isSetTcPr() && cell.getCTTc().getTcPr().isSetNoWrap(); - XWPFParagraph previous = null; - for (XWPFParagraph paragraph : cellParagraphs(cell)) { - // Word collapses the spacing between consecutive cell paragraphs - // to max(after(previous), before(current)) from the style chain. - if (previous != null) { - float gap = Math.max( - twipsToPoints(effectiveSpacing(previous).after()), - twipsToPoints(effectiveSpacing(paragraph).before())); - if (gap > 0.0f) { - items.add(CellItem.spacing(gap)); - } - } - previous = paragraph; - boolean hasPictures = false; - for (XWPFRun run : paragraph.getRuns()) { - for (XWPFPicture picture : run.getEmbeddedPictures()) { - if (picture.getPictureData() == null) { - continue; - } - items.add(CellItem.image(picture)); - hasPictures = true; - } - } - String text = paragraphText(paragraph).trim(); - float fontSize = paragraphFontSize(paragraph, DEFAULT_TABLE_FONT_SIZE); - // A picture-only paragraph's image replaces its paragraph-mark line. - if (text.isEmpty() && hasPictures) { - continue; - } - // Mirrors the body paragraph color chain: an explicit run color - // wins, otherwise the paragraph style's color applies (e.g. the - // green MastheadGREEN title). - String color = paragraphStyleColor(paragraph); - for (XWPFRun run : paragraph.getRuns()) { - String runColor = runColor(run); - if (runColor != null) { - color = runColor; - break; - } - } - PDFont paragraphFont = paragraphCellFont(paragraph, fonts, boldFont); - // A Latin face cannot measure (or draw) East Asian code points; - // mixed-script paragraphs fall back to the CJK face like Word's - // eastAsia slot does. - if (text.codePoints().anyMatch(PoiDocxRenderer::usesEastAsianFontSlot) - && fonts.isLatinFace(paragraphFont)) { - paragraphFont = fonts.simSun(); - } - // Each paragraph advances by its own effective line height (a - // uniform per-cell height wrongly inflates mixed-size cells like - // a 24pt heading followed by 11pt body text). - float advance = paragraphCellLineHeight(paragraph, fontSize, linePitch); - if (noWrap) { - items.add(CellItem.text(new CellLine(text, fontSize, advance, color, paragraphFont))); - } else { - for (String line : wrap(paragraphFont, text, fontSize, cellContentWidth(width, padding))) { - items.add(CellItem.text(new CellLine(line, fontSize, advance, color, paragraphFont))); - } - } - } - if (items.isEmpty()) { - items.add(CellItem.text(new CellLine("", DEFAULT_TABLE_FONT_SIZE))); - } - return items; - } - - /** - * The face a cell paragraph renders with: the theme major font (Demi) for - * majorHAnsi styles, the first run's resolved face, or the cell text's - * script default. - */ - private static PDFont paragraphCellFont( - XWPFParagraph paragraph, ParagraphFonts fonts, PDFont boldFont) { - PDFont majorFace = fonts.majorFace(); - if (paragraphStyleMajorFont(paragraph) && majorFace != null) { - return majorFace; - } - for (XWPFRun run : paragraph.getRuns()) { - String text = renderableText(run.text()); - for (int offset = 0; offset < text.length();) { - int codePoint = text.codePointAt(offset); - offset += Character.charCount(codePoint); - return run.isBold() ? boldFont : fonts.resolve(run, codePoint); - } - } - String text = paragraphText(paragraph); - return text.codePoints().anyMatch(codePoint -> codePoint > 255) - ? fonts.simSun() - : fonts.latin(); - } - - /** - * Effective line height for a cell paragraph: explicit line rule when - * present, otherwise the natural height. Honors each paragraph's own - * spacing rule instead of taking the tallest paragraph of the cell. - */ - private static float paragraphCellLineHeight(XWPFParagraph paragraph, float fontSize, float linePitch) { - float natural = fontSize * 1.2f; - double spacing = paragraph.getSpacingBetween(); - if (spacing < 0.0) { - return gridLineHeight(natural, linePitch); - } - LineSpacingRule rule = paragraph.getSpacingLineRule(); - if (rule == LineSpacingRule.EXACT) { - return Math.max(1.0f, (float) spacing); - } - if (rule == LineSpacingRule.AT_LEAST) { - return Math.max(natural, (float) spacing); - } - return natural * (float) spacing; - } - - private static List columnWidths(XWPFTable table, float tableWidth) { - List widths = new ArrayList<>(); - if (table.getCTTbl().getTblGrid() != null) { - for (CTTblGridCol column : table.getCTTbl().getTblGrid().getGridColList()) { - if (!column.isSetW()) { - widths.clear(); - break; - } - try { - widths.add(Float.parseFloat(column.getW().toString()) / 20.0f); - } catch (NumberFormatException ignored) { - widths.clear(); - break; - } - } - } - if (widths.isEmpty()) { - for (XWPFTableRow row : table.getRows()) { - if (row.getTableCells().size() <= widths.size()) { - continue; - } - widths = row.getTableCells().stream() - .map(cell -> twipsToPoints(cell.getWidth())) - .collect(Collectors.toList()); - } - } - float total = sum(widths, widths.size()); - if (total <= 0.0f) { - return Collections.singletonList(tableWidth); - } - float scale = tableWidth / total; - return widths.stream().map(width -> width * scale).collect(Collectors.toList()); - } - - private static boolean rowHeightExact(XWPFTableRow row) { - Node trPr = directChild(row.getCtRow().getDomNode(), "trPr"); - Node trHeight = trPr == null ? null : directChild(trPr, "trHeight"); - return trHeight != null && "exact".equalsIgnoreCase(attribute(trHeight, "hRule")); - } - - private static float rowHeight( - XWPFTableRow row, - ParagraphFonts fonts, - PDFont boldFont, - List widths, - boolean compact, - float rowHeightPadding, - float linePitch) throws IOException { - // Mirror DocxReader.cs: w:trHeight with hRule="exact" is a hard cap — - // Word clips cell content to that height instead of growing the row. - // Without this, a fixed-height business-card/label table expands every - // row to its wrapped content height and overflows the page. - if (rowHeightExact(row)) { - return twipsToPoints(row.getHeight()); - } - float height = twipsToPoints(row.getHeight()); - int column = 0; - for (XWPFTableCell cell : row.getTableCells()) { - if (isVerticallyMerged(cell)) { - column++; - continue; - } - float width = twipsToPoints(cell.getWidth()); - if (width <= 0.0f && column < widths.size()) { - width = widths.get(column); - } - float fontSize = cellFontSize(cell, DEFAULT_TABLE_FONT_SIZE); - float horizontalPadding = compact ? 0.0f : CELL_HORIZONTAL_PADDING; - PDFont cellFont = compact ? fonts.simSun() : resolvedCellFont(cell, fonts, boldFont); - List items = cellItems(cell, fonts, boldFont, width, horizontalPadding, linePitch); - float contentHeight = 0.0f; - for (CellItem item : items) { - if (item.line() != null) { - contentHeight += item.line().advance(linePitch); - } else if (item.picture() != null) { - // Inline pictures advance the cell content flow like a - // line of text (Word grows the row to fit the image). - contentHeight += item.pictureHeight(); - } else { - contentHeight += item.spacing(); - } - } - height = Math.max( - height, - paragraphSpacingBefore(cell) - + contentHeight - + paragraphSpacingAfter(cell) - + (linePitch > 0.0f ? rowHeightPadding : 0.0f)); - column++; - } - return height; - } - - private static float paragraphSpacingBefore(XWPFTableCell cell) { - return cellParagraphs(cell).stream() - .map(paragraph -> twipsToPoints(effectiveSpacing(paragraph).before())) - .max(Float::compare) - .orElse(0.0f); - } - - private static float paragraphSpacingAfter(XWPFTableCell cell) { - return cellParagraphs(cell).stream() - .map(paragraph -> twipsToPoints(effectiveSpacing(paragraph).after())) - .max(Float::compare) - .orElse(0.0f); - } - - private static boolean isCellBold(XWPFTableCell cell) { - return cellParagraphs(cell).stream() - .flatMap(paragraph -> paragraph.getRuns().stream()) - .anyMatch(XWPFRun::isBold); - } - - private static final class CellLine { - private final String text; - private final float fontSize; - private final float advance; - private final String color; - private final PDFont font; - - private CellLine(String text, float fontSize) { - this(text, fontSize, 0.0f, null, null); - } - - private CellLine(String text, float fontSize, float advance, String color, PDFont font) { - this.text = text; - this.fontSize = fontSize; - this.advance = advance; - this.color = color; - this.font = font; - } - - private float advance(float linePitch) { - return advance > 0.0f ? advance : gridLineHeight(fontSize * 1.35f, linePitch); - } - } - - private static List cellLines( - XWPFTableCell cell, - PDFont font, - float width, - float padding) - throws IOException { - List lines = new ArrayList<>(); - for (XWPFParagraph paragraph : cellParagraphs(cell)) { - String text = paragraphText(paragraph).trim(); - float fontSize = paragraphFontSize(paragraph, DEFAULT_TABLE_FONT_SIZE); - if (cell.getCTTc().isSetTcPr() && cell.getCTTc().getTcPr().isSetNoWrap()) { - lines.add(new CellLine(text, fontSize)); - } else { - for (String line : wrap(font, text, fontSize, cellContentWidth(width, padding))) { - lines.add(new CellLine(line, fontSize)); - } - } - } - return lines.isEmpty() ? Collections.singletonList(new CellLine("", DEFAULT_TABLE_FONT_SIZE)) : lines; - } - - static float cellContentWidth(float width, float padding) { - return width - padding; - } - - private static float mergedHeight( - XWPFTable table, - List rowHeights, - int rowIndex, - int cellIndex) { - float height = rowHeights.get(rowIndex); - for (int nextRow = rowIndex + 1; nextRow < table.getRows().size(); nextRow++) { - XWPFTableRow row = table.getRows().get(nextRow); - if (cellIndex >= row.getTableCells().size() || !isMergeContinuation(row.getCell(cellIndex))) { - break; - } - height += rowHeights.get(nextRow); - } - return height; - } - - private static boolean isVerticallyMerged(XWPFTableCell cell) { - return cell.getCTTc().isSetTcPr() && cell.getCTTc().getTcPr().isSetVMerge(); - } - - private static boolean isMergeRestart(XWPFTableCell cell) { - if (!isVerticallyMerged(cell) || cell.getCTTc().getTcPr().getVMerge().getVal() == null) { - return false; - } - return "restart".equals(cell.getCTTc().getTcPr().getVMerge().getVal().toString()); - } - - private static boolean isMergeContinuation(XWPFTableCell cell) { - return isVerticallyMerged(cell) && !isMergeRestart(cell); - } - - static List wrap(PDFont font, String text, float fontSize, float width) throws IOException { - return wrap(font, text, fontSize, width, DEFAULT_AUTO_SPACING); - } - - private static List wrap( - PDFont font, - String text, - float fontSize, - float width, - AutoSpacing autoSpacing) throws IOException { - return wrap(font, text, fontSize, width, width, autoSpacing); - } - - private static List wrap( - PDFont font, - String text, - float fontSize, - float firstLineWidth, - float width, - AutoSpacing autoSpacing) throws IOException { - return wrap(font, text, fontSize, firstLineWidth, width, autoSpacing, false); - } - - private static List wrap( - PDFont font, - String text, - float fontSize, - float firstLineWidth, - float width, - AutoSpacing autoSpacing, - boolean bold) throws IOException { - if (text.isEmpty()) { - return Collections.singletonList(""); - } - List lines = new ArrayList<>(); - StringBuilder line = new StringBuilder(); - for (int offset = 0; offset < text.length();) { - int codePoint = text.codePointAt(offset); - offset += Character.charCount(codePoint); - line.appendCodePoint(codePoint); - while (line.codePointCount(0, line.length()) > 1 - && textWidth(font, line.toString(), fontSize, autoSpacing, bold) - > (lines.isEmpty() ? firstLineWidth : width)) { - int breakOffset = lastWrapBoundary(line); - if (breakOffset <= 0) { - // An unbreakable token wider than the line (e.g. an email - // address): Word/LibreOffice let it overflow instead of - // splitting it mid-word. - break; - } - String completed = stripTrailing(line.substring(0, breakOffset)); - String remainder = stripLeading(line.substring(breakOffset)); - if (!completed.isEmpty()) { - lines.add(completed); - } - line.setLength(0); - line.append(remainder); - } - } - lines.add(line.toString()); - return lines; - } - - private static int lastWrapBoundary(StringBuilder text) { - int rightOffset = text.length(); - int right = text.codePointBefore(rightOffset); - while (rightOffset > 0) { - int leftOffset = text.offsetByCodePoints(rightOffset, -1); - if (leftOffset == 0) { - return -1; - } - int left = text.codePointBefore(leftOffset); - if (isWrapBoundary(left, right)) { - return leftOffset; - } - rightOffset = leftOffset; - right = left; - } - return -1; - } - - private static String stripLeading(String value) { - int index = 0; - while (index < value.length() && Character.isWhitespace(value.charAt(index))) { - index++; - } - return value.substring(index); - } - - private static String stripTrailing(String value) { - int index = value.length(); - while (index > 0 && Character.isWhitespace(value.charAt(index - 1))) { - index--; - } - return value.substring(0, index); - } - - private static boolean isWrapBoundary(int left, int right) { - if (Character.isWhitespace(left) || Character.isWhitespace(right) || left == '-') { - return true; - } - return (isEastAsian(left) || isEastAsian(right)) - && !isOpeningPunctuation(left) - && !isClosingPunctuation(right); - } - - private static boolean isOpeningPunctuation(int codePoint) { - return codePoint == '(' || codePoint == '[' || codePoint == '{' - || codePoint == '\u3008' || codePoint == '\u300a' || codePoint == '\u300c' - || codePoint == '\u300e' || codePoint == '\u3010' || codePoint == '\uff08'; - } - - private static boolean isClosingPunctuation(int codePoint) { - return codePoint == ')' || codePoint == ']' || codePoint == '}' - || codePoint == '\u3001' || codePoint == '\u3002' || codePoint == '\u3009' - || codePoint == '\u300b' || codePoint == '\u300d' || codePoint == '\u300f' - || codePoint == '\u3011' || codePoint == '\uff09'; - } - - private static final class MergeLine { - private final XWPFTableCell cell; - private final int index; - - private MergeLine(XWPFTableCell cell, int index) { - this.cell = cell; - this.index = index; - } - - private XWPFTableCell cell() { - return cell; - } - - private int index() { - return index; - } - } - - private static final class AutoSpacing { - private final boolean latin; - private final boolean digit; - - private AutoSpacing(boolean latin, boolean digit) { - this.latin = latin; - this.digit = digit; - } - - private boolean latin() { - return latin; - } - - private boolean digit() { - return digit; - } - } - - private static final class PageNumberFooter { - private final String prefix; - private final String suffix; - private final float fontSize; - - private PageNumberFooter(String prefix, String suffix, float fontSize) { - this.prefix = prefix; - this.suffix = suffix; - this.fontSize = fontSize; - } - - private String prefix() { - return prefix; - } - - private String suffix() { - return suffix; - } - - private float fontSize() { - return fontSize; - } - - @Override - public boolean equals(Object value) { - if (this == value) { - return true; - } - if (!(value instanceof PageNumberFooter)) { - return false; - } - PageNumberFooter other = (PageNumberFooter) value; - return prefix.equals(other.prefix) - && suffix.equals(other.suffix) - && Float.compare(fontSize, other.fontSize) == 0; - } - - @Override - public int hashCode() { - return 31 * (31 * prefix.hashCode() + suffix.hashCode()) + Float.floatToIntBits(fontSize); - } - } - - private static final class PageMargins { - private final float left; - private final float top; - private final float bottom; - private final float firstPageTopOffset; - - private PageMargins(float left, float top, float bottom, float firstPageTopOffset) { - this.left = left; - this.top = top; - this.bottom = bottom; - this.firstPageTopOffset = firstPageTopOffset; - } - - private float left() { - return left; - } - - private float top() { - return top; - } - - private float bottom() { - return bottom; - } - - private float firstPageTopOffset() { - return firstPageTopOffset; - } - } - - static final class RunSegment { - private final String text; - private final PDFont font; - private final float fontSize; - private final float leadingSpacing; - private final HighlightColor highlight; - private final boolean tab; - private final boolean bold; - private final String color; - - RunSegment( - String text, - PDFont font, - float fontSize, - float leadingSpacing, - HighlightColor highlight, - boolean tab) { - this(text, font, fontSize, leadingSpacing, highlight, tab, false, null); - } - - RunSegment( - String text, - PDFont font, - float fontSize, - float leadingSpacing, - HighlightColor highlight, - boolean tab, - boolean bold) { - this(text, font, fontSize, leadingSpacing, highlight, tab, bold, null); - } - - RunSegment( - String text, - PDFont font, - float fontSize, - float leadingSpacing, - HighlightColor highlight, - boolean tab, - boolean bold, - String color) { - this.text = text; - this.font = font; - this.fontSize = fontSize; - this.leadingSpacing = leadingSpacing; - this.highlight = highlight; - this.tab = tab; - this.bold = bold; - this.color = color; - } - - String text() { - return text; - } - - RunSegment prepend(String prefix) { - return new RunSegment( - prefix + text, font, fontSize, leadingSpacing, highlight, tab, bold, color); - } - - PDFont font() { - return font; - } - - float fontSize() { - return fontSize; - } - - float leadingSpacing() { - return leadingSpacing; - } - - HighlightColor highlight() { - return highlight; - } - - boolean tab() { - return tab; - } - - boolean bold() { - return bold; - } - - String color() { - return color; - } - } - - static final class HighlightColor { - private final float red; - private final float green; - private final float blue; - - HighlightColor(float red, float green, float blue) { - this.red = red; - this.green = green; - this.blue = blue; - } - } - - private static final class FootnoteData { - private final String number; - private final String text; - private final PDFont font; - private final float fontSize; - - private FootnoteData(String number, String text, PDFont font, float fontSize) { - this.number = number; - this.text = text; - this.font = font; - this.fontSize = fontSize; - } - - private float lineHeight() { - return fontSize * 1.2f; - } - - private String displayText() { - return number + " " + text; - } - } - - static final class FloatingCheckbox { - private final float offsetX; - private final float offsetY; - private final float width; - private final float height; - private final float lineWidth; - private final String horizontalRelative; - private final boolean checked; - - private FloatingCheckbox( - float offsetX, - float offsetY, - float width, - float height, - float lineWidth, - String horizontalRelative, - boolean checked) { - this.offsetX = offsetX; - this.offsetY = offsetY; - this.width = width; - this.height = height; - this.lineWidth = lineWidth; - this.horizontalRelative = horizontalRelative; - this.checked = checked; - } - - float offsetX() { - return offsetX; - } - - float offsetY() { - return offsetY; - } - - boolean checked() { - return checked; - } - } - - static final class ParagraphFonts { - private final PDFont fallback; - private final PDFont simSun; - private final PDFont simHei; - private final PDFont kai; - private final PDFont fangSong; - private final PDFont times; - private final PDFont arial; - private final PDFont franklinBook; - private final PDFont franklinDemi; - private final PDFont impact; - private final PDFont sourceSans; - private final String defaultAsciiFamily; - private final String defaultEastAsiaFamily; - - ParagraphFonts( - PDFont fallback, - PDFont simSun, - PDFont simHei, - PDFont kai, - PDFont fangSong, - PDFont times, - PDFont arial, - String defaultAsciiFamily, - String defaultEastAsiaFamily) { - this(fallback, simSun, simHei, kai, fangSong, times, arial, null, null, - defaultAsciiFamily, defaultEastAsiaFamily); - } - - ParagraphFonts( - PDFont fallback, - PDFont simSun, - PDFont simHei, - PDFont kai, - PDFont fangSong, - PDFont times, - PDFont arial, - PDFont franklinBook, - PDFont franklinDemi, - String defaultAsciiFamily, - String defaultEastAsiaFamily) { - this(fallback, simSun, simHei, kai, fangSong, times, arial, franklinBook, franklinDemi, - null, null, defaultAsciiFamily, defaultEastAsiaFamily); - } - - ParagraphFonts( - PDFont fallback, - PDFont simSun, - PDFont simHei, - PDFont kai, - PDFont fangSong, - PDFont times, - PDFont arial, - PDFont franklinBook, - PDFont franklinDemi, - PDFont impact, - PDFont sourceSans, - String defaultAsciiFamily, - String defaultEastAsiaFamily) { - this.fallback = fallback; - this.simSun = simSun; - this.simHei = simHei; - this.kai = kai; - this.fangSong = fangSong; - this.times = times; - this.arial = arial; - this.franklinBook = franklinBook; - this.franklinDemi = franklinDemi; - this.impact = impact; - this.sourceSans = sourceSans; - this.defaultAsciiFamily = defaultAsciiFamily; - this.defaultEastAsiaFamily = defaultEastAsiaFamily; - } - - PDFont fallback() { - return fallback; - } - - PDFont latin() { - String family = defaultAsciiFamily == null ? "" : defaultAsciiFamily.toLowerCase(); - if (family.contains("franklin") && franklinBook != null) { - return franklinBook; - } - if (family.contains("source sans pro") && sourceSans != null) { - return sourceSans; - } - if (family.contains("times") || family.contains("georgia")) { - return times; - } - return arial; - } - - PDFont simSun() { - return simSun; - } - - PDFont franklinBook() { - return franklinBook; - } - - PDFont franklinDemi() { - return franklinDemi; - } - - /** - * The theme major face: Franklin Gothic Demi when the document asks - * for it, otherwise Impact (letterhead templates). Null when neither - * is loaded. - */ - PDFont majorFace() { - if (franklinDemi != null) { - return franklinDemi; - } - return impact; - } - - private boolean isLatinFace(PDFont font) { - return font == arial || font == times || font == franklinBook || font == franklinDemi - || font == impact || font == sourceSans; - } - - private PDFont resolve(XWPFRun run, int codePoint) { - boolean eastAsian = usesEastAsianFontSlot(codePoint); - XWPFRun.FontCharRange range = eastAsian - ? XWPFRun.FontCharRange.eastAsia - : XWPFRun.FontCharRange.ascii; - String family = run.getFontFamily(range); - if (family == null || family.trim().isEmpty()) { - family = eastAsian ? defaultEastAsiaFamily : defaultAsciiFamily; - } - String normalized = family == null ? "" : family.toLowerCase(); - // Word never applies a Latin family (Arial, Times, a theme minor - // font like Franklin Gothic...) to East Asian code points — those - // always render with the eastAsia face. Resolving them against - // the ascii slot leaks a Latin face into CJK text (No glyph). - if (eastAsian) { - if (normalized.contains("\u9ed1\u4f53") || normalized.contains("simhei")) { - return simHei; - } - if (normalized.contains("\u6977\u4f53") || normalized.contains("simkai")) { - return kai; - } - if (normalized.contains("\u4eff\u5b8b") || normalized.contains("simfang")) { - return fangSong; - } - return simSun; - } - if (normalized.contains("impact") && impact != null) { - return impact; - } - if (normalized.contains("source sans pro") && sourceSans != null) { - return sourceSans; - } - if (normalized.contains("franklin")) { - boolean demi = normalized.contains("demi") || normalized.contains("heavy"); - if (demi && franklinDemi != null) { - return franklinDemi; - } - if (franklinBook != null) { - return franklinBook; - } - } - if (normalized.contains("arial")) { - return arial; - } - if (normalized.contains("times")) { - return times; - } - return fallback; - } - } - - private static boolean usesEastAsianFontSlot(int codePoint) { - Character.UnicodeBlock block = Character.UnicodeBlock.of(codePoint); - return isEastAsian(codePoint) - || block == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION - || block == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS; - } - - static PDFont wrappingFont(ParagraphFonts fonts, String text) { - if (text.codePoints().anyMatch(PoiDocxRenderer::usesEastAsianFontSlot)) { - return fonts.simSun(); - } - // Mirror DocxReader.cs: Latin text must wrap with the document's Latin - // font metrics (Times/Arial), not the CJK fallback (SimHei renders Latin - // glyphs at half-width 500/1000). Wrapping with half-width glyphs makes - // every line ~10% narrower than Word, collapsing pagination. - return fonts.latin(); - } - - static List paragraphSegments( - XWPFParagraph paragraph, - ParagraphFonts fonts, - float fallbackFontSize) { - return paragraphSegments(paragraph, fonts, fallbackFontSize, null); - } - - static List paragraphSegments( - XWPFParagraph paragraph, - ParagraphFonts fonts, - float fallbackFontSize, - PDFont boldFont) { - return paragraphSegments(paragraph, fonts, fallbackFontSize, boldFont, false); - } - - private static List paragraphSegments( - XWPFParagraph paragraph, - ParagraphFonts fonts, - float fallbackFontSize, - PDFont boldFont, - boolean preserveTabs) { - List segments = new ArrayList<>(); - AutoSpacing autoSpacing = paragraphAutoSpacing(paragraph); - boolean styleBold = paragraphStyleBold(paragraph); - boolean styleMajorFont = paragraphStyleMajorFont(paragraph); - String styleColor = paragraphStyleColor(paragraph); - for (XWPFRun run : paragraph.getRuns()) { - String text = preserveTabs ? runText(run) : renderableText(runText(run)); - if (text.isEmpty()) { - continue; - } - float fontSize = run.getFontSizeAsDouble() == null || run.getFontSizeAsDouble() <= 0.0 - ? fallbackFontSize - : run.getFontSizeAsDouble().floatValue(); - StringBuilder segmentText = new StringBuilder(); - PDFont segmentFont = null; - float segmentLeadingSpacing = 0.0f; - boolean runBold = (run.isBold() || styleBold) && boldFont != null; - String color = runColor(run); - if (color == null) { - color = styleColor; - } - int previous = -1; - for (int offset = 0; offset < text.length();) { - int codePoint = text.codePointAt(offset); - offset += Character.charCount(codePoint); - if (codePoint == '\t') { - if (segmentText.length() > 0) { - segments.add(new RunSegment( - segmentText.toString(), segmentFont, fontSize, segmentLeadingSpacing, - runHighlight(run), false, runBold, color)); - segmentText.setLength(0); - } - segments.add(new RunSegment("\t", null, fontSize, 0.0f, null, true)); - segmentFont = null; - segmentLeadingSpacing = 0.0f; - previous = -1; - continue; - } - PDFont majorFace = fonts.majorFace(); - PDFont codePointFont = runBold - ? boldFont - : styleMajorFont - && majorFace != null - && !usesEastAsianFontSlot(codePoint) - ? majorFace - : fonts.resolve(run, codePoint); - if (segmentFont != null && codePointFont != segmentFont) { - float spacing = isEastAsianLatinBoundary(previous, codePoint, autoSpacing) - ? fontSize * 0.25f - : 0.0f; - segments.add(new RunSegment( - segmentText.toString(), segmentFont, fontSize, segmentLeadingSpacing, - runHighlight(run), false, runBold, color)); - segmentText.setLength(0); - segmentFont = codePointFont; - segmentLeadingSpacing = spacing; - segmentText.appendCodePoint(codePoint); - } else { - segmentFont = codePointFont; - segmentText.appendCodePoint(codePoint); - } - previous = codePoint; - } - if (segmentText.length() > 0) { - segments.add(new RunSegment( - segmentText.toString(), segmentFont, fontSize, segmentLeadingSpacing, - runHighlight(run), false, runBold, color)); - } - } - return segments; - } - - static String paragraphText(XWPFParagraph paragraph) { - boolean needsSemanticRuns = paragraph.getRuns().stream() - .anyMatch(run -> run.getCTR().sizeOfFootnoteReferenceArray() > 0 - || run.getCTR().sizeOfSymArray() > 0); - if (!needsSemanticRuns) { - return normalizeRunText(paragraph.getText()); - } - return paragraph.getRuns().stream() - .map(PoiDocxRenderer::runText) - .collect(Collectors.joining()); - } - - static String runText(XWPFRun run) { - if (run.getCTR().sizeOfFootnoteReferenceArray() > 0) { - return run.getCTR().getFootnoteReferenceList().stream() - .map(reference -> reference.getId().toString()) - .collect(Collectors.joining()); - } - if (run.getCTR().sizeOfSymArray() > 0) { - return run.getCTR().getSymList().stream() - .map(PoiDocxRenderer::symbolText) - .collect(Collectors.joining()); - } - return normalizeRunText(run.text()); - } - - private static String normalizeRunText(String text) { - return Normalizer.normalize(text.replace('\r', ' ').replace('\n', ' '), Normalizer.Form.NFC); - } - - static float nextDefaultTabStop(float position) { - return ((float) Math.floor(position / 36.0f) + 1.0f) * 36.0f; - } - - private static String symbolText(CTSym symbol) { - byte[] value = symbol.getChar(); - if (value == null || value.length == 0) { - return ""; - } - int code = 0; - for (byte part : value) { - code = code << 8 | part & 0xff; - } - if ("Wingdings".equalsIgnoreCase(symbol.getFont()) && code == 0xf0fc) { - return "\u2713"; - } - return Character.toString((char) code); - } - - private static Map footnotes(XWPFDocument source, PDFont font) { - Map footnotes = new LinkedHashMap<>(); - for (XWPFFootnote footnote : source.getFootnotes()) { - BigInteger id = footnote.getId(); - if (id == null || id.signum() < 0) { - continue; - } - String text = footnote.getParagraphs().stream() - .flatMap(paragraph -> paragraph.getRuns().stream()) - .map(PoiDocxRenderer::footnoteRunText) - .collect(Collectors.joining()) - .trim(); - float fontSize = footnote.getParagraphs().isEmpty() - ? 10.0f - : paragraphFontSize(footnote.getParagraphs().get(0), 10.0f); - footnotes.put(id.toString(), new FootnoteData(id.toString(), text, font, fontSize)); - } - return footnotes; - } - - private static String footnoteRunText(XWPFRun run) { - if (run.getCTR().sizeOfFootnoteRefArray() == 0) { - return runText(run); - } - return java.util.Arrays.stream(run.getCTR().getTArray()) - .map(text -> text.getStringValue()) - .collect(Collectors.joining()); - } - - static HighlightColor runHighlight(XWPFRun run) { - if (run.getTextHighlightColor() == null) { - return null; - } - String color = run.getTextHighlightColor().toString().toLowerCase(); - if ("yellow".equals(color)) { - return new HighlightColor(1.0f, 1.0f, 0.0f); - } - if ("green".equals(color)) { - return new HighlightColor(0.0f, 1.0f, 0.0f); - } - if ("cyan".equals(color)) { - return new HighlightColor(0.0f, 1.0f, 1.0f); - } - if ("magenta".equals(color)) { - return new HighlightColor(1.0f, 0.0f, 1.0f); - } - if ("red".equals(color)) { - return new HighlightColor(1.0f, 0.0f, 0.0f); - } - if ("blue".equals(color)) { - return new HighlightColor(0.0f, 0.0f, 1.0f); - } - return null; - } - - static PDFont resolvedCellFont(XWPFTableCell cell, ParagraphFonts fonts, PDFont boldFont) { - PDFont resolved = null; - PDFont majorFace = fonts.majorFace(); - for (XWPFParagraph paragraph : cellParagraphs(cell)) { - boolean styleMajorFont = paragraphStyleMajorFont(paragraph); - for (XWPFRun run : paragraph.getRuns()) { - String text = renderableText(run.text()); - for (int offset = 0; offset < text.length();) { - int codePoint = text.codePointAt(offset); - offset += Character.charCount(codePoint); - PDFont candidate = run.isBold() - ? boldFont - : styleMajorFont - && majorFace != null - && !usesEastAsianFontSlot(codePoint) - ? majorFace - : fonts.resolve(run, codePoint); - if (resolved != null && resolved != candidate) { - // Mixed Latin faces (e.g. a Demi heading above Book - // body text) must keep a Latin face; only genuinely - // mixed CJK/Latin cells fall back to SimSun. - if (fonts.isLatinFace(resolved) && fonts.isLatinFace(candidate)) { - return fonts.latin(); - } - return isCellBold(cell) ? boldFont : fonts.simSun(); - } - resolved = candidate; - } - } - } - if (resolved == null) { - // Paragraphs whose runs live inside run-level SDTs expose no runs - // to POI; derive the face from the style theme font instead. - for (XWPFParagraph paragraph : cellParagraphs(cell)) { - if (paragraphStyleMajorFont(paragraph) && majorFace != null) { - return majorFace; - } - } - if (isCellBold(cell)) { - return boldFont; - } - return cell.getText().codePoints().anyMatch(codePoint -> codePoint > 255) - ? fonts.simSun() - : fonts.latin(); - } - return resolved; - } - - private static AutoSpacing paragraphAutoSpacing(XWPFParagraph paragraph) { - if (!paragraph.getCTP().isSetPPr()) { - return DEFAULT_AUTO_SPACING; - } - CTPPr properties = paragraph.getCTP().getPPr(); - boolean latin = !properties.isSetAutoSpaceDE() - || onOffValue(properties.getAutoSpaceDE().getVal()); - boolean digit = !properties.isSetAutoSpaceDN() - || onOffValue(properties.getAutoSpaceDN().getVal()); - return new AutoSpacing(latin, digit); - } - - private static boolean onOffValue(Object value) { - return value == null - || !("0".equals(value.toString()) || "false".equalsIgnoreCase(value.toString()) - || "off".equalsIgnoreCase(value.toString())); - } - - private static String latinText(String text) { - return text.codePoints() - .filter(codePoint -> codePoint <= 0xff) - .collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append) - .toString(); - } - - private static PDFont loadDocumentLatinFont( - PDDocument document, - List> text, - String family) { - String normalized = family == null ? "" : family.toLowerCase(); - if (normalized.contains("times") || normalized.contains("georgia")) { - return SimplePdfTextRenderer.loadSystemFont( - document, text, "times.ttf", "NotoSerif-Regular.ttf"); - } - // Explicit CJK families must not route into the Latin layout path. - if (cjkFamilyName(normalized)) { - return null; - } - // Office cloud fonts (Source Sans Pro, Aptos, ...) live in the - // Microsoft 365 cloud font cache even when absent from - // C:\Windows\Fonts. Prefer the real face so glyphs and wrap widths - // match Word; Calibri documents keep the calibrated width tables. - if (!normalized.isEmpty() && !normalized.contains("calibri")) { - PDFont familyFont = SimplePdfTextRenderer.loadSystemFontByFamily( - document, text, family); - if (familyFont != null) { - return familyFont; - } - } - // Theme defaults (minorHAnsi, e.g. Calibri/Aptos/Franklin Gothic Book) - // and unknown western families use Arial metrics — mirrors the .NET - // fallback so that Latin documents take the Word-paragraph layout path - // instead of the CJK grid/margin path. Franklin Gothic documents later - // swap in the real FRABK face once it is loaded. - return SimplePdfTextRenderer.loadSystemFont( - document, text, "arial.ttf", "NotoSans-Regular.ttf"); - } - - private static boolean cjkFamilyName(String normalized) { - return normalized.contains("simsun") - || normalized.contains("simhei") - || normalized.contains("simkai") - || normalized.contains("simfang") - || normalized.contains("\u5b8b\u4f53") - || normalized.contains("\u9ed1\u4f53") - || normalized.contains("\u6977\u4f53") - || normalized.contains("\u4eff\u5b8b") - || normalized.contains("ming") - || normalized.contains("mincho") - || normalized.contains("batang") - || normalized.contains("gulim") - || normalized.contains("dotum") - || normalized.contains("malgun") - || normalized.contains("dengxian") - || normalized.contains("\u7b49\u7ebf") - || normalized.contains("\u65b0\u7d30\u660e\u9ad4") - || normalized.contains("\u5fae\u8edf\u6b63\u9ed1\u9ad4") - || normalized.contains("\u5fae\u8f6f\u96c5\u9ed1") - || normalized.contains("\u96c5\u9ed1") - || normalized.contains("gothic") && !normalized.contains("franklin"); - } - - private static String defaultFontFamily(XWPFDocument document, XWPFRun.FontCharRange range) { - if (document.getStyles() == null || document.getStyles().getCtStyles() == null) { - return null; - } - XWPFStyle normalStyle = document.getStyles().getStyle("Normal"); - if (normalStyle != null && normalStyle.getCTStyle().isSetRPr()) { - String family = fontFamily(normalStyle.getCTStyle().getRPr(), range); - if (family != null) { - return family; - } - } - CTStyles styles = document.getStyles().getCtStyles(); - if (!styles.isSetDocDefaults() - || !styles.getDocDefaults().isSetRPrDefault() - || !styles.getDocDefaults().getRPrDefault().isSetRPr()) { - return null; - } - return fontFamily(styles.getDocDefaults().getRPrDefault().getRPr(), range); - } - - private static String fontFamily(CTRPr properties, XWPFRun.FontCharRange range) { - if (properties.sizeOfRFontsArray() == 0) { - return null; - } - CTFonts fonts = properties.getRFontsArray(0); - switch (range) { - case ascii: - return fonts.isSetAscii() ? fonts.getAscii() : fonts.getHAnsi(); - case eastAsia: - return fonts.isSetEastAsia() ? fonts.getEastAsia() : null; - default: - return null; - } - } - - private static float paragraphFontSize(XWPFParagraph paragraph, float fallback) { - Float runSize = paragraph.getRuns().stream() - .map(XWPFRun::getFontSizeAsDouble) - .filter(size -> size != null && size > 0.0) - .map(Double::floatValue) - .max(Float::compare) - .orElse(null); - if (runSize != null) { - return runSize; - } - if (paragraph.getCTP().isSetPPr() - && paragraph.getCTP().getPPr().isSetRPr() - && paragraph.getCTP().getPPr().getRPr().sizeOfSzArray() > 0) { - try { - return Float.parseFloat( - paragraph.getCTP().getPPr().getRPr().getSzArray(0).getVal().toString()) / 2.0f; - } catch (NumberFormatException ignored) { - return fallback; - } - } - // Mirror the .NET effective-size chain: direct run -> paragraph mark -> - // paragraph style -> Normal style -> docDefaults. Without this, a body - // paragraph that inherits its size from Normal (e.g. 12pt) falls back - // to the 11pt default, making every line ~0.5pt shorter and collapsing - // pagination. - XWPFStyles styles = paragraph.getDocument().getStyles(); - if (styles != null) { - String styleId = paragraph.getStyle(); - if (styleId != null) { - Float styleSize = styleFontSize(styles.getStyle(styleId)); - if (styleSize != null) { - return styleSize; - } - } - Float normalSize = styleFontSize(styles.getStyle("Normal")); - if (normalSize != null) { - return normalSize; - } - Float docDefaultSize = docDefaultsFontSize(styles.getCtStyles()); - if (docDefaultSize != null) { - return docDefaultSize; - } - } - return fallback; - } - - private static Float styleFontSize(XWPFStyle style) { - if (style == null || style.getCTStyle() == null || !style.getCTStyle().isSetRPr()) { - return null; - } - CTRPr properties = style.getCTStyle().getRPr(); - if (properties.sizeOfSzArray() == 0) { - return null; - } - try { - return Float.parseFloat(properties.getSzArray(0).getVal().toString()) / 2.0f; - } catch (NumberFormatException ignored) { - return null; - } - } - - private static Float docDefaultsFontSize(CTStyles styles) { - if (styles == null || !styles.isSetDocDefaults() - || !styles.getDocDefaults().isSetRPrDefault() - || !styles.getDocDefaults().getRPrDefault().isSetRPr()) { - return null; - } - CTRPr properties = styles.getDocDefaults().getRPrDefault().getRPr(); - if (properties.sizeOfSzArray() == 0) { - return null; - } - try { - return Float.parseFloat(properties.getSzArray(0).getVal().toString()) / 2.0f; - } catch (NumberFormatException ignored) { - return null; - } - } - - /** - * Mirrors Word's effective bold: a run is bold if its own rPr says so, or - * if the paragraph mark or paragraph style (e.g. Heading2) turns bold on. - * POI's XWPFRun#isBold only reads the direct run rPr, so heading styles - * would otherwise render non-bold. - */ - private static boolean paragraphStyleBold(XWPFParagraph paragraph) { - if (paragraph.getCTP().isSetPPr() && paragraph.getCTP().getPPr().isSetRPr()) { - CTParaRPr mark = paragraph.getCTP().getPPr().getRPr(); - if (isBoldOn(mark.sizeOfBArray() == 0 ? null : mark.getBArray(0))) { - return true; - } - } - if (paragraph.getDocument().getStyles() == null) { - return false; - } - String styleId = paragraph.getStyle(); - if (styleId != null) { - XWPFStyle style = paragraph.getDocument().getStyles().getStyle(styleId); - if (style != null && style.getCTStyle() != null && style.getCTStyle().isSetRPr()) { - CTRPr properties = style.getCTStyle().getRPr(); - if (isBoldOn(properties.sizeOfBArray() == 0 ? null : properties.getBArray(0))) { - return true; - } - } - } - return false; - } - - private static boolean isBoldOn(CTOnOff bold) { - if (bold == null) { - return false; - } - Object value = bold.getVal(); - return value == null - || !"0".equals(value.toString()) && !"false".equalsIgnoreCase(value.toString()); - } - - /** - * Mirrors Word's theme font selection: a paragraph style whose rFonts - * references asciiTheme/hAnsiTheme = majorHAnsi renders with the theme's - * major font (headings, e.g. Franklin Gothic Demi) even without explicit - * bold or font names on the runs. - */ - private static boolean paragraphStyleMajorFont(XWPFParagraph paragraph) { - if (paragraph.getDocument().getStyles() == null) { - return false; - } - String styleId = paragraph.getStyle(); - if (styleId == null) { - return false; - } - XWPFStyle style = paragraph.getDocument().getStyles().getStyle(styleId); - if (style == null || style.getCTStyle() == null || !style.getCTStyle().isSetRPr()) { - return false; - } - CTRPr properties = style.getCTStyle().getRPr(); - if (properties.sizeOfRFontsArray() == 0) { - return false; - } - CTFonts fonts = properties.getRFontsArray(0); - return fonts.isSetAsciiTheme() && "majorHAnsi".equals(fonts.getAsciiTheme().toString()) - || fonts.isSetHAnsiTheme() && "majorHAnsi".equals(fonts.getHAnsiTheme().toString()); - } - - /** - * Mirrors Word's contextualSpacing flag: set on the paragraph itself or on - * its style (e.g. ListBullet). Between consecutive same-style paragraphs, - * Word suppresses the spacing-after of the first one. - */ - private static boolean paragraphContextualSpacing(XWPFParagraph paragraph) { - Node pPr = directChild(paragraph.getCTP().getDomNode(), "pPr"); - if (directChild(pPr, "contextualSpacing") != null) { - return true; - } - if (paragraph.getDocument().getStyles() == null) { - return false; - } - String styleId = paragraph.getStyle(); - if (styleId == null) { - return false; - } - XWPFStyle style = paragraph.getDocument().getStyles().getStyle(styleId); - if (style == null || style.getCTStyle() == null) { - return false; - } - Node stylePPr = directChild(style.getCTStyle().getDomNode(), "pPr"); - return directChild(stylePPr, "contextualSpacing") != null; - } - - /** - * Mirrors Word's keepNext: set on the paragraph pPr or its style pPr - * (e.g. Heading2/Heading3). Prevents the paragraph from being orphaned at - * the bottom of a page. - */ - private static boolean paragraphKeepNext(XWPFParagraph paragraph) { - Node pPr = directChild(paragraph.getCTP().getDomNode(), "pPr"); - if (keepNextOn(directChild(pPr, "keepNext"))) { - return true; - } - if (paragraph.getDocument().getStyles() == null) { - return false; - } - String styleId = paragraph.getStyle(); - if (styleId == null) { - return false; - } - XWPFStyle style = paragraph.getDocument().getStyles().getStyle(styleId); - if (style == null || style.getCTStyle() == null) { - return false; - } - Node stylePPr = directChild(style.getCTStyle().getDomNode(), "pPr"); - return keepNextOn(directChild(stylePPr, "keepNext")); - } - - private static boolean keepNextOn(Node node) { - if (node == null) { - return false; - } - String value = attribute(node, "val"); - return value == null || (!"0".equals(value) && !"false".equalsIgnoreCase(value)); - } - - /** - * Returns the run's explicit w:color/w:val hex value, or null when the run - * has no color (or "auto", which resets to the paragraph default). Read via - * DOM to avoid materializing CTColor from the lite schema. - */ - private static String runColor(XWPFRun run) { - Node rPr = directChild(run.getCTR().getDomNode(), "rPr"); - Node color = directChild(rPr, "color"); - String value = attribute(color, "val"); - if (value == null || value.isEmpty() || value.equalsIgnoreCase("auto")) { - return null; - } - return value; - } - - /** - * Mirrors Word's paragraph-level color: runs without an explicit color - * inherit the paragraph style's rPr/w:color (e.g. Heading2 = 4F81BD blue), - * then the Normal style's color (e.g. this template's 171717 body ink). - * Resolved via DOM so no theme mapping is needed when w:val is present. - */ - private static String paragraphStyleColor(XWPFParagraph paragraph) { - if (paragraph.getDocument().getStyles() == null) { - return null; - } - String styleId = paragraph.getStyle(); - if (styleId != null) { - String styleColor = styleColor(paragraph, styleId); - if (styleColor != null) { - return styleColor; - } - } - return styleColor(paragraph, "Normal"); - } - - private static String styleColor(XWPFParagraph paragraph, String styleId) { - XWPFStyle style = paragraph.getDocument().getStyles().getStyle(styleId); - if (style == null || style.getCTStyle() == null) { - return null; - } - Node rPr = directChild(style.getCTStyle().getDomNode(), "rPr"); - Node color = directChild(rPr, "color"); - String value = attribute(color, "val"); - if (value == null || value.isEmpty() || value.equalsIgnoreCase("auto")) { - return null; - } - return value; - } - - private static void applyTextColor(PDPageContentStream content, String hex) throws IOException { - if (hex == null || hex.isEmpty()) { - content.setNonStrokingColor(0.0f, 0.0f, 0.0f); - return; - } - try { - int value = Integer.parseInt(hex, 16); - content.setNonStrokingColor( - ((value >> 16) & 0xFF) / 255.0f, - ((value >> 8) & 0xFF) / 255.0f, - (value & 0xFF) / 255.0f); - } catch (NumberFormatException ignored) { - content.setNonStrokingColor(0.0f, 0.0f, 0.0f); - } - } - - /** - * Resolves a paragraph's list bullet marker, or null when the paragraph is - * not part of a bulleted list. Returns a renderable bullet (U+2022) that - * the Latin fonts embed, replacing Word's private-use Wingdings/Symbol - * bullet codepoints (e.g. \uF0B7) that standard text fonts cannot draw. - */ - private static String paragraphBullet(XWPFParagraph paragraph) { - BigInteger numId = paragraphNumberingId(paragraph); - if (numId == null) { - return null; - } - XWPFNumbering numbering = paragraph.getDocument().getNumbering(); - if (numbering == null) { - return null; - } - BigInteger abstractId = numbering.getAbstractNumID(numId); - if (abstractId == null) { - return null; - } - XWPFAbstractNum abstractNum = numbering.getAbstractNum(abstractId); - if (abstractNum == null || abstractNum.getCTAbstractNum() == null) { - return null; - } - CTAbstractNum definition = abstractNum.getCTAbstractNum(); - if (definition.sizeOfLvlArray() == 0 || definition.getLvlArray(0).getNumFmt() == null - || definition.getLvlArray(0).getLvlText() == null) { - return null; - } - CTLvl level = definition.getLvlArray(0); - String format = level.getNumFmt().getVal() == null - ? null - : level.getNumFmt().getVal().toString(); - if (!"bullet".equalsIgnoreCase(format)) { - return null; - } - String text = level.getLvlText().getVal(); - if (text == null || text.isEmpty()) { - return null; - } - return text.chars().anyMatch(cp -> cp >= 0xF000 && cp <= 0xF8FF) - ? "\u2022" - : text; - } - - private static BigInteger paragraphNumberingId(XWPFParagraph paragraph) { - if (paragraph.getCTP().isSetPPr() && paragraph.getCTP().getPPr().isSetNumPr() - && paragraph.getCTP().getPPr().getNumPr().isSetNumId()) { - return paragraph.getCTP().getPPr().getNumPr().getNumId().getVal(); - } - if (paragraph.getDocument().getStyles() == null) { - return null; - } - String styleId = paragraph.getStyle(); - if (styleId == null) { - return null; - } - XWPFStyle style = paragraph.getDocument().getStyles().getStyle(styleId); - if (style != null && style.getCTStyle() != null && style.getCTStyle().isSetPPr() - && style.getCTStyle().getPPr().isSetNumPr() - && style.getCTStyle().getPPr().getNumPr().isSetNumId()) { - return style.getCTStyle().getPPr().getNumPr().getNumId().getVal(); - } - return null; - } - - private static float cellFontSize(XWPFTableCell cell, float fallback) { - return cellParagraphs(cell).stream() - .map(paragraph -> paragraphFontSize(paragraph, fallback)) - .max(Float::compare) - .orElse(fallback); - } - - private static PageMargins pageMargins( - XWPFDocument document, - float fallback, - boolean landscape, - boolean useWordParagraphLayout) { - CTBody body = document.getDocument().getBody(); - if (!body.isSetSectPr() || !body.getSectPr().isSetPgMar()) { - return new PageMargins( - fallback, fallback, fallback, useWordParagraphLayout ? 0.0f : 10.0f); - } - CTPageMar margins = body.getSectPr().getPgMar(); - float left = twipsValue(margins.getLeft(), fallback); - if (!landscape && !useWordParagraphLayout) { - return new PageMargins(left, left, left, 10.0f); - } - float top = twipsValue(margins.getTop(), left); - float bottom = twipsValue(margins.getBottom(), left); - return new PageMargins(left, top, bottom, 0.0f); - } - - private static float twipsValue(Object value, float fallback) { - if (value == null) { - return fallback; - } - try { - return Float.parseFloat(value.toString()) / 20.0f; - } catch (NumberFormatException exception) { - return fallback; - } - } - - private static float documentLinePitch(XWPFDocument document) { - CTBody body = document.getDocument().getBody(); - if (!body.isSetSectPr() || !body.getSectPr().isSetDocGrid() - || body.getSectPr().getDocGrid().getLinePitch() == null) { - return 0.0f; - } - // Mirror DocxReader.cs: only CJK line-grid types activate line snapping. - // A plain w:docGrid (type omitted/default) must not inflate line heights. - STDocGrid.Enum gridType = body.getSectPr().getDocGrid().getType(); - if (gridType == null - || (!gridType.equals(STDocGrid.LINES) - && !gridType.equals(STDocGrid.LINES_AND_CHARS) - && !gridType.equals(STDocGrid.SNAP_TO_CHARS))) { - return 0.0f; - } - try { - return Float.parseFloat(body.getSectPr().getDocGrid().getLinePitch().toString()) / 20.0f; - } catch (NumberFormatException exception) { - return 0.0f; - } - } - - private static PageNumberFooter pageNumberFooter(XWPFDocument document) { - if (document.getFooterList().isEmpty()) { - return null; - } - PageNumberFooter result = null; - float fontSize = footerFontSize(document); - for (XWPFFooter footer : document.getFooterList()) { - boolean hasPageField = descendantElementText(footer, "instrText").stream() - .map(String::trim) - .anyMatch(instruction -> PAGE_FIELD.matcher(instruction).find()); - if (!hasPageField) { - return null; - } - String cachedText = footer.getText().trim(); - if (cachedText.isEmpty()) { - cachedText = String.join("", descendantElementText(footer, "t")).trim(); - } - Matcher cachedPage = CACHED_PAGE_NUMBER.matcher(cachedText); - if (!cachedPage.matches()) { - continue; - } - PageNumberFooter candidate = new PageNumberFooter( - cachedPage.group(1), cachedPage.group(3), fontSize); - if (result != null && !result.equals(candidate)) { - return null; - } - result = candidate; - } - return result == null ? new PageNumberFooter("", "", fontSize) : result; - } - - private static float footerFontSize(XWPFDocument document) { - if (document.getStyles() != null) { - for (String styleId : new String[] {"FooterChar", "Footer", "Normal"}) { - XWPFStyle style = document.getStyles().getStyle(styleId); - if (style == null || !style.getCTStyle().isSetRPr()) { - continue; - } - CTRPr properties = style.getCTStyle().getRPr(); - if (properties.sizeOfSzArray() > 0) { - try { - return Float.parseFloat(properties.getSzArray(0).getVal().toString()) / 2.0f; - } catch (NumberFormatException ignored) { - // Try the next inherited style. - } - } - } - } - return 9.0f; - } - - private static List descendantElementText(XWPFFooter footer, String localName) { - List values = new ArrayList<>(); - try (XmlCursor cursor = footer._getHdrFtr().newCursor()) { - while (cursor.toNextToken() != XmlCursor.TokenType.NONE) { - if (cursor.isStart() - && cursor.getName() != null - && localName.equals(cursor.getName().getLocalPart())) { - values.add(cursor.getTextValue()); - } - } - } - return values; - } - - private static float pageFooterDistance(XWPFDocument document, float fallback) { - CTBody body = document.getDocument().getBody(); - if (!body.isSetSectPr() || !body.getSectPr().isSetPgMar() - || body.getSectPr().getPgMar().getFooter() == null) { - return fallback; - } - try { - return Float.parseFloat(body.getSectPr().getPgMar().getFooter().toString()) / 20.0f; - } catch (NumberFormatException exception) { - return fallback; - } - } - - private static float textWidth(PDFont font, String text, float fontSize) throws IOException { - return textWidth(font, text, fontSize, DEFAULT_AUTO_SPACING); - } - - private static float textWidth( - PDFont font, - String text, - float fontSize, - AutoSpacing autoSpacing) throws IOException { - return textWidth(font, text, fontSize, autoSpacing, false); - } - - private static float textWidth( - PDFont font, - String text, - float fontSize, - AutoSpacing autoSpacing, - boolean bold) throws IOException { - // Mirrors DocxToPdfConverter.EstimateWrapTextWidth: wrap decisions use - // calibrated per-character width tables, not the actual embedded font's - // advances. Actual TTF advances drift from Word's metrics by a few - // percent and collapse pagination over many lines. - // - // Path selection mirrors the .NET state flags: - // - Calibri-default document: Calibri table x0.977, except serif runs - // which use the Times table with -8.8 units/letter kerning - // (s_serifRunInCalibri). - // - Other defaults (e.g. Times New Roman): raw Helvetica table scaled - // down per the .NET latin-fraction reduction (serif default 10%, - // sans default 8%, bold 5%, CJK 27%). - boolean calibriDefault = Boolean.TRUE.equals(CALIBRI_DEFAULT.get()); - if (calibriDefault) { - return calibratedTextWidth(font, text, fontSize, autoSpacing, bold); - } - return helveticaTextWidth(font, text, fontSize, autoSpacing, bold); - } - - private static float calibratedTextWidth( - PDFont font, - String text, - float fontSize, - AutoSpacing autoSpacing, - boolean bold) throws IOException { - boolean useTimesWidths = serifFont(font); - int[] table = useTimesWidths ? TIMES_ROMAN_WIDTHS : CALIBRI_WIDTHS; - float totalUnits = 0.0f; - int kernable = 0; - for (int offset = 0; offset < text.length();) { - int codePoint = text.codePointAt(offset); - offset += Character.charCount(codePoint); - int width = calibratedCharWidth(codePoint, table); - totalUnits += width; - if (useTimesWidths && width != 1000 && isKernable(codePoint)) { - kernable++; - } - } - if (useTimesWidths) { - // Approximate kerning/hinting: ~8.8 units per kernable letter/digit. - totalUnits -= kernable * 8.8f; - } else { - totalUnits *= 0.977f; - } - if (bold) { - totalUnits *= useTimesWidths ? 1.06f : 1.03f; - } - return totalUnits / 1000.0f * fontSize - + eastAsianBoundaryCount(text, autoSpacing) * fontSize * 0.25f; - } - - private static float helveticaTextWidth( - PDFont font, - String text, - float fontSize, - AutoSpacing autoSpacing, - boolean bold) throws IOException { - if (font instanceof PDType0Font) { - // Word lays out with the same TTF advances as the embedded font - // (Times New Roman etc.), so for real document fonts use the - // actual metrics. The Helvetica table stays as a fallback for - // Standard14 fonts (unit tests) where getStringWidth is still - // usable but historically mismatched Word's Times metrics. - float width = font.getStringWidth(text) / 1000.0f * fontSize; - if (bold) { - width *= serifFont(font) ? 1.06f : 1.03f; - } - return width + eastAsianBoundaryCount(text, autoSpacing) * fontSize * 0.25f; - } - boolean hasCjk = text.codePoints().anyMatch(PoiDocxRenderer::usesEastAsianFontSlot); - float latinUnits = 0.0f; - float totalUnits = 0.0f; - for (int offset = 0; offset < text.length();) { - int codePoint = text.codePointAt(offset); - offset += Character.charCount(codePoint); - int width = calibratedCharWidth(codePoint, HELVETICA_WIDTHS); - float actual = hasCjk && codePoint == ' ' ? 500.0f : width; - totalUnits += actual; - if (!(width == 1000 && usesEastAsianFontSlot(codePoint)) && codePoint != '\u2009') { - latinUnits += actual; - } - } - if (latinUnits > 0.0f && totalUnits > 0.0f) { - float latinFraction = latinUnits / totalUnits; - float reduction = hasCjk - ? 0.27f - : bold ? 0.05f : Boolean.TRUE.equals(SERIF_DEFAULT.get()) ? 0.10f : 0.08f; - totalUnits *= 1.0f - latinFraction * reduction; - } - return totalUnits / 1000.0f * fontSize - + eastAsianBoundaryCount(text, autoSpacing) * fontSize * 0.25f; - } - - private static boolean serifFamily(String family) { - return family.contains("times") - || family.contains("georgia") - || family.contains("cambria") - || family.contains("palatino") - || family.contains("garamond"); - } - - private static int calibratedCharWidth(int codePoint, int[] table) { - if (codePoint >= ' ' && codePoint <= '~') { - return table[codePoint - ' ']; - } - if (usesEastAsianFontSlot(codePoint)) { - return 1000; - } - return 500; - } - - private static boolean isKernable(int codePoint) { - return codePoint >= 'A' && codePoint <= 'Z' - || codePoint >= 'a' && codePoint <= 'z' - || codePoint >= '0' && codePoint <= '9'; - } - - private static boolean serifFont(PDFont font) { - String name = font.getName() == null ? "" : font.getName().toLowerCase(); - return name.contains("times") || name.contains("georgia") || name.contains("serif"); - } - - /** - * Font ascent as a fraction of the font size. Word's first line on a page - * sits on baseline = topMargin + fontSize * ascent (Times = 0.891), not - * topMargin + fontSize. Falls back to 0.8 for fonts without a descriptor - * (Standard14 unit-test fonts). - */ - private static float fontAscentRatio(PDFont font) throws IOException { - if (font.getFontDescriptor() != null) { - return font.getFontDescriptor().getAscent() / 1000.0f; - } - return serifFont(font) ? 0.891f : 0.8f; - } - - static int eastAsianBoundaryCount(String text) { - return eastAsianBoundaryCount(text, DEFAULT_AUTO_SPACING); - } - - private static int eastAsianBoundaryCount(String text, AutoSpacing autoSpacing) { - int boundaries = 0; - int previous = -1; - for (int offset = 0; offset < text.length();) { - int codePoint = text.codePointAt(offset); - offset += Character.charCount(codePoint); - if (previous >= 0 && isEastAsianLatinBoundary(previous, codePoint, autoSpacing)) { - boundaries++; - } - previous = codePoint; - } - return boundaries; - } - - private static boolean isEastAsianLatinBoundary(int left, int right, AutoSpacing autoSpacing) { - if (isEastAsian(left)) { - return isSpacedLatinOrDigit(right, autoSpacing); - } - return isSpacedLatinOrDigit(left, autoSpacing) && isEastAsian(right); - } - - private static boolean isSpacedLatinOrDigit(int codePoint, AutoSpacing autoSpacing) { - return Character.isDigit(codePoint) - ? autoSpacing.digit() - : autoSpacing.latin() - && Character.UnicodeScript.of(codePoint) == Character.UnicodeScript.LATIN; - } - - private static boolean isEastAsian(int codePoint) { - Character.UnicodeScript script = Character.UnicodeScript.of(codePoint); - return script == Character.UnicodeScript.HAN - || script == Character.UnicodeScript.HIRAGANA - || script == Character.UnicodeScript.KATAKANA - || script == Character.UnicodeScript.HANGUL; - } - - static String renderableText(String text) { - return Normalizer.normalize( - text.replace('\r', ' ').replace('\n', ' ').replace('\t', ' '), - Normalizer.Form.NFC); - } - - private static float gridLineHeight(float naturalHeight, float linePitch) { - if (linePitch <= 0.0f) { - return naturalHeight; - } - return (float) Math.ceil(naturalHeight / linePitch) * linePitch; - } - - static float paragraphLineHeight( - XWPFParagraph paragraph, - float fontSize, - float naturalHeight, - float linePitch, - boolean useWordParagraphLayout) { - return paragraphLineHeight( - paragraph, fontSize, naturalHeight, linePitch, useWordParagraphLayout, false); - } - - static float paragraphLineHeight( - XWPFParagraph paragraph, - float fontSize, - float naturalHeight, - float linePitch, - boolean useWordParagraphLayout, - boolean symbolBullet) { - return paragraphLineHeight( - paragraph, fontSize, naturalHeight, linePitch, useWordParagraphLayout, - symbolBullet, null); - } - - static float paragraphLineHeight( - XWPFParagraph paragraph, - float fontSize, - float naturalHeight, - float linePitch, - boolean useWordParagraphLayout, - boolean symbolBullet, - PDFont lineFont) { - double spacing = useWordParagraphLayout - ? effectiveSpacing(paragraph).line() - : paragraph.getSpacingBetween(); - LineSpacingRule rule = useWordParagraphLayout - ? effectiveSpacing(paragraph).rule() - : paragraph.getSpacingLineRule(); - if (useWordParagraphLayout) { - // A style chain without any w:spacing (e.g. NoSpacing) resolves - // to Word's single spacing: fontSize x the font's natural line - // height factor (12pt Source Sans Pro advances 15.1pt), not the - // grid path's 1.2 x fontSize. - double effectiveSpacing = spacing >= 0.0 ? spacing : 1.0; - LineSpacingRule effectiveRule = spacing >= 0.0 ? rule : LineSpacingRule.AUTO; - if (effectiveRule == LineSpacingRule.EXACT) { - return (float) effectiveSpacing; - } - if (effectiveRule == LineSpacingRule.AT_LEAST) { - return Math.max(naturalHeight, (float) effectiveSpacing); - } - // Word computes line height from the line's font metrics - // (hhea ascent − descent + lineGap): single-spaced 12pt Source - // Sans Pro advances 15.1pt and 1.2x advances 18.1pt, while Times - // New Roman advances ~15.9pt. The old fixed 1.151 factor drifted - // every wrapped line of cloud-font documents (OSCAR WARD). Bullet - // list labels render in Symbol whose metrics are taller (12pt - // bullets advance 16.7pt vs 15.9pt for plain body lines). - float metricsFactor = symbolBullet ? 1.21f : fontMetricsFactor(lineFont); - return fontSize * metricsFactor * (float) effectiveSpacing; - } - return gridLineHeight(naturalHeight, linePitch); - } - - /** - * The font's natural single-line height as a fraction of the font size: - * (ascent − descent + lineGap) / 1000 from the embedded font descriptor, - * falling back to the Times New Roman factor for fonts without metrics - * (Standard14 test fonts). - */ - private static float fontMetricsFactor(PDFont lineFont) { - if (lineFont != null && lineFont.getFontDescriptor() != null) { - float ascent = lineFont.getFontDescriptor().getAscent(); - float descent = lineFont.getFontDescriptor().getDescent(); - float leading = Math.max(0.0f, lineFont.getFontDescriptor().getLeading()); - return (ascent - descent + leading) / 1000.0f; - } - return 1.151f; - } - - /** - * Resolves a paragraph's effective spacing properties the way Word does: - * direct pPr wins, then the paragraph style, then its basedOn ancestors, - * then docDefaults. When the paragraph has no style, Word applies Normal. - * Each property (line / lineRule / before / after) falls back independently. - */ - private static ParagraphSpacing effectiveSpacing(XWPFParagraph paragraph) { - CTSpacing direct = paragraph.getCTP().isSetPPr() - && paragraph.getCTP().getPPr().isSetSpacing() - ? paragraph.getCTP().getPPr().getSpacing() - : null; - List chain = new ArrayList<>(); - chain.add(direct); - XWPFStyles documentStyles = paragraph.getDocument().getStyles(); - if (documentStyles != null) { - String styleId = paragraph.getStyle(); - Set visited = new HashSet<>(); - while (styleId != null && visited.add(styleId)) { - XWPFStyle style = documentStyles.getStyle(styleId); - if (style == null) { - break; - } - if (style.getCTStyle() != null - && style.getCTStyle().isSetPPr() - && style.getCTStyle().getPPr().isSetSpacing()) { - chain.add(style.getCTStyle().getPPr().getSpacing()); - } - styleId = basedOnStyleId(style); - } - if (paragraph.getStyle() == null) { - // Word renders style-less paragraphs with the Normal style. - XWPFStyle normal = documentStyles.getStyle("Normal"); - if (normal != null && normal.getCTStyle() != null - && normal.getCTStyle().isSetPPr() - && normal.getCTStyle().getPPr().isSetSpacing()) { - chain.add(normal.getCTStyle().getPPr().getSpacing()); - } - } - CTStyles ctStyles = documentStyles.getCtStyles(); - if (ctStyles != null && ctStyles.isSetDocDefaults() - && ctStyles.getDocDefaults().isSetPPrDefault() - && ctStyles.getDocDefaults().getPPrDefault().isSetPPr() - && ctStyles.getDocDefaults().getPPrDefault().getPPr().isSetSpacing()) { - chain.add(ctStyles.getDocDefaults().getPPrDefault().getPPr().getSpacing()); - } - } - CTSpacing[] spacings = chain.toArray(new CTSpacing[0]); - return new ParagraphSpacing( - resolveLine(spacings), - resolveLineRule(spacings), - resolveBefore(spacings), - resolveAfter(spacings)); - } - - private static String basedOnStyleId(XWPFStyle style) { - Node styleNode = style.getCTStyle().getDomNode(); - Node basedOn = styleNode == null ? null : directChild(styleNode, "basedOn"); - String value = basedOn == null ? null : attribute(basedOn, "val"); - return value == null || value.isEmpty() ? null : value; - } - - private static double resolveLine(CTSpacing[] chain) { - for (CTSpacing spacing : chain) { - if (spacing == null || !spacing.isSetLine()) { - continue; - } - double value = Double.parseDouble(String.valueOf(spacing.getLine())); - if (spacing.isSetLineRule() && spacing.getLineRule() == STLineSpacingRule.AUTO) { - return value / 240.0; - } - return value / 20.0; - } - return -1.0; - } - - private static LineSpacingRule resolveLineRule(CTSpacing[] chain) { - for (CTSpacing spacing : chain) { - if (spacing == null || !spacing.isSetLineRule()) { - continue; - } - if (spacing.getLineRule() == STLineSpacingRule.EXACT) { - return LineSpacingRule.EXACT; - } - if (spacing.getLineRule() == STLineSpacingRule.AT_LEAST) { - return LineSpacingRule.AT_LEAST; - } - return LineSpacingRule.AUTO; - } - return null; - } - - private static int resolveBefore(CTSpacing[] chain) { - for (CTSpacing spacing : chain) { - if (spacing != null && spacing.isSetBefore()) { - return Integer.parseInt(String.valueOf(spacing.getBefore())); - } - } - return -1; - } - - private static int resolveAfter(CTSpacing[] chain) { - for (CTSpacing spacing : chain) { - if (spacing != null && spacing.isSetAfter()) { - return Integer.parseInt(String.valueOf(spacing.getAfter())); - } - } - return -1; - } - - private static final class ParagraphSpacing { - private final double line; - private final LineSpacingRule rule; - private final int before; - private final int after; - - private ParagraphSpacing(double line, LineSpacingRule rule, int before, int after) { - this.line = line; - this.rule = rule; - this.before = before; - this.after = after; - } - - private double line() { - return line; - } - - private LineSpacingRule rule() { - return rule; - } - - private int before() { - return before; - } - - private int after() { - return after; - } - } - - static float centeredTextX(float pageWidth, float leftIndent, float rightIndent, float textWidth) { - return (pageWidth + leftIndent - rightIndent - textWidth) / 2.0f; - } - - private static float stylePoints(String xml, String property) { - Matcher matcher = Pattern.compile(property + ":(-?[0-9.]+)pt").matcher(xml); - return matcher.find() ? Float.parseFloat(matcher.group(1)) : Float.NaN; - } - - private static void drawRunHighlight( - PDPageContentStream content, - HighlightColor highlight, - float x, - float baseline, - float width, - float fontSize) throws IOException { - if (highlight == null || width <= 0.0f) { - return; - } - float horizontalPadding = Math.max(0.7f, fontSize * 0.08f); - content.setNonStrokingColor(highlight.red, highlight.green, highlight.blue); - content.addRect( - x - horizontalPadding, - baseline - fontSize * 0.24f, - width + horizontalPadding * 2.0f, - fontSize * 1.18f); - content.fill(); - content.setNonStrokingColor(0.0f, 0.0f, 0.0f); - } - - private static void showText( - PDPageContentStream content, - PDFont font, - float fontSize, - String text, - float x, - float y) throws IOException { - showText(content, font, fontSize, text, x, y, DEFAULT_AUTO_SPACING); - } - - private static void showText( - PDPageContentStream content, - PDFont font, - float fontSize, - String text, - float x, - float y, - AutoSpacing autoSpacing) throws IOException { - showText(content, font, fontSize, text, x, y, autoSpacing, 0.0f); - } - - private static void showText( - PDPageContentStream content, - PDFont font, - float fontSize, - String text, - float x, - float y, - AutoSpacing autoSpacing, - float wordSpacing) throws IOException { - if (text.isEmpty()) { - return; - } - content.beginText(); - content.setFont(font, fontSize); - if (wordSpacing > 0.0f) { - content.setWordSpacing(wordSpacing); - } - content.newLineAtOffset(x, y); - if (eastAsianBoundaryCount(text, autoSpacing) == 0) { - content.showText(text); - } else { - List positioned = new ArrayList<>(); - int start = 0; - int previous = -1; - for (int offset = 0; offset < text.length();) { - int codePoint = text.codePointAt(offset); - if (previous >= 0 && isEastAsianLatinBoundary(previous, codePoint, autoSpacing)) { - positioned.add(text.substring(start, offset)); - positioned.add(-250.0f); - start = offset; - } - offset += Character.charCount(codePoint); - previous = codePoint; - } - positioned.add(text.substring(start)); - content.showTextWithPositioning(positioned.toArray()); - } - content.endText(); - } - - static float justifiedWordSpacing(String text, float textWidth, float availableWidth) { - long spaces = text.codePoints().filter(codePoint -> codePoint == ' ').count(); - return spaces == 0 ? 0.0f : Math.max(0.0f, availableWidth - textWidth) / spaces; - } - - private static float sum(List values, int count) { - float sum = 0.0f; - for (int index = 0; index < count && index < values.size(); index++) { - sum += values.get(index); - } - return sum; - } - - private static float twipsToPoints(int twips) { - return Math.max(0, twips) / 20.0f; - } - - static float indentationToPoints(int twips) { - return twips == -1 ? 0.0f : twips / 20.0f; - } - - private static final class PageContext implements AutoCloseable { - private final PDDocument document; - private final PageSize pageSize; - private final float margin; - private final float topMargin; - private final float bottomMargin; - private final float linePitch; - private final PDFont pageNumberFont; - private final PageNumberFooter pageNumberFooter; - private final float pageFooterDistance; - private final Map footnotes; - private final Map themeColors; - private final List headerParagraphs; - private final List currentPageFootnoteIds = new ArrayList<>(); - private PDPageContentStream content; - private float y; - private int pageCount; - private float previousParagraphSpacingAfter; - private float footnoteReservedHeight; - private boolean alignNextParagraphToCheckboxes; - private boolean topOfPage; - - private PageContext( - PDDocument document, - PageSize pageSize, - float margin, - float topMargin, - float bottomMargin, - float linePitch, - float topOffset, - PDFont pageNumberFont, - PageNumberFooter pageNumberFooter, - float pageFooterDistance, - Map footnotes, - Map themeColors, - List headerParagraphs) - throws IOException { - this.document = document; - this.pageSize = pageSize; - this.margin = margin; - this.topMargin = topMargin; - this.bottomMargin = bottomMargin; - this.linePitch = linePitch; - this.pageNumberFont = pageNumberFont; - this.pageNumberFooter = pageNumberFooter; - this.pageFooterDistance = pageFooterDistance; - this.footnotes = footnotes; - this.themeColors = themeColors; - this.headerParagraphs = headerParagraphs; - newPage(topOffset); - } - - private void ensureSpace(float height) throws IOException { - if (y - height < bottomMargin + footnoteReservedHeight) { - newPage(); - } - } - - private void registerFootnotes(XWPFParagraph paragraph) throws IOException { - for (XWPFRun run : paragraph.getRuns()) { - run.getCTR().getFootnoteReferenceList().forEach(reference -> { - String id = reference.getId().toString(); - if (footnotes.containsKey(id) && !currentPageFootnoteIds.contains(id)) { - currentPageFootnoteIds.add(id); - FootnoteData footnote = footnotes.get(id); - if (footnoteReservedHeight == 0.0f) { - footnoteReservedHeight = 17.0f; - } - footnoteReservedHeight += footnote.lineHeight() + 8.0f; - } - }); - } - } - - private void expectCheckboxLabelAlignment() { - alignNextParagraphToCheckboxes = true; - } - - private boolean consumeCheckboxLabelAlignment() { - boolean align = alignNextParagraphToCheckboxes; - alignNextParagraphToCheckboxes = false; - return align; - } - - private void moveDown(float amount) throws IOException { - ensureSpace(amount); - y -= amount; - topOfPage = false; - } - - private boolean consumeTopOfPage() { - boolean value = topOfPage; - topOfPage = false; - return value; - } - - private void avoidWidowOrphanSplit(float lineHeight, int lineCount) throws IOException { - if (lineCount < 2 || lineHeight <= 0.0f) { - return; - } - int linesThatFit = (int) Math.floor((y - bottomMargin) / lineHeight); - if (linesThatFit > 0 - && linesThatFit < lineCount - && (linesThatFit < 2 || lineCount - linesThatFit < 2)) { - newPage(); - } - } - - private void moveToParagraph(float spacingBefore) throws IOException { - moveDown(Math.max(0.0f, spacingBefore - previousParagraphSpacingAfter)); - previousParagraphSpacingAfter = 0.0f; - } - - private void finishParagraph(float spacingAfter) throws IOException { - moveDown(spacingAfter); - previousParagraphSpacingAfter = spacingAfter; - } - - private void resetParagraphSpacingAfter() { - previousParagraphSpacingAfter = 0.0f; - } - - private void keepNextBeforeParagraph(float needed) throws IOException { - if (y < pageSize.height() - topMargin && y - needed < bottomMargin) { - newPage(); - } - } - - private void newPage() throws IOException { - newPage(0.0f); - } - - private void newPage(float topOffset) throws IOException { - if (content != null) { - renderFootnotes(); - renderPageNumber(); - content.close(); - } - currentPageFootnoteIds.clear(); - footnoteReservedHeight = 0.0f; - previousParagraphSpacingAfter = 0.0f; - PDPage page = new PDPage(new PDRectangle(pageSize.width(), pageSize.height())); - document.addPage(page); - pageCount++; - content = new PDPageContentStream(document, page); - renderHeaderBehindDocShapes(); - y = pageSize.height() - topMargin - topOffset; - topOfPage = true; - } - - /** - * Header parts only contribute behindDoc anchored shapes here (e.g. - * the full-page letterhead frame); they render behind the body text - * of every page, matching Word's default header behavior. - */ - private void renderHeaderBehindDocShapes() throws IOException { - if (headerParagraphs == null || headerParagraphs.isEmpty()) { - return; - } - float headerTop = pageSize.height(); - for (XWPFParagraph headerParagraph : headerParagraphs) { - renderAnchoredBehindDocShapes(this, headerParagraph, headerTop); - } - } - - private void renderFootnotes() throws IOException { - if (currentPageFootnoteIds.isEmpty()) { - return; - } - float textHeight = currentPageFootnoteIds.stream() - .map(footnotes::get) - .map(FootnoteData::lineHeight) - .reduce(0.0f, Float::sum); - float footnoteY = bottomMargin + textHeight + 5.0f; - content.setStrokingColor(0, 0, 0); - content.setLineWidth(0.5f); - content.moveTo(margin, footnoteY); - content.lineTo(margin + Math.min(144.0f, (pageSize.width() - margin * 2.0f) * 0.33f), footnoteY); - content.stroke(); - footnoteY -= 2.0f; - for (String id : currentPageFootnoteIds) { - FootnoteData footnote = footnotes.get(id); - footnoteY -= footnote.lineHeight(); - showText( - content, - footnote.font, - footnote.fontSize, - footnote.displayText(), - margin, - footnoteY); - } - } - - private void renderPageNumber() throws IOException { - if (pageNumberFont == null) { - return; - } - String pageNumber = pageNumberFooter.prefix() + pageCount + pageNumberFooter.suffix(); - float fontSize = pageNumberFooter.fontSize(); - float x = (pageSize.width() - textWidth(pageNumberFont, pageNumber, fontSize)) / 2.0f; - float descent = pageNumberFont.getFontDescriptor() == null - ? 0.0f - : pageNumberFont.getFontDescriptor().getDescent(); - float baseline = pageNumberBaseline(pageFooterDistance, fontSize, descent); - showText(content, pageNumberFont, fontSize, pageNumber, x, baseline); - } - - @Override - public void close() throws IOException { - if (content != null) { - renderFootnotes(); - renderPageNumber(); - content.close(); - content = null; - } - } - } - - static float pageNumberBaseline(float footerDistance, float fontSize, float fontDescent) { - return footerDistance + fontSize * 1.151f + Math.abs(fontDescent) / 1000.0f * fontSize; - } -} \ No newline at end of file diff --git a/minipdf-java/minipdf/src/main/java/io/github/minisoftware/minipdf/internal/pptx/PptxConverter.java b/minipdf-java/minipdf/src/main/java/io/github/minisoftware/minipdf/internal/pptx/PptxConverter.java deleted file mode 100644 index 17eb68ff..00000000 --- a/minipdf-java/minipdf/src/main/java/io/github/minisoftware/minipdf/internal/pptx/PptxConverter.java +++ /dev/null @@ -1,246 +0,0 @@ -package io.github.minisoftware.minipdf.internal.pptx; - -import io.github.minisoftware.minipdf.ConversionOptions; -import io.github.minisoftware.minipdf.MiniPdfException; -import io.github.minisoftware.minipdf.PageSize; -import io.github.minisoftware.minipdf.internal.OoxmlPackage; -import io.github.minisoftware.minipdf.internal.SecureXml; -import io.github.minisoftware.minipdf.internal.SimplePdfTextRenderer; - -import javax.xml.stream.XMLStreamConstants; -import javax.xml.stream.XMLStreamException; -import javax.xml.stream.XMLStreamReader; -import java.util.ArrayDeque; -import java.util.ArrayList; -import java.util.Collections; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; - -public final class PptxConverter { - private static final float EMUS_PER_POINT = 12_700.0f; - private static final float DEFAULT_SLIDE_WIDTH = 720.0f; - private static final float DEFAULT_SLIDE_HEIGHT = 540.0f; - - private PptxConverter() { - } - - public static byte[] convert(byte[] input, ConversionOptions options) throws MiniPdfException { - OoxmlPackage presentation = OoxmlPackage.open(input); - byte[] presentationXml = presentation.entry("ppt/presentation.xml") - .orElseThrow(() -> new MiniPdfException( - MiniPdfException.Kind.INVALID_INPUT, - "PPTX package does not contain ppt/presentation.xml")); - PageSize slideSize = readSlideSize(presentationXml); - List slideNames = readSlideNames(presentation, presentationXml); - if (slideNames.isEmpty()) { - throw new MiniPdfException( - MiniPdfException.Kind.INVALID_INPUT, - "PPTX package does not contain a slide"); - } - - List> slides = new ArrayList<>(); - for (String slideName : slideNames) { - byte[] slideXml = presentation.entry(slideName) - .orElseThrow(() -> new MiniPdfException( - MiniPdfException.Kind.INVALID_INPUT, - "PPTX slide part is missing: " + slideName)); - slides.add(readSlide(slideXml)); - } - return SimplePdfTextRenderer.renderPages(slides, options, slideSize); - } - - private static PageSize readSlideSize(byte[] xml) throws MiniPdfException { - XMLStreamReader reader = null; - try { - reader = SecureXml.reader(xml); - while (reader.hasNext()) { - int event = reader.next(); - if (event == XMLStreamConstants.START_ELEMENT && reader.getLocalName().equals("sldSz")) { - float width = emusToPoints(reader.getAttributeValue(null, "cx"), DEFAULT_SLIDE_WIDTH); - float height = emusToPoints(reader.getAttributeValue(null, "cy"), DEFAULT_SLIDE_HEIGHT); - return PageSize.of(width, height); - } - } - return PageSize.of(DEFAULT_SLIDE_WIDTH, DEFAULT_SLIDE_HEIGHT); - } catch (XMLStreamException exception) { - throw SecureXml.parseError(exception); - } finally { - closeReader(reader); - } - } - - private static List readSlide(byte[] xml) throws MiniPdfException { - List paragraphs = new ArrayList<>(); - StringBuilder paragraph = null; - XMLStreamReader reader = null; - try { - reader = SecureXml.reader(xml); - while (reader.hasNext()) { - int event = reader.next(); - if (event == XMLStreamConstants.START_ELEMENT && reader.getLocalName().equals("p")) { - paragraph = new StringBuilder(); - } else if (event == XMLStreamConstants.START_ELEMENT - && reader.getLocalName().equals("t") && paragraph != null) { - paragraph.append(reader.getElementText()); - } else if (event == XMLStreamConstants.START_ELEMENT - && reader.getLocalName().equals("br") && paragraph != null) { - paragraph.append(' '); - } else if (event == XMLStreamConstants.END_ELEMENT - && reader.getLocalName().equals("p") && paragraph != null) { - paragraphs.add(paragraph.toString()); - paragraph = null; - } - } - return paragraphs; - } catch (XMLStreamException exception) { - throw SecureXml.parseError(exception); - } finally { - closeReader(reader); - } - } - - private static List readSlideNames(OoxmlPackage presentation, byte[] presentationXml) - throws MiniPdfException { - List relationshipIds = readSlideRelationshipIds(presentationXml); - if (relationshipIds.isEmpty()) { - return Collections.emptyList(); - } - byte[] relationshipsXml = presentation.entry("ppt/_rels/presentation.xml.rels") - .orElseThrow(() -> new MiniPdfException( - MiniPdfException.Kind.INVALID_INPUT, - "PPTX package does not contain presentation relationships")); - Map relationships = readSlideRelationships(relationshipsXml); - List slideNames = new ArrayList<>(); - for (String relationshipId : relationshipIds) { - String target = relationships.get(relationshipId); - if (target == null) { - throw new MiniPdfException( - MiniPdfException.Kind.INVALID_INPUT, - "PPTX slide relationship is missing: " + relationshipId); - } - slideNames.add(resolvePartName("ppt/presentation.xml", target)); - } - return slideNames; - } - - private static List readSlideRelationshipIds(byte[] xml) throws MiniPdfException { - List relationshipIds = new ArrayList<>(); - XMLStreamReader reader = null; - try { - reader = SecureXml.reader(xml); - while (reader.hasNext()) { - int event = reader.next(); - if (event == XMLStreamConstants.START_ELEMENT && reader.getLocalName().equals("sldId")) { - String relationshipId = namespacedAttribute(reader, "id"); - if (relationshipId != null) { - relationshipIds.add(relationshipId); - } - } - } - return relationshipIds; - } catch (XMLStreamException exception) { - throw SecureXml.parseError(exception); - } finally { - closeReader(reader); - } - } - - private static Map readSlideRelationships(byte[] xml) throws MiniPdfException { - Map relationships = new LinkedHashMap<>(); - XMLStreamReader reader = null; - try { - reader = SecureXml.reader(xml); - while (reader.hasNext()) { - int event = reader.next(); - if (event != XMLStreamConstants.START_ELEMENT - || !reader.getLocalName().equals("Relationship")) { - continue; - } - String type = attribute(reader, "Type"); - String targetMode = attribute(reader, "TargetMode"); - if (type == null || !type.endsWith("/slide") - || "external".equalsIgnoreCase(targetMode)) { - continue; - } - String relationshipId = attribute(reader, "Id"); - String target = attribute(reader, "Target"); - if (relationshipId != null && target != null) { - relationships.put(relationshipId, target); - } - } - return relationships; - } catch (XMLStreamException exception) { - throw SecureXml.parseError(exception); - } finally { - closeReader(reader); - } - } - - private static float emusToPoints(String value, float defaultValue) { - if (value == null) { - return defaultValue; - } - try { - long emus = Long.parseLong(value); - return emus > 0 ? emus / EMUS_PER_POINT : defaultValue; - } catch (NumberFormatException ignored) { - return defaultValue; - } - } - - private static String attribute(XMLStreamReader reader, String localName) { - for (int index = 0; index < reader.getAttributeCount(); index++) { - if (reader.getAttributeLocalName(index).equals(localName)) { - return reader.getAttributeValue(index); - } - } - return null; - } - - private static String namespacedAttribute(XMLStreamReader reader, String localName) { - for (int index = 0; index < reader.getAttributeCount(); index++) { - String namespace = reader.getAttributeNamespace(index); - if (namespace != null && !namespace.isEmpty() - && reader.getAttributeLocalName(index).equals(localName)) { - return reader.getAttributeValue(index); - } - } - return null; - } - - private static String resolvePartName(String sourcePart, String target) throws MiniPdfException { - String normalizedTarget = target.replace('\\', '/'); - String sourceDirectory = sourcePart.substring(0, sourcePart.lastIndexOf('/') + 1); - String combined = normalizedTarget.startsWith("/") - ? normalizedTarget.substring(1) - : sourceDirectory + normalizedTarget; - ArrayDeque segments = new ArrayDeque<>(); - for (String segment : combined.split("/")) { - if (segment.isEmpty() || segment.equals(".")) { - continue; - } - if (segment.equals("..")) { - if (segments.isEmpty()) { - throw new MiniPdfException( - MiniPdfException.Kind.INVALID_INPUT, - "PPTX relationship target escapes the package: " + target); - } - segments.removeLast(); - } else { - segments.addLast(segment); - } - } - return String.join("/", segments); - } - - private static void closeReader(XMLStreamReader reader) { - if (reader == null) { - return; - } - try { - reader.close(); - } catch (XMLStreamException ignored) { - } - } -} \ No newline at end of file diff --git a/minipdf-java/minipdf/src/main/java/io/github/minisoftware/minipdf/internal/xlsx/LegacyVmlPictureReader.java b/minipdf-java/minipdf/src/main/java/io/github/minisoftware/minipdf/internal/xlsx/LegacyVmlPictureReader.java deleted file mode 100644 index 999ae6e5..00000000 --- a/minipdf-java/minipdf/src/main/java/io/github/minisoftware/minipdf/internal/xlsx/LegacyVmlPictureReader.java +++ /dev/null @@ -1,327 +0,0 @@ -package io.github.minisoftware.minipdf.internal.xlsx; - -import io.github.minisoftware.minipdf.MiniPdfException; -import io.github.minisoftware.minipdf.internal.SecureXml; -import org.apache.poi.hemf.usermodel.HemfPicture; - -import javax.imageio.ImageIO; -import javax.xml.stream.XMLStreamConstants; -import javax.xml.stream.XMLStreamException; -import javax.xml.stream.XMLStreamReader; -import java.awt.Color; -import java.awt.Graphics2D; -import java.awt.RenderingHints; -import java.awt.geom.Dimension2D; -import java.awt.geom.Rectangle2D; -import java.awt.image.BufferedImage; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.zip.ZipEntry; -import java.util.zip.ZipInputStream; - -final class LegacyVmlPictureReader { - private static final float EMF_RASTER_DPI = 300.0f; - - private LegacyVmlPictureReader() { - } - - static Map> read(byte[] input) throws MiniPdfException { - Map entries = zipEntries(input); - Map> pictures = new HashMap<>(); - for (Map.Entry entry : entries.entrySet()) { - String relationshipPath = entry.getKey(); - if (!relationshipPath.startsWith("xl/worksheets/_rels/") - || !relationshipPath.endsWith(".xml.rels")) { - continue; - } - String sheetPath = "xl/worksheets/" - + relationshipPath.substring("xl/worksheets/_rels/".length(), relationshipPath.length() - 5); - for (Relationship relationship : relationships(entry.getValue())) { - if (!relationship.type().endsWith("/vmlDrawing")) { - continue; - } - String vmlPath = resolve(sheetPath, relationship.target()); - byte[] vml = entries.get(vmlPath); - if (vml == null) { - continue; - } - Map imageTargets = new HashMap<>(); - byte[] vmlRelationships = entries.get(relationshipPath(vmlPath)); - if (vmlRelationships != null) { - for (Relationship imageRelationship : relationships(vmlRelationships)) { - if (imageRelationship.type().endsWith("/image")) { - imageTargets.put( - imageRelationship.id(), - resolve(vmlPath, imageRelationship.target())); - } - } - } - List sheetPictures = parseVml(vml, imageTargets, entries); - if (!sheetPictures.isEmpty()) { - pictures.computeIfAbsent(sheetPath, ignored -> new ArrayList<>()).addAll(sheetPictures); - } - } - } - return pictures; - } - - private static Map zipEntries(byte[] input) throws MiniPdfException { - Map entries = new HashMap<>(); - try (ZipInputStream archive = new ZipInputStream(new ByteArrayInputStream(input))) { - ZipEntry entry; - while ((entry = archive.getNextEntry()) != null) { - if (!entry.isDirectory()) { - entries.put(entry.getName(), readAllBytes(archive)); - } - } - return entries; - } catch (IOException exception) { - throw new MiniPdfException( - MiniPdfException.Kind.ZIP_PACKAGE, - "unable to read XLSX package: " + exception.getMessage(), - exception); - } - } - - private static byte[] readAllBytes(ZipInputStream input) throws IOException { - ByteArrayOutputStream output = new ByteArrayOutputStream(); - byte[] buffer = new byte[8192]; - int read; - while ((read = input.read(buffer)) != -1) { - output.write(buffer, 0, read); - } - return output.toByteArray(); - } - - private static List relationships(byte[] xml) throws MiniPdfException { - List relationships = new ArrayList<>(); - try { - XMLStreamReader reader = SecureXml.reader(xml); - while (reader.hasNext()) { - if (reader.next() == XMLStreamConstants.START_ELEMENT - && reader.getLocalName().equals("Relationship")) { - relationships.add(new Relationship( - attribute(reader, "Id"), - attribute(reader, "Type"), - attribute(reader, "Target"))); - } - } - reader.close(); - return relationships; - } catch (XMLStreamException exception) { - throw SecureXml.parseError(exception); - } - } - - private static List parseVml( - byte[] xml, - Map imageTargets, - Map entries) throws MiniPdfException { - List pictures = new ArrayList<>(); - String relationId = null; - float cropTop = 0.0f; - float cropBottom = 0.0f; - float cropLeft = 0.0f; - float cropRight = 0.0f; - try { - XMLStreamReader reader = SecureXml.reader(xml); - while (reader.hasNext()) { - int event = reader.next(); - if (event == XMLStreamConstants.START_ELEMENT && reader.getLocalName().equals("shape")) { - relationId = null; - cropTop = cropBottom = cropLeft = cropRight = 0.0f; - } else if (event == XMLStreamConstants.START_ELEMENT - && reader.getLocalName().equals("imagedata")) { - relationId = attribute(reader, "relid"); - cropTop = crop(attribute(reader, "croptop")); - cropBottom = crop(attribute(reader, "cropbottom")); - cropLeft = crop(attribute(reader, "cropleft")); - cropRight = crop(attribute(reader, "cropright")); - } else if (event == XMLStreamConstants.START_ELEMENT - && reader.getLocalName().equals("Anchor") && relationId != null) { - int[] anchor = parseAnchor(reader.getElementText()); - String imagePath = imageTargets.get(relationId); - byte[] image = imagePath == null ? null : entries.get(imagePath); - if (anchor != null && image != null) { - pictures.add(new LegacyPicture( - image, - imagePath, - anchor, - cropTop, - cropBottom, - cropLeft, - cropRight)); - } - } - } - reader.close(); - return pictures; - } catch (XMLStreamException exception) { - throw SecureXml.parseError(exception); - } - } - - private static String attribute(XMLStreamReader reader, String localName) { - for (int index = 0; index < reader.getAttributeCount(); index++) { - if (reader.getAttributeLocalName(index).equals(localName)) { - return reader.getAttributeValue(index); - } - } - return ""; - } - - private static int[] parseAnchor(String value) { - String[] values = value.split(","); - if (values.length != 8) { - return null; - } - int[] anchor = new int[8]; - try { - for (int index = 0; index < values.length; index++) { - anchor[index] = Integer.parseInt(values[index].trim()); - } - return anchor; - } catch (NumberFormatException ignored) { - return null; - } - } - - private static float crop(String value) { - if (value == null || value.trim().isEmpty()) { - return 0.0f; - } - String normalized = value.toLowerCase(Locale.ROOT).endsWith("f") - ? value.substring(0, value.length() - 1) - : value; - try { - return Math.max(0.0f, Math.min(1.0f, Integer.parseInt(normalized) / 65_536.0f)); - } catch (NumberFormatException ignored) { - return 0.0f; - } - } - - private static String resolve(String source, String target) { - Path parent = Paths.get(source).getParent(); - return parent.resolve(target.replace('/', java.io.File.separatorChar)) - .normalize() - .toString() - .replace('\\', '/'); - } - - private static String relationshipPath(String partPath) { - Path path = Paths.get(partPath); - return path.getParent().resolve("_rels").resolve(path.getFileName() + ".rels") - .toString() - .replace('\\', '/'); - } - - static final class LegacyPicture { - private final byte[] data; - private final String path; - private final int[] anchor; - private final float cropTop; - private final float cropBottom; - private final float cropLeft; - private final float cropRight; - - LegacyPicture( - byte[] data, - String path, - int[] anchor, - float cropTop, - float cropBottom, - float cropLeft, - float cropRight) { - this.data = data; - this.path = path; - this.anchor = anchor; - this.cropTop = cropTop; - this.cropBottom = cropBottom; - this.cropLeft = cropLeft; - this.cropRight = cropRight; - } - - byte[] data() { - return data; - } - - String path() { - return path; - } - - int[] anchor() { - return anchor; - } - - float cropTop() { - return cropTop; - } - - float cropBottom() { - return cropBottom; - } - - float cropLeft() { - return cropLeft; - } - - float cropRight() { - return cropRight; - } - - byte[] png() throws IOException { - if (!path.toLowerCase(Locale.ROOT).endsWith(".emf")) { - return data; - } - HemfPicture picture = new HemfPicture(new ByteArrayInputStream(data)); - Dimension2D size = picture.getSize(); - int width = Math.max(1, (int) Math.ceil(size.getWidth() * EMF_RASTER_DPI / 72.0f)); - int height = Math.max(1, (int) Math.ceil(size.getHeight() * EMF_RASTER_DPI / 72.0f)); - BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); - Graphics2D graphics = image.createGraphics(); - try { - graphics.setColor(Color.WHITE); - graphics.fillRect(0, 0, width, height); - graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); - picture.draw(graphics, new Rectangle2D.Double(0, 0, width, height)); - } finally { - graphics.dispose(); - } - ByteArrayOutputStream output = new ByteArrayOutputStream(); - ImageIO.write(image, "png", output); - return output.toByteArray(); - } - } - - private static final class Relationship { - private final String id; - private final String type; - private final String target; - - private Relationship(String id, String type, String target) { - this.id = id; - this.type = type; - this.target = target; - } - - private String id() { - return id; - } - - private String type() { - return type; - } - - private String target() { - return target; - } - } -} \ No newline at end of file diff --git a/minipdf-java/minipdf/src/main/java/io/github/minisoftware/minipdf/internal/xlsx/PoiXlsxRenderer.java b/minipdf-java/minipdf/src/main/java/io/github/minisoftware/minipdf/internal/xlsx/PoiXlsxRenderer.java deleted file mode 100644 index 4829a24c..00000000 --- a/minipdf-java/minipdf/src/main/java/io/github/minisoftware/minipdf/internal/xlsx/PoiXlsxRenderer.java +++ /dev/null @@ -1,2341 +0,0 @@ -package io.github.minisoftware.minipdf.internal.xlsx; - -import de.rototor.pdfbox.graphics2d.PdfBoxGraphics2D; -import io.github.minisoftware.minipdf.ConversionOptions; -import io.github.minisoftware.minipdf.internal.FontEmbeddingPolicy; -import io.github.minisoftware.minipdf.MiniPdf; -import io.github.minisoftware.minipdf.MiniPdfException; -import io.github.minisoftware.minipdf.PageSize; -import io.github.minisoftware.minipdf.RegisteredFont; -import org.apache.fontbox.ttf.TrueTypeCollection; -import org.apache.pdfbox.pdmodel.PDDocument; -import org.apache.pdfbox.pdmodel.PDPage; -import org.apache.pdfbox.pdmodel.PDPageContentStream; -import org.apache.pdfbox.pdmodel.common.PDRectangle; -import org.apache.pdfbox.pdmodel.font.PDFont; -import org.apache.pdfbox.pdmodel.font.PDType0Font; -import org.apache.pdfbox.pdmodel.font.PDType1Font; -import org.apache.pdfbox.pdmodel.graphics.form.PDFormXObject; -import org.apache.pdfbox.pdmodel.font.Standard14Fonts; -import org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject; -import org.apache.pdfbox.pdmodel.graphics.state.PDExtendedGraphicsState; -import org.apache.pdfbox.util.Matrix; -import org.apache.poi.hemf.usermodel.HemfPicture; -import org.apache.pdfbox.pdmodel.graphics.state.RenderingMode; -import org.apache.pdfbox.pdfwriter.compress.CompressParameters; -import org.apache.poi.ss.SpreadsheetVersion; -import org.apache.poi.ss.usermodel.BorderStyle; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.CellStyle; -import org.apache.poi.ss.usermodel.CellType; -import org.apache.poi.ss.usermodel.DataFormatter; -import org.apache.poi.ss.usermodel.DifferentialStyleProvider; -import org.apache.poi.ss.usermodel.FillPatternType; -import org.apache.poi.ss.usermodel.FormulaEvaluator; -import org.apache.poi.ss.usermodel.HorizontalAlignment; -import org.apache.poi.ss.usermodel.Name; -import org.apache.poi.ss.usermodel.PageMargin; -import org.apache.poi.ss.usermodel.PatternFormatting; -import org.apache.poi.ss.usermodel.PrintSetup; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.ss.usermodel.TableStyleInfo; -import org.apache.poi.ss.usermodel.TableStyleType; -import org.apache.poi.ss.usermodel.VerticalAlignment; -import org.apache.poi.ss.util.AreaReference; -import org.apache.poi.ss.util.CellRangeAddress; -import org.apache.poi.ss.util.CellRangeAddressBase; -import org.apache.poi.ss.util.CellReference; -import org.apache.poi.xssf.usermodel.XSSFCellStyle; -import org.apache.poi.xssf.usermodel.XSSFClientAnchor; -import org.apache.poi.xssf.usermodel.XSSFColor; -import org.apache.poi.xssf.usermodel.XSSFDrawing; -import org.apache.poi.xssf.usermodel.XSSFFont; -import org.apache.poi.xssf.usermodel.XSSFPicture; -import org.apache.poi.xssf.usermodel.XSSFPrintSetup; -import org.apache.poi.xssf.usermodel.XSSFShape; -import org.apache.poi.xssf.usermodel.XSSFShapeGroup; -import org.apache.poi.xssf.usermodel.XSSFSimpleShape; -import org.apache.poi.xssf.usermodel.XSSFSheet; -import org.apache.poi.xssf.usermodel.XSSFTable; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; -import org.apache.xmlbeans.XmlCursor; -import org.apache.xmlbeans.XmlObject; -import org.openxmlformats.schemas.drawingml.x2006.main.CTAdjPoint2D; -import org.openxmlformats.schemas.drawingml.x2006.main.CTGroupTransform2D; -import org.openxmlformats.schemas.drawingml.x2006.main.CTPath2D; -import org.openxmlformats.schemas.drawingml.x2006.main.CTPath2DClose; -import org.openxmlformats.schemas.drawingml.x2006.main.CTPath2DCubicBezierTo; -import org.openxmlformats.schemas.drawingml.x2006.main.CTPath2DLineTo; -import org.openxmlformats.schemas.drawingml.x2006.main.CTPath2DMoveTo; -import org.openxmlformats.schemas.drawingml.x2006.main.CTPath2DQuadBezierTo; -import org.openxmlformats.schemas.drawingml.x2006.main.CTSchemeColor; -import org.openxmlformats.schemas.drawingml.x2006.main.CTShapeProperties; -import org.openxmlformats.schemas.drawingml.x2006.main.CTSolidColorFillProperties; -import org.openxmlformats.schemas.drawingml.x2006.main.CTSRgbColor; -import org.openxmlformats.schemas.drawingml.x2006.main.CTTransform2D; -import org.openxmlformats.schemas.drawingml.x2006.main.STSchemeColorVal; -import org.openxmlformats.schemas.drawingml.x2006.main.STShapeType; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTDefinedName; - -import java.awt.Color; -import java.awt.geom.Rectangle2D; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.stream.Collectors; -import java.util.stream.Stream; - -import static io.github.minisoftware.minipdf.internal.xlsx.LegacyVmlPictureReader.LegacyPicture; - -final class PoiXlsxRenderer { - private static final float POINTS_PER_PIXEL = 72.0f / 96.0f; - private static final float POINTS_PER_INCH = 72.0f; - private static final float EMU_PER_POINT = 12_700.0f; - private static final float CELL_PADDING = 2.0f; - private static final float VERDANA_ROW_HEIGHT_SCALE = 0.919f; - private static final float CENTERED_VML_HORIZONTAL_GEOMETRY_SCALE = 1.0777f; - private static final float CENTERED_VML_BORDER_SCALE = 1.8f; - - private PoiXlsxRenderer() { - } - - static byte[] render(byte[] input, ConversionOptions options) throws MiniPdfException { - try (XSSFWorkbook workbook = new XSSFWorkbook(new ByteArrayInputStream(input)); - PDDocument document = new PDDocument()) { - document.setVersion(1.4f); - FontSet fonts = FontSet.load(document); - Map> legacyPictures = LegacyVmlPictureReader.read(input); - DataFormatter formatter = new DataFormatter(Locale.ROOT, true); - FormulaEvaluator evaluator = workbook.getCreationHelper().createFormulaEvaluator(); - for (int sheetIndex = 0; sheetIndex < workbook.getNumberOfSheets(); sheetIndex++) { - XSSFSheet sheet = workbook.getSheetAt(sheetIndex); - String sheetPath = sheet.getPackagePart().getPartName().getName().replaceFirst("^/", ""); - renderSheet( - document, - fonts, - workbook, - sheet, - sheetIndex, - formatter, - evaluator, - options, - legacyPictures.getOrDefault(sheetPath, Collections.emptyList())); - } - ByteArrayOutputStream output = new ByteArrayOutputStream(); - document.save(output, CompressParameters.NO_COMPRESSION); - return output.toByteArray(); - } catch (IOException | RuntimeException exception) { - throw new MiniPdfException( - MiniPdfException.Kind.INVALID_INPUT, - "unable to render XLSX: " + exception.getMessage(), - exception); - } - } - - private static void renderSheet( - PDDocument document, - FontSet fonts, - XSSFWorkbook workbook, - XSSFSheet sheet, - int sheetIndex, - DataFormatter formatter, - FormulaEvaluator evaluator, - ConversionOptions options, - List legacyPictures) throws IOException { - CellRangeAddress area = printArea(workbook, sheet, sheetIndex); - PageGeometry geometry = pageGeometry(sheet, options); - XSSFPrintSetup setup = sheet.getPrintSetup(); - List merged = sheet.getMergedRegions(); - CellRangeAddress repeatingRows = sheet.getRepeatingRows(); - int repeatingFirstRow = repeatingRows == null - ? -1 - : Math.max(area.getFirstRow(), repeatingRows.getFirstRow()); - int repeatingLastRow = repeatingRows == null - ? -1 - : Math.min(area.getLastRow(), repeatingRows.getLastRow()); - boolean hasPrintArea = printAreaValue(workbook, sheet, sheetIndex) != null; - float verticalScaleLimit = explicitScale(sheet) && sheet.getVerticallyCenter() - ? Math.min(1.0f, geometry.usableHeight() / rowsBefore( - sheet, area.getFirstRow(), area.getLastRow() + 1)) - : 1.0f; - for (ColumnGroup group : columnGroups( - sheet, area, geometry, setup, hasPrintArea, verticalScaleLimit)) { - CellRangeAddress groupArea = new CellRangeAddress( - area.getFirstRow(), - area.getLastRow(), - group.firstColumn(), - group.lastColumn()); - int startRow = area.getFirstRow(); - while (startRow <= area.getLastRow()) { - boolean repeatTitles = repeatingFirstRow >= 0 && startRow > repeatingLastRow; - float repeatingHeight = repeatTitles - ? rowsBefore(sheet, repeatingFirstRow, repeatingLastRow + 1) * group.scale() - : 0.0f; - int endRow = pageEndRow( - sheet, - startRow, - area.getLastRow(), - geometry.usableHeight() - repeatingHeight, - group.scale()); - List pageRows = repeatTitles - ? Arrays.asList( - new RowRange(repeatingFirstRow, repeatingLastRow), - new RowRange(startRow, endRow)) - : Collections.singletonList(new RowRange(startRow, endRow)); - renderPage( - document, - fonts, - workbook, - sheet, - groupArea, - merged, - group.widths(), - pageRows, - group.scale(), - geometry, - formatter, - evaluator, - legacyPictures); - startRow = endRow + 1; - } - } - } - - private static void renderPage( - PDDocument document, - FontSet fonts, - XSSFWorkbook workbook, - XSSFSheet sheet, - CellRangeAddress area, - List merged, - float[] columnWidths, - List pageRows, - float scale, - PageGeometry geometry, - DataFormatter formatter, - FormulaEvaluator evaluator, - List legacyPictures) throws IOException { - PDPage page = new PDPage(new PDRectangle(geometry.mediaWidth(), geometry.mediaHeight())); - document.addPage(page); - float unscaledWidth = sum(columnWidths, 0, columnWidths.length); - boolean centeredLegacy = !legacyPictures.isEmpty() - && sheet.getHorizontallyCenter() - && sheet.getVerticallyCenter(); - float horizontalScale = centeredLegacy - ? scale - : scale / geometry.outputScale(); - float verticalScale = scale * geometry.outputScale(); - if (centeredLegacy) { - horizontalScale = Math.min( - scale * CENTERED_VML_HORIZONTAL_GEOMETRY_SCALE, - geometry.usableWidth() / unscaledWidth); - } - float printedWidth = unscaledWidth * horizontalScale; - float horizontalOffset = sheet.getHorizontallyCenter() - ? Math.max(0.0f, (geometry.usableWidth() - printedWidth) / 2.0f) - : 0.0f; - float[] columnX = columnPositions( - columnWidths, - geometry.marginLeft() + horizontalOffset, - horizontalScale); - float usedHeight = (float) pageRows.stream() - .mapToDouble(rows -> rowsBefore(sheet, rows.firstRow(), rows.lastRow() + 1) * verticalScale) - .reduce(0.0, Double::sum); - float centerOffset = sheet.getVerticallyCenter() - ? Math.max(0.0f, (geometry.usableHeight() - usedHeight) / 2.0f) - : 0.0f; - try (PDPageContentStream content = new PDPageContentStream(document, page)) { - content.transform(new Matrix( - geometry.outputScale(), - 0.0f, - 0.0f, - geometry.outputScale(), - geometry.outputOffsetX(), - geometry.outputOffsetY())); - float rangeOffset = 0.0f; - for (RowRange rows : pageRows) { - float cellTop = geometry.layoutHeight() - geometry.marginTop() - centerOffset - rangeOffset; - for (int rowIndex = rows.firstRow(); rowIndex <= rows.lastRow(); rowIndex++) { - Row row = sheet.getRow(rowIndex); - float cellHeight = rowHeight(sheet, rowIndex) * verticalScale; - List pendingTexts = new ArrayList<>(); - for (int column = area.getFirstColumn(); column <= area.getLastColumn(); column++) { - int localColumn = column - area.getFirstColumn(); - float x = columnX[localColumn]; - float width = columnWidths[localColumn] * horizontalScale; - Cell cell = row == null - ? null - : row.getCell(column, Row.MissingCellPolicy.RETURN_NULL_AND_BLANK); - XSSFCellStyle style = cell == null ? null : (XSSFCellStyle) cell.getCellStyle(); - CellRangeAddress merge = mergedAt(merged, rowIndex, column); - boolean mergeOrigin = merge != null - && rowIndex == merge.getFirstRow() - && column == merge.getFirstColumn(); - float textWidth = merge == null - ? width - : mergedWidth(columnWidths, area.getFirstColumn(), merge, horizontalScale); - float textHeight = merge == null - ? cellHeight - : mergedHeight(sheet, merge, rows.firstRow(), rows.lastRow(), verticalScale); - if (merge == null) { - drawCell( - content, - style, - tableFill(sheet, rowIndex, column), - x, - cellTop - textHeight, - textWidth, - textHeight, - centeredLegacy ? CENTERED_VML_BORDER_SCALE : 1.0f); - } else if (mergeOrigin) { - drawMergedCell( - content, - sheet, - merge, - style, - tableFill(sheet, rowIndex, column), - x, - cellTop - textHeight, - textWidth, - textHeight, - centeredLegacy ? CENTERED_VML_BORDER_SCALE : 1.0f); - } - if (cell == null || (merge != null && !mergeOrigin)) { - continue; - } - String value = formatter.formatCellValue(cell, evaluator); - TextClip textClip = merge == null && style != null && !style.getWrapText() && isTextCell(cell) - ? textOverflowClip( - sheet, - rowIndex, - column, - area, - merged, - columnWidths, - x, - textWidth, - horizontalScale, - style.getAlignment(), - formatter, - evaluator) - : new TextClip(x, textWidth); - pendingTexts.add(new PendingText( - cell, - style, - value, - x, - cellTop - textHeight, - textWidth, - textHeight, - textClip.x(), - textClip.width(), - centeredLegacy ? 0.75f : CELL_PADDING)); - } - for (PendingText text : pendingTexts) { - drawText( - content, - fonts, - workbook, - text.cell(), - text.style(), - text.value(), - text.x(), - text.y(), - text.width(), - text.height(), - text.clipX(), - text.clipWidth(), - verticalScale, - text.padding()); - } - cellTop -= cellHeight; - } - drawPictures( - document, - content, - sheet, - area, - columnWidths, - rows.firstRow(), - rows.lastRow(), - verticalScale, - horizontalScale, - geometry, - horizontalOffset, - centerOffset + rangeOffset, - legacyPictures); - rangeOffset += rowsBefore(sheet, rows.firstRow(), rows.lastRow() + 1) * verticalScale; - } - } - } - - private static void drawCell( - PDPageContentStream content, - XSSFCellStyle style, - Color tableFill, - float x, - float y, - float width, - float height, - float borderScale) throws IOException { - Color fill = tableFill; - if (style != null && style.getFillPattern() == FillPatternType.SOLID_FOREGROUND) { - fill = color(style.getFillForegroundXSSFColor(), fill); - } - if (fill != null) { - content.setNonStrokingColor(fill); - content.addRect(x, y, width, height); - content.fill(); - } - if (style == null) { - return; - } - drawBorder(content, style.getBorderTop(), style.getTopBorderXSSFColor(), x, y + height, x + width, y + height, borderScale); - drawBorder(content, style.getBorderBottom(), style.getBottomBorderXSSFColor(), x, y, x + width, y, borderScale); - drawBorder(content, style.getBorderLeft(), style.getLeftBorderXSSFColor(), x, y, x, y + height, borderScale); - drawBorder(content, style.getBorderRight(), style.getRightBorderXSSFColor(), x + width, y, x + width, y + height, borderScale); - } - - private static void drawMergedCell( - PDPageContentStream content, - XSSFSheet sheet, - CellRangeAddress merge, - XSSFCellStyle style, - Color tableFill, - float x, - float y, - float width, - float height, - float borderScale) throws IOException { - Color fill = tableFill; - if (style != null && style.getFillPattern() == FillPatternType.SOLID_FOREGROUND) { - fill = color(style.getFillForegroundXSSFColor(), fill); - } - if (fill != null) { - content.setNonStrokingColor(fill); - content.addRect(x, y, width, height); - content.fill(); - } - BorderEdge top = mergedBorder(sheet, merge, BorderSide.TOP); - BorderEdge bottom = mergedBorder(sheet, merge, BorderSide.BOTTOM); - BorderEdge left = mergedBorder(sheet, merge, BorderSide.LEFT); - BorderEdge right = mergedBorder(sheet, merge, BorderSide.RIGHT); - drawBorder(content, top.style(), top.color(), x, y + height, x + width, y + height, borderScale); - drawBorder(content, bottom.style(), bottom.color(), x, y, x + width, y, borderScale); - drawBorder(content, left.style(), left.color(), x, y, x, y + height, borderScale); - drawBorder(content, right.style(), right.color(), x + width, y, x + width, y + height, borderScale); - } - - private static Color tableFill(XSSFSheet sheet, int rowIndex, int columnIndex) { - CellReference cell = new CellReference(sheet.getSheetName(), rowIndex, columnIndex, true, true); - Color fill = null; - for (XSSFTable table : sheet.getTables()) { - if (!table.contains(cell)) { - continue; - } - TableStyleInfo styleInfo = table.getStyle(); - if (styleInfo == null || styleInfo.getStyle() == null) { - continue; - } - for (TableStyleType type : TableStyleType.values()) { - DifferentialStyleProvider style = styleInfo.getStyle().getStyle(type); - CellRangeAddressBase range = type.getRange(table, cell); - if (style == null || range == null || !range.isInRange(rowIndex, columnIndex)) { - continue; - } - PatternFormatting pattern = style.getPatternFormatting(); - if (pattern == null) { - continue; - } - org.apache.poi.ss.usermodel.Color background = pattern.getFillBackgroundColorColor(); - org.apache.poi.ss.usermodel.Color foreground = pattern.getFillForegroundColorColor(); - if (background instanceof XSSFColor) { - XSSFColor xssfColor = (XSSFColor) background; - resolveThemeColor(sheet.getWorkbook(), xssfColor); - fill = color(xssfColor, fill); - } else if (foreground instanceof XSSFColor) { - XSSFColor xssfColor = (XSSFColor) foreground; - resolveThemeColor(sheet.getWorkbook(), xssfColor); - fill = color(xssfColor, fill); - } - } - } - return fill; - } - - private static void resolveThemeColor(XSSFWorkbook workbook, XSSFColor color) { - if (workbook.getStylesSource().getTheme() != null) { - workbook.getStylesSource().getTheme().inheritFromThemeAsRequired(color); - } - } - - private static BorderEdge mergedBorder( - XSSFSheet sheet, - CellRangeAddress merge, - BorderSide side) { - int start = side == BorderSide.TOP || side == BorderSide.BOTTOM - ? merge.getFirstColumn() - : merge.getFirstRow(); - int end = side == BorderSide.TOP || side == BorderSide.BOTTOM - ? merge.getLastColumn() - : merge.getLastRow(); - for (int index = start; index <= end; index++) { - int rowIndex; - int columnIndex; - switch (side) { - case TOP: - rowIndex = merge.getFirstRow(); - columnIndex = index; - break; - case BOTTOM: - rowIndex = merge.getLastRow(); - columnIndex = index; - break; - case LEFT: - rowIndex = index; - columnIndex = merge.getFirstColumn(); - break; - case RIGHT: - default: - rowIndex = index; - columnIndex = merge.getLastColumn(); - break; - } - Row row = sheet.getRow(rowIndex); - Cell cell = row == null ? null : row.getCell(columnIndex, Row.MissingCellPolicy.RETURN_NULL_AND_BLANK); - if (cell == null) { - continue; - } - XSSFCellStyle cellStyle = (XSSFCellStyle) cell.getCellStyle(); - BorderStyle borderStyle; - XSSFColor borderColor; - switch (side) { - case TOP: - borderStyle = cellStyle.getBorderTop(); - borderColor = cellStyle.getTopBorderXSSFColor(); - break; - case BOTTOM: - borderStyle = cellStyle.getBorderBottom(); - borderColor = cellStyle.getBottomBorderXSSFColor(); - break; - case LEFT: - borderStyle = cellStyle.getBorderLeft(); - borderColor = cellStyle.getLeftBorderXSSFColor(); - break; - case RIGHT: - default: - borderStyle = cellStyle.getBorderRight(); - borderColor = cellStyle.getRightBorderXSSFColor(); - break; - } - if (borderStyle != BorderStyle.NONE) { - return new BorderEdge(borderStyle, borderColor); - } - } - return new BorderEdge(BorderStyle.NONE, null); - } - - private static void drawBorder( - PDPageContentStream content, - BorderStyle border, - XSSFColor borderColor, - float x1, - float y1, - float x2, - float y2, - float borderScale) throws IOException { - if (border == null || border == BorderStyle.NONE) { - return; - } - content.setStrokingColor(color(borderColor, Color.BLACK)); - float lineWidth = borderWidth(border) * borderScale; - content.setLineWidth(lineWidth); - content.setLineDashPattern(borderDashPattern(border, lineWidth), 0.0f); - content.moveTo(x1, y1); - content.lineTo(x2, y2); - content.stroke(); - content.setLineDashPattern(new float[0], 0.0f); - } - - private static void drawText( - PDPageContentStream content, - FontSet fonts, - XSSFWorkbook workbook, - Cell cell, - XSSFCellStyle style, - String value, - float x, - float y, - float width, - float height, - float clipX, - float clipWidth, - float scale, - float padding) throws IOException { - if (value == null || value.isEmpty() || width <= padding * 2.0f || height <= 1.0f) { - return; - } - XSSFFont cellFont = workbook.getFontAt(style == null ? 0 : style.getFontIndex()); - float fontSize = Math.max(4.0f, cellFont.getFontHeightInPoints() * scale); - PDFont font = fonts.resolve(cellFont.getFontName(), value, cellFont.getBold(), cellFont.getItalic()); - String safeValue = fonts.sanitize(font, value.replace('\t', ' ').replace('\r', '\n')); - List lines = style != null && style.getRotation() == 255 - ? safeValue.codePoints() - .filter(codePoint -> codePoint != '\n') - .mapToObj(codePoint -> new String(Character.toChars(codePoint))) - .collect(Collectors.toList()) - : fonts.wrap(font, safeValue, fontSize, width - padding * 2.0f, style != null && style.getWrapText()); - float lineHeight = fontSize * 1.18f; - float verticalPadding = padding; - int maxLines = Math.max(1, 1 + (int) Math.floor((height - fontSize) / lineHeight)); - if (lines.size() > maxLines) { - lines = lines.subList(0, maxLines); - } - float blockHeight = fontSize + Math.max(0, lines.size() - 1) * lineHeight; - VerticalAlignment vertical = style == null ? VerticalAlignment.BOTTOM : style.getVerticalAlignment(); - float baseline; - switch (vertical) { - case TOP: - baseline = y + height - verticalPadding - fontSize; - break; - case CENTER: - baseline = y + (height + blockHeight) / 2.0f - fontSize; - break; - default: - baseline = y + verticalPadding + blockHeight - fontSize; - break; - } - Color textColor = color(cellFont.getXSSFColor(), Color.BLACK); - content.saveGraphicsState(); - content.addRect(clipX + 0.2f, y + 0.2f, Math.max(0.1f, clipWidth - 0.4f), Math.max(0.1f, height - 0.4f)); - content.clip(); - content.setNonStrokingColor(textColor); - if (cellFont.getBold() - && fonts.requiresSyntheticBold(cellFont.getFontName(), value, cellFont.getItalic())) { - content.setStrokingColor(textColor); - content.setLineWidth(Math.max(0.15f, fontSize * 0.025f)); - content.setRenderingMode(RenderingMode.FILL_STROKE); - } - for (String line : lines) { - float lineWidth = fonts.textWidth(font, line, fontSize); - HorizontalAlignment alignment = style == null ? HorizontalAlignment.GENERAL : style.getAlignment(); - float textX; - switch (alignment) { - case CENTER: - case CENTER_SELECTION: - textX = x + Math.max(padding, (width - lineWidth) / 2.0f); - break; - case RIGHT: - textX = x + Math.max(padding, width - padding - lineWidth); - break; - default: - textX = x + padding; - break; - } - content.beginText(); - boolean firstRun = true; - for (FontSet.TextRun run : fonts.runs(font, line)) { - content.setFont(run.font(), fontSize); - if (firstRun) { - content.newLineAtOffset(textX, baseline); - firstRun = false; - } - content.showText(run.text()); - } - content.endText(); - baseline -= lineHeight; - } - content.restoreGraphicsState(); - } - - private static void drawPictures( - PDDocument document, - PDPageContentStream content, - XSSFSheet sheet, - CellRangeAddress area, - float[] columnWidths, - int startRow, - int endRow, - float scale, - float horizontalScale, - PageGeometry geometry, - float horizontalOffset, - float centerOffset, - List legacyPictures) throws IOException { - XSSFDrawing drawing = sheet.getDrawingPatriarch(); - if (drawing != null) { - for (XSSFShape shape : drawing.getShapes()) { - if (shape instanceof XSSFPicture) { - XSSFPicture picture = (XSSFPicture) shape; - XSSFClientAnchor anchor = picture.getClientAnchor(); - if (anchor == null || anchor.getRow1() < startRow || anchor.getRow1() > endRow) { - continue; - } - drawPicture(document, content, sheet.getWorkbook(), picture, pictureBounds( - sheet, - area, - columnWidths, - startRow, - scale, - horizontalScale, - geometry, - horizontalOffset, - centerOffset, - anchor)); - } else if (shape instanceof XSSFShapeGroup) { - XSSFShapeGroup group = (XSSFShapeGroup) shape; - drawShapeGroup( - document, - content, - drawing, - group, - sheet, - area, - columnWidths, - startRow, - endRow, - scale, - horizontalScale, - geometry, - horizontalOffset, - centerOffset); - } else if (shape instanceof XSSFSimpleShape) { - XSSFSimpleShape simpleShape = (XSSFSimpleShape) shape; - if (!(simpleShape.getAnchor() instanceof XSSFClientAnchor)) { - continue; - } - XSSFClientAnchor anchor = (XSSFClientAnchor) simpleShape.getAnchor(); - if (anchor.getRow1() < startRow || anchor.getRow1() > endRow - || anchor.getCol1() > area.getLastColumn() - || anchor.getCol2() < area.getFirstColumn()) { - continue; - } - drawRectangleShape( - content, - sheet.getWorkbook(), - simpleShape, - pictureBounds( - sheet, - area, - columnWidths, - startRow, - scale, - horizontalScale, - geometry, - horizontalOffset, - centerOffset, - anchor)); - } - } - } - for (LegacyPicture picture : legacyPictures) { - drawLegacyPicture( - document, - content, - sheet, - area, - columnWidths, - startRow, - endRow, - scale, - horizontalScale, - geometry, - horizontalOffset, - centerOffset, - picture); - } - } - - private static void drawLegacyPicture( - PDDocument document, - PDPageContentStream content, - XSSFSheet sheet, - CellRangeAddress area, - float[] columnWidths, - int startRow, - int endRow, - float scale, - float horizontalScale, - PageGeometry geometry, - float horizontalOffset, - float centerOffset, - LegacyPicture picture) throws IOException { - int[] anchor = picture.anchor(); - int column1 = anchor[0]; - int row1 = anchor[2]; - int column2 = anchor[4]; - int row2 = anchor[6]; - if (row1 < startRow || row1 > endRow - || column2 < area.getFirstColumn() || column1 > area.getLastColumn()) { - return; - } - float x = geometry.marginLeft() + horizontalOffset - + columnsBefore(columnWidths, area.getFirstColumn(), column1) * horizontalScale - + columnWidth(sheet, column1) * anchor[1] / 1024.0f * horizontalScale; - float top = geometry.layoutHeight() - geometry.marginTop() - centerOffset - - rowsBefore(sheet, startRow, row1) * scale - - rowHeight(sheet, row1) * anchor[3] / 256.0f * scale; - float width = (columnsBefore(columnWidths, area.getFirstColumn(), column2) - - columnsBefore(columnWidths, area.getFirstColumn(), column1)) * horizontalScale - + (columnWidth(sheet, column2) * anchor[5] / 1024.0f - - columnWidth(sheet, column1) * anchor[1] / 1024.0f) * horizontalScale; - float height = rowsBefore(sheet, row1, row2) * scale - + (rowHeight(sheet, row2) * anchor[7] / 256.0f - - rowHeight(sheet, row1) * anchor[3] / 256.0f) * scale; - if (width <= 0.0f || height <= 0.0f) { - return; - } - if (!drawVectorEmf(document, content, picture, x, top - height, width, height)) { - PDImageXObject image = PDImageXObject.createFromByteArray(document, picture.png(), picture.path()); - content.drawImage(image, x, top - height, width, height); - } - } - - /** - * Renders a standalone DrawingML rectangle shape (xdr:sp with a rect - * preset geometry), mirroring the .NET engine's ExcelDrawingShape support. - */ - private static void drawRectangleShape( - PDPageContentStream content, - XSSFWorkbook workbook, - XSSFSimpleShape shape, - ShapeBounds bounds) throws IOException { - CTShapeProperties properties = shape.getCTShape().getSpPr(); - if (!properties.isSetPrstGeom() - || properties.getPrstGeom().getPrst() != STShapeType.RECT - || !properties.isSetSolidFill()) { - return; - } - Color fill = shapeFill(workbook, properties.getSolidFill()); - if (fill == null) { - return; - } - content.setNonStrokingColor(fill); - content.addRect( - bounds.x(), - bounds.top() - bounds.height(), - bounds.width(), - bounds.height()); - content.fill(); - } - - private static Color shapeFill(XSSFWorkbook workbook, CTSolidColorFillProperties solidFill) { - if (solidFill.isSetSrgbClr()) { - CTSRgbColor rgb = solidFill.getSrgbClr(); - byte[] value = rgb.getVal(); - if (value == null || value.length < 3) { - return null; - } - return new Color( - Byte.toUnsignedInt(value[0]), - Byte.toUnsignedInt(value[1]), - Byte.toUnsignedInt(value[2])); - } - if (!solidFill.isSetSchemeClr()) { - return null; - } - CTSchemeColor scheme = solidFill.getSchemeClr(); - int themeIndex = schemeColorThemeIndex(scheme.getVal()); - if (themeIndex < 0 || workbook.getStylesSource().getTheme() == null) { - return null; - } - XSSFColor themeColor = workbook.getStylesSource().getTheme().getThemeColor(themeIndex); - byte[] rgb = themeColor == null ? null : themeColor.getRGB(); - if (rgb == null || rgb.length < 3) { - return null; - } - double red = Byte.toUnsignedInt(rgb[0]); - double green = Byte.toUnsignedInt(rgb[1]); - double blue = Byte.toUnsignedInt(rgb[2]); - if (scheme.sizeOfLumModArray() > 0) { - double modifier = Integer.parseInt(scheme.getLumModArray(0).xgetVal().toString()) / 100_000.0; - red *= modifier; - green *= modifier; - blue *= modifier; - } - if (scheme.sizeOfLumOffArray() > 0) { - double offset = Integer.parseInt(scheme.getLumOffArray(0).xgetVal().toString()) / 100_000.0; - red += offset * 255.0; - green += offset * 255.0; - blue += offset * 255.0; - } - return new Color( - (int) Math.round(Math.min(255.0, red)), - (int) Math.round(Math.min(255.0, green)), - (int) Math.round(Math.min(255.0, blue))); - } - - private static int schemeColorThemeIndex(STSchemeColorVal.Enum value) { - if (value == null) { - return -1; - } - switch (value.toString()) { - case "lt1": - case "bg1": - return 0; - case "dk1": - case "tx1": - return 1; - case "lt2": - case "bg2": - return 2; - case "dk2": - case "tx2": - return 3; - case "accent1": - return 4; - case "accent2": - return 5; - case "accent3": - return 6; - case "accent4": - return 7; - case "accent5": - return 8; - case "accent6": - return 9; - case "hlink": - return 10; - case "folHlink": - return 11; - default: - return -1; - } - } - - private static void drawShapeGroup( - PDDocument document, - PDPageContentStream content, - XSSFDrawing drawing, - XSSFShapeGroup group, - XSSFSheet sheet, - CellRangeAddress area, - float[] columnWidths, - int startRow, - int endRow, - float scale, - float horizontalScale, - PageGeometry geometry, - float horizontalOffset, - float centerOffset) throws IOException { - if (!(group.getAnchor() instanceof XSSFClientAnchor)) { - return; - } - XSSFClientAnchor anchor = (XSSFClientAnchor) group.getAnchor(); - if (anchor.getRow1() < startRow - || anchor.getRow1() > endRow) { - return; - } - ShapeBounds groupBounds = pictureBounds( - sheet, - area, - columnWidths, - startRow, - scale, - horizontalScale, - geometry, - horizontalOffset, - centerOffset, - anchor); - CTGroupTransform2D groupTransform = group.getCTGroupShape().getGrpSpPr().getXfrm(); - if (groupTransform == null - || groupTransform.getChExt().getCx() == 0 - || groupTransform.getChExt().getCy() == 0) { - return; - } - for (XSSFShape child : drawing.getShapes(group)) { - CTTransform2D childTransform; - if (child instanceof XSSFPicture - && ((XSSFPicture) child).getCTPicture().getSpPr().isSetXfrm()) { - XSSFPicture picture = (XSSFPicture) child; - childTransform = picture.getCTPicture().getSpPr().getXfrm(); - } else if (child instanceof XSSFSimpleShape - && ((XSSFSimpleShape) child).getCTShape().getSpPr().isSetXfrm()) { - XSSFSimpleShape simpleShape = (XSSFSimpleShape) child; - childTransform = simpleShape.getCTShape().getSpPr().getXfrm(); - } else { - continue; - } - float relativeX = (coordinate(childTransform.getOff().getX()) - - coordinate(groupTransform.getChOff().getX())) - / groupTransform.getChExt().getCx(); - float relativeY = (coordinate(childTransform.getOff().getY()) - - coordinate(groupTransform.getChOff().getY())) - / groupTransform.getChExt().getCy(); - ShapeBounds childBounds = new ShapeBounds( - groupBounds.x() + relativeX * groupBounds.width(), - groupBounds.top() - relativeY * groupBounds.height(), - (float) childTransform.getExt().getCx() / groupTransform.getChExt().getCx() * groupBounds.width(), - (float) childTransform.getExt().getCy() / groupTransform.getChExt().getCy() * groupBounds.height()); - if (child instanceof XSSFPicture) { - drawPicture(document, content, sheet.getWorkbook(), (XSSFPicture) child, childBounds); - } else if (child instanceof XSSFSimpleShape) { - drawCustomShape(content, (XSSFSimpleShape) child, childBounds); - } - } - } - - private static float coordinate(Object value) { - return value instanceof Number - ? ((Number) value).floatValue() - : Float.parseFloat(value.toString()); - } - - private static void drawCustomShape( - PDPageContentStream content, - XSSFSimpleShape shape, - ShapeBounds bounds) throws IOException { - CTShapeProperties properties = shape.getCTShape().getSpPr(); - if (!properties.isSetCustGeom() || !properties.isSetSolidFill() - || !properties.getSolidFill().isSetSrgbClr()) { - return; - } - CTSRgbColor rgb = properties.getSolidFill().getSrgbClr(); - byte[] value = rgb.getVal(); - if (value == null || value.length < 3) { - return; - } - float alpha = rgb.sizeOfAlphaArray() == 0 - ? 1.0f - : coordinate(rgb.getAlphaArray(0).getVal()) / 100_000.0f; - content.saveGraphicsState(); - try { - content.setNonStrokingColor(new Color( - Byte.toUnsignedInt(value[0]), - Byte.toUnsignedInt(value[1]), - Byte.toUnsignedInt(value[2]))); - PDExtendedGraphicsState graphicsState = new PDExtendedGraphicsState(); - graphicsState.setNonStrokingAlphaConstant(alpha); - content.setGraphicsStateParameters(graphicsState); - for (CTPath2D path : properties.getCustGeom().getPathLst().getPathArray()) { - float pathWidth = path.getW() > 0 ? path.getW() : 1.0f; - float pathHeight = path.getH() > 0 ? path.getH() : 1.0f; - boolean hasSegments = false; - try (XmlCursor cursor = path.newCursor()) { - if (cursor.toFirstChild()) { - do { - XmlObject segment = cursor.getObject(); - if (segment instanceof CTPath2DMoveTo) { - CTPath2DMoveTo move = (CTPath2DMoveTo) segment; - moveTo(content, move.getPt(), bounds, pathWidth, pathHeight); - hasSegments = true; - } else if (segment instanceof CTPath2DLineTo) { - CTPath2DLineTo line = (CTPath2DLineTo) segment; - lineTo(content, line.getPt(), bounds, pathWidth, pathHeight); - } else if (segment instanceof CTPath2DQuadBezierTo) { - CTPath2DQuadBezierTo quadratic = (CTPath2DQuadBezierTo) segment; - CTAdjPoint2D control = quadratic.getPtArray(0); - CTAdjPoint2D end = quadratic.getPtArray(1); - float currentX = shapeX(bounds, coordinate(control.getX()), pathWidth); - float currentY = shapeY(bounds, coordinate(control.getY()), pathHeight); - float endX = shapeX(bounds, coordinate(end.getX()), pathWidth); - float endY = shapeY(bounds, coordinate(end.getY()), pathHeight); - content.curveTo1(currentX, currentY, endX, endY); - } else if (segment instanceof CTPath2DCubicBezierTo) { - CTPath2DCubicBezierTo cubic = (CTPath2DCubicBezierTo) segment; - CTAdjPoint2D first = cubic.getPtArray(0); - CTAdjPoint2D second = cubic.getPtArray(1); - CTAdjPoint2D end = cubic.getPtArray(2); - content.curveTo( - shapeX(bounds, coordinate(first.getX()), pathWidth), - shapeY(bounds, coordinate(first.getY()), pathHeight), - shapeX(bounds, coordinate(second.getX()), pathWidth), - shapeY(bounds, coordinate(second.getY()), pathHeight), - shapeX(bounds, coordinate(end.getX()), pathWidth), - shapeY(bounds, coordinate(end.getY()), pathHeight)); - } else if (segment instanceof CTPath2DClose) { - content.closePath(); - } - } while (cursor.toNextSibling()); - } - } - if (hasSegments) { - content.fill(); - } - } - } finally { - content.restoreGraphicsState(); - } - } - - private static void moveTo( - PDPageContentStream content, - CTAdjPoint2D point, - ShapeBounds bounds, - float pathWidth, - float pathHeight) throws IOException { - content.moveTo( - shapeX(bounds, coordinate(point.getX()), pathWidth), - shapeY(bounds, coordinate(point.getY()), pathHeight)); - } - - private static void lineTo( - PDPageContentStream content, - CTAdjPoint2D point, - ShapeBounds bounds, - float pathWidth, - float pathHeight) throws IOException { - content.lineTo( - shapeX(bounds, coordinate(point.getX()), pathWidth), - shapeY(bounds, coordinate(point.getY()), pathHeight)); - } - - private static float shapeX(ShapeBounds bounds, float value, float pathWidth) { - return bounds.x() + value / pathWidth * bounds.width(); - } - - private static float shapeY(ShapeBounds bounds, float value, float pathHeight) { - return bounds.top() - value / pathHeight * bounds.height(); - } - - private static ShapeBounds pictureBounds( - XSSFSheet sheet, - CellRangeAddress area, - float[] columnWidths, - int startRow, - float scale, - float horizontalScale, - PageGeometry geometry, - float horizontalOffset, - float centerOffset, - XSSFClientAnchor anchor) { - float x = geometry.marginLeft() + horizontalOffset - + columnsBefore(columnWidths, area.getFirstColumn(), anchor.getCol1()) * horizontalScale - + anchor.getDx1() / EMU_PER_POINT * horizontalScale; - float top = geometry.layoutHeight() - geometry.marginTop() - centerOffset - - rowsBefore(sheet, startRow, anchor.getRow1()) * scale - - anchor.getDy1() / EMU_PER_POINT * scale; - float width = (columnsBefore(columnWidths, area.getFirstColumn(), anchor.getCol2()) - - columnsBefore(columnWidths, area.getFirstColumn(), anchor.getCol1())) * horizontalScale - + (anchor.getDx2() - anchor.getDx1()) / EMU_PER_POINT * horizontalScale; - float height = rowsBefore(sheet, anchor.getRow1(), anchor.getRow2()) * scale - + (anchor.getDy2() - anchor.getDy1()) / EMU_PER_POINT * scale; - return new ShapeBounds(x, top, width, height); - } - - private static void drawPicture( - PDDocument document, - PDPageContentStream content, - XSSFWorkbook workbook, - XSSFPicture picture, - ShapeBounds bounds) throws IOException { - if (bounds.width() <= 0.0f || bounds.height() <= 0.0f || picture.getPictureData() == null) { - return; - } - CTShapeProperties properties = picture.getCTPicture().getSpPr(); - if (properties != null && properties.isSetSolidFill()) { - // Excel and LibreOffice draw the picture's background fill (e.g. bg1 - // white) behind the image so the sheet content does not show through - // transparent pixels. - Color fill = shapeFill(workbook, properties.getSolidFill()); - if (fill != null) { - content.setNonStrokingColor(fill); - content.addRect( - bounds.x(), - bounds.top() - bounds.height(), - bounds.width(), - bounds.height()); - content.fill(); - } - } - try { - PDImageXObject image = PDImageXObject.createFromByteArray( - document, - picture.getPictureData().getData(), - picture.getShapeName()); - content.drawImage(image, bounds.x(), bounds.top() - bounds.height(), bounds.width(), bounds.height()); - } catch (IllegalArgumentException ignored) { - } - } - - private static boolean drawVectorEmf( - PDDocument document, - PDPageContentStream content, - LegacyPicture picture, - float x, - float y, - float width, - float height) throws IOException { - if (!picture.path().toLowerCase(Locale.ROOT).endsWith(".emf")) { - return false; - } - PdfBoxGraphics2D graphics = new PdfBoxGraphics2D(document, width, height); - try { - HemfPicture emf = new HemfPicture(new ByteArrayInputStream(picture.data())); - emf.draw(graphics, new Rectangle2D.Float(0.0f, 0.0f, width, height)); - } catch (RuntimeException exception) { - return false; - } finally { - graphics.dispose(); - } - PDFormXObject form = graphics.getXFormObject(); - content.saveGraphicsState(); - try { - content.transform(Matrix.getTranslateInstance(x, y)); - content.drawForm(form); - } finally { - content.restoreGraphicsState(); - } - return true; - } - - private static CellRangeAddress printArea(XSSFWorkbook workbook, XSSFSheet sheet, int sheetIndex) { - String value = printAreaValue(workbook, sheet, sheetIndex); - if (value != null && !value.trim().isEmpty()) { - AreaReference reference = new AreaReference(value, SpreadsheetVersion.EXCEL2007); - CellReference first = reference.getFirstCell(); - CellReference last = reference.getLastCell(); - return new CellRangeAddress(first.getRow(), last.getRow(), first.getCol(), last.getCol()); - } - int firstRow = Math.max(0, sheet.getFirstRowNum()); - int lastRow = Math.max(firstRow, sheet.getLastRowNum()); - int lastColumn = 0; - for (Row row : sheet) { - lastColumn = Math.max(lastColumn, Math.max(0, row.getLastCellNum() - 1)); - } - for (CellRangeAddress merge : sheet.getMergedRegions()) { - lastColumn = Math.max(lastColumn, merge.getLastColumn()); - } - return new CellRangeAddress(firstRow, lastRow, 0, lastColumn); - } - - private static String printAreaValue(XSSFWorkbook workbook, XSSFSheet sheet, int sheetIndex) { - String direct = workbook.getPrintArea(sheetIndex); - if (referencesSheet(direct, sheet.getSheetName())) { - return direct; - } - for (Name name : workbook.getAllNames()) { - if ("_xlnm.Print_Area".equals(name.getNameName()) - && referencesSheet(name.getRefersToFormula(), sheet.getSheetName())) { - return name.getRefersToFormula(); - } - } - if (workbook.getCTWorkbook().isSetDefinedNames()) { - for (CTDefinedName name : workbook.getCTWorkbook().getDefinedNames().getDefinedNameList()) { - if ("_xlnm.Print_Area".equals(name.getName()) - && referencesSheet(name.getStringValue(), sheet.getSheetName())) { - return name.getStringValue(); - } - } - } - return null; - } - - private static boolean referencesSheet(String formula, String sheetName) { - if (formula == null || formula.trim().isEmpty()) { - return false; - } - int separator = formula.indexOf('!'); - if (separator < 0) { - return true; - } - String referenceSheet = formula.substring(0, separator); - if (referenceSheet.startsWith("'") && referenceSheet.endsWith("'")) { - referenceSheet = referenceSheet.substring(1, referenceSheet.length() - 1).replace("''", "'"); - } - return referenceSheet.equals(sheetName); - } - - private static PageGeometry pageGeometry(XSSFSheet sheet, ConversionOptions options) { - PageSize configured = options.pageSize().orElse(null); - float layoutWidth; - float layoutHeight; - float mediaWidth; - float mediaHeight; - if (configured != null) { - layoutWidth = configured.width(); - layoutHeight = configured.height(); - mediaWidth = layoutWidth; - mediaHeight = layoutHeight; - } else { - PrintSetup setup = sheet.getPrintSetup(); - boolean explicitPaperSize = sheet.getCTWorksheet().isSetPageSetup() - && sheet.getCTWorksheet().getPageSetup().isSetPaperSize(); - boolean scaledDefaultPaper = !explicitPaperSize - && explicitScale(sheet) - && !sheet.getCTWorksheet().getPageSetup().isSetFitToHeight(); - boolean letter = !scaledDefaultPaper && setup.getPaperSize() == PrintSetup.LETTER_PAPERSIZE; - layoutWidth = letter ? PageSize.LETTER.width() : PageSize.A4.width(); - layoutHeight = letter ? PageSize.LETTER.height() : PageSize.A4.height(); - mediaWidth = explicitPaperSize ? layoutWidth : PageSize.A4.width(); - mediaHeight = explicitPaperSize ? layoutHeight : PageSize.A4.height(); - if (setup.getLandscape()) { - float layoutSwap = layoutWidth; - layoutWidth = layoutHeight; - layoutHeight = layoutSwap; - float mediaSwap = mediaWidth; - mediaWidth = mediaHeight; - mediaHeight = mediaSwap; - } - } - float left = margin(sheet.getMargin(PageMargin.LEFT), 0.25f); - float right = margin(sheet.getMargin(PageMargin.RIGHT), 0.25f); - float top = margin(sheet.getMargin(PageMargin.TOP), 0.3f); - float bottom = margin(sheet.getMargin(PageMargin.BOTTOM), 0.3f); - return new PageGeometry( - layoutWidth, - layoutHeight, - mediaWidth, - mediaHeight, - left, - right, - top, - bottom); - } - - private static float margin(double inches, float fallback) { - return (float) ((inches > 0.0 ? inches : fallback) * POINTS_PER_INCH); - } - - private static float[] columnWidths(XSSFSheet sheet, CellRangeAddress area) { - float[] widths = new float[area.getLastColumn() - area.getFirstColumn() + 1]; - for (int column = area.getFirstColumn(); column <= area.getLastColumn(); column++) { - widths[column - area.getFirstColumn()] = columnWidth(sheet, column); - } - return widths; - } - - private static float columnWidth(XSSFSheet sheet, int column) { - if (sheet.isColumnHidden(column)) { - return 0.0f; - } - XSSFWorkbook workbook = sheet.getWorkbook(); - XSSFFont normalFont = workbook.getFontAt(workbook.getCellStyleAt(0).getFontIndex()); - float maxDigitWidth = maxDigitWidth(normalFont.getFontName(), normalFont.getFontHeightInPoints()); - float characterUnits = sheet.getColumnWidth(column) / 256.0f; - float padding = (float) Math.floor(128.0f / maxDigitWidth); - float pixels = (float) Math.floor( - ((256.0f * characterUnits + padding) / 256.0f) * maxDigitWidth); - return Math.max(1.0f, pixels * POINTS_PER_PIXEL); - } - - private static float maxDigitWidth(String fontName, float fontSize) { - String normalized = fontName == null ? "" : fontName.trim().toLowerCase(Locale.ROOT); - float widthAtTenPoints; - if ("arial".equals(normalized)) { - widthAtTenPoints = 7.06f; - } else if ("palatino linotype".equals(normalized)) { - widthAtTenPoints = 6.42f; - } else if ("verdana".equals(normalized)) { - widthAtTenPoints = 7.55f; - } else { - widthAtTenPoints = 7.0f; - } - return widthAtTenPoints * (fontSize > 0.0f ? fontSize : 10.0f) / 10.0f; - } - - private static List columnGroups( - XSSFSheet sheet, - CellRangeAddress area, - PageGeometry geometry, - XSSFPrintSetup setup, - boolean hasPrintArea, - float verticalScaleLimit) { - float[] allWidths = columnWidths(sheet, area); - float naturalWidth = sum(allWidths, 0, allWidths.length); - boolean explicitFitWidth = sheet.getCTWorksheet().isSetPageSetup() - && sheet.getCTWorksheet().getPageSetup().isSetFitToWidth(); - boolean unlimitedFitHeight = sheet.getCTWorksheet().isSetPageSetup() - && sheet.getCTWorksheet().getPageSetup().isSetFitToHeight() - && setup.getFitHeight() == 0; - boolean fitOnePageWide = hasPrintArea - || (sheet.getFitToPage() - && (explicitFitWidth || !explicitScale(sheet) || unlimitedFitHeight) - && setup.getFitWidth() == 1); - float scale = setup.getScale() > 0 ? setup.getScale() / 100.0f : 1.0f; - if (fitOnePageWide || naturalWidth * scale <= geometry.usableWidth()) { - if (fitOnePageWide) { - scale = naturalWidth > 0.0f - ? Math.min(1.0f, geometry.usableWidth() / naturalWidth) - : 1.0f; - } - scale = Math.min(scale, verticalScaleLimit); - return Collections.singletonList( - new ColumnGroup(area.getFirstColumn(), area.getLastColumn(), allWidths, scale)); - } - - scale = Math.min(scale, verticalScaleLimit); - List groups = new ArrayList<>(); - int groupStart = 0; - float groupWidth = 0.0f; - for (int index = 0; index < allWidths.length; index++) { - float next = allWidths[index] * scale; - if (index > groupStart && groupWidth + next > geometry.usableWidth()) { - groups.add(columnGroup(area, allWidths, groupStart, index, scale)); - groupStart = index; - groupWidth = 0.0f; - } - groupWidth += next; - } - groups.add(columnGroup(area, allWidths, groupStart, allWidths.length, scale)); - return groups; - } - - private static boolean explicitScale(XSSFSheet sheet) { - return sheet.getCTWorksheet().isSetPageSetup() - && sheet.getCTWorksheet().getPageSetup().isSetScale(); - } - - private static ColumnGroup columnGroup( - CellRangeAddress area, - float[] allWidths, - int start, - int end, - float scale) { - float[] widths = new float[end - start]; - System.arraycopy(allWidths, start, widths, 0, widths.length); - return new ColumnGroup( - area.getFirstColumn() + start, - area.getFirstColumn() + end - 1, - widths, - scale); - } - - private static float[] columnPositions(float[] widths, float start, float scale) { - float[] positions = new float[widths.length]; - float x = start; - for (int index = 0; index < widths.length; index++) { - positions[index] = x; - x += widths[index] * scale; - } - return positions; - } - - private static float[] rowPositions(XSSFSheet sheet, int startRow, int endRow, float start, float scale) { - float[] positions = new float[endRow - startRow + 1]; - float y = start; - for (int row = startRow; row <= endRow; row++) { - positions[row - startRow] = y; - y -= rowHeight(sheet, row) * scale; - } - return positions; - } - - private static int pageEndRow(XSSFSheet sheet, int startRow, int lastRow, float available, float scale) { - float used = 0.0f; - int row = startRow; - while (row <= lastRow) { - float next = rowHeight(sheet, row) * scale; - if (row > startRow && (used + next > available + 0.5f || sheet.isRowBroken(row - 1))) { - break; - } - used += next; - row++; - } - return Math.max(startRow, row - 1); - } - - private static float rowHeight(XSSFSheet sheet, int rowIndex) { - Row row = sheet.getRow(rowIndex); - if (row != null && row.getZeroHeight()) { - return 0.0f; - } - float height = row == null - ? sheet.getDefaultRowHeightInPoints() - : row.getHeightInPoints(); - if (row != null) { - for (Cell cell : row) { - XSSFFont font = sheet.getWorkbook().getFontAt(cell.getCellStyle().getFontIndex()); - if ("verdana".equalsIgnoreCase(font.getFontName())) { - return height * VERDANA_ROW_HEIGHT_SCALE; - } - } - } - return height; - } - - private static CellRangeAddress mergedAt(List merged, int row, int column) { - for (CellRangeAddress range : merged) { - if (range.isInRange(row, column)) { - return range; - } - } - return null; - } - - private static float mergedWidth( - float[] columnWidths, - int areaFirstColumn, - CellRangeAddress merge, - float scale) { - int first = Math.max(0, merge.getFirstColumn() - areaFirstColumn); - int end = Math.min(columnWidths.length, merge.getLastColumn() - areaFirstColumn + 1); - return sum(columnWidths, first, end) * scale; - } - - private static float mergedHeight( - XSSFSheet sheet, - CellRangeAddress merge, - int pageStart, - int pageEnd, - float scale) { - float height = 0.0f; - for (int row = Math.max(pageStart, merge.getFirstRow()); row <= Math.min(pageEnd, merge.getLastRow()); row++) { - height += rowHeight(sheet, row) * scale; - } - return height; - } - - private static boolean isTextCell(Cell cell) { - return cell.getCellType() == CellType.STRING - || (cell.getCellType() == CellType.FORMULA - && cell.getCachedFormulaResultType() == CellType.STRING); - } - - private static TextClip textOverflowClip( - XSSFSheet sheet, - int rowIndex, - int column, - CellRangeAddress area, - List merged, - float[] columnWidths, - float x, - float width, - float scale, - HorizontalAlignment alignment, - DataFormatter formatter, - FormulaEvaluator evaluator) { - float clipX = x; - float clipWidth = width; - if (alignment == HorizontalAlignment.RIGHT || alignment == HorizontalAlignment.CENTER) { - for (int adjacent = column - 1; adjacent >= area.getFirstColumn(); adjacent--) { - if (cellBlocksTextOverflow(sheet, rowIndex, adjacent, merged, formatter, evaluator)) { - break; - } - float adjacentWidth = columnWidths[adjacent - area.getFirstColumn()] * scale; - clipX -= adjacentWidth; - clipWidth += adjacentWidth; - } - } - if (alignment != HorizontalAlignment.RIGHT) { - for (int adjacent = column + 1; adjacent <= area.getLastColumn(); adjacent++) { - if (cellBlocksTextOverflow(sheet, rowIndex, adjacent, merged, formatter, evaluator)) { - break; - } - clipWidth += columnWidths[adjacent - area.getFirstColumn()] * scale; - } - } - return new TextClip(clipX, clipWidth); - } - - private static boolean cellBlocksTextOverflow( - XSSFSheet sheet, - int rowIndex, - int column, - List merged, - DataFormatter formatter, - FormulaEvaluator evaluator) { - CellRangeAddress merge = mergedAt(merged, rowIndex, column); - int sourceRow = merge == null ? rowIndex : merge.getFirstRow(); - int sourceColumn = merge == null ? column : merge.getFirstColumn(); - Row row = sheet.getRow(sourceRow); - Cell cell = row == null ? null : row.getCell(sourceColumn, Row.MissingCellPolicy.RETURN_BLANK_AS_NULL); - return cell != null && !formatter.formatCellValue(cell, evaluator).trim().isEmpty(); - } - - private static float columnsBefore(float[] widths, int areaFirstColumn, int column) { - return sum(widths, 0, Math.max(0, Math.min(widths.length, column - areaFirstColumn))); - } - - private static float rowsBefore(XSSFSheet sheet, int startRow, int endRow) { - float height = 0.0f; - for (int row = startRow; row < endRow; row++) { - height += rowHeight(sheet, row); - } - return height; - } - - private static float sum(float[] values, int start, int end) { - float total = 0.0f; - for (int index = start; index < end; index++) { - total += values[index]; - } - return total; - } - - private static float borderWidth(BorderStyle style) { - switch (style) { - case HAIR: - return 0.1f; - case MEDIUM: - case MEDIUM_DASHED: - case MEDIUM_DASH_DOT: - case MEDIUM_DASH_DOT_DOT: - return 1.0f; - case THICK: - case DOUBLE: - return 1.5f; - default: - return 0.35f; - } - } - - private static float[] borderDashPattern(BorderStyle style, float lineWidth) { - switch (style) { - case DOTTED: - return new float[]{0.2f, 0.8f}; - case DASHED: - case MEDIUM_DASHED: - return new float[]{4.0f, 2.0f}; - case DASH_DOT: - case MEDIUM_DASH_DOT: - case SLANTED_DASH_DOT: - return new float[]{4.0f, 1.5f, Math.max(0.5f, lineWidth), 1.5f}; - case DASH_DOT_DOT: - case MEDIUM_DASH_DOT_DOT: - return new float[]{ - 4.0f, - 1.0f, - Math.max(0.5f, lineWidth), - 1.0f, - Math.max(0.5f, lineWidth), - 1.0f}; - case HAIR: - return new float[]{0.5f, 0.5f}; - default: - return new float[0]; - } - } - - private static Color color(XSSFColor source, Color fallback) { - if (source == null) { - return fallback; - } - byte[] rgb = source.getRGB(); - if (rgb == null || rgb.length < 3) { - byte[] argb = source.getARGB(); - if (argb == null || argb.length < 4) { - return fallback; - } - rgb = new byte[]{argb[1], argb[2], argb[3]}; - } - float red = Byte.toUnsignedInt(rgb[0]) / 255.0f; - float green = Byte.toUnsignedInt(rgb[1]) / 255.0f; - float blue = Byte.toUnsignedInt(rgb[2]) / 255.0f; - double tint = source.getTint(); - if (tint != 0.0) { - // ECMA-376 §18.8.19: apply tint via HSL luminance adjustment. - float max = Math.max(red, Math.max(green, blue)); - float min = Math.min(red, Math.min(green, blue)); - float hue = 0.0f; - float saturation = 0.0f; - float luminance = (max + min) / 2.0f; - if (max != min) { - float delta = max - min; - saturation = luminance > 0.5f - ? delta / (2.0f - max - min) - : delta / (max + min); - if (max == red) { - hue = (green - blue) / delta + (green < blue ? 6.0f : 0.0f); - } else if (max == green) { - hue = (blue - red) / delta + 2.0f; - } else { - hue = (red - green) / delta + 4.0f; - } - hue /= 6.0f; - } - if (tint < 0) { - luminance = (float) (luminance * (1.0 + tint)); - } else { - luminance = (float) (luminance * (1.0 - tint) + tint); - } - if (saturation == 0.0f) { - red = green = blue = luminance; - } else { - float q = luminance < 0.5f - ? luminance * (1.0f + saturation) - : luminance + saturation - luminance * saturation; - float p = 2.0f * luminance - q; - red = hueToRgb(p, q, hue + 1.0f / 3.0f); - green = hueToRgb(p, q, hue); - blue = hueToRgb(p, q, hue - 1.0f / 3.0f); - } - } - return new Color( - (int) Math.round(Math.max(0.0f, Math.min(1.0f, red)) * 255.0f), - (int) Math.round(Math.max(0.0f, Math.min(1.0f, green)) * 255.0f), - (int) Math.round(Math.max(0.0f, Math.min(1.0f, blue)) * 255.0f)); - } - - private static float hueToRgb(float p, float q, float hue) { - if (hue < 0.0f) { - hue += 1.0f; - } - if (hue > 1.0f) { - hue -= 1.0f; - } - if (hue < 1.0f / 6.0f) { - return p + (q - p) * 6.0f * hue; - } - if (hue < 1.0f / 2.0f) { - return q; - } - if (hue < 2.0f / 3.0f) { - return p + (q - p) * (2.0f / 3.0f - hue) * 6.0f; - } - return p; - } - - private static final class PageGeometry { - private final float layoutWidth; - private final float layoutHeight; - private final float mediaWidth; - private final float mediaHeight; - private final float marginLeft; - private final float marginRight; - private final float marginTop; - private final float marginBottom; - - private PageGeometry(float layoutWidth, float layoutHeight, float mediaWidth, float mediaHeight, - float marginLeft, float marginRight, float marginTop, float marginBottom) { - this.layoutWidth = layoutWidth; - this.layoutHeight = layoutHeight; - this.mediaWidth = mediaWidth; - this.mediaHeight = mediaHeight; - this.marginLeft = marginLeft; - this.marginRight = marginRight; - this.marginTop = marginTop; - this.marginBottom = marginBottom; - } - - float layoutWidth() { return layoutWidth; } - float layoutHeight() { return layoutHeight; } - float mediaWidth() { return mediaWidth; } - float mediaHeight() { return mediaHeight; } - float marginLeft() { return marginLeft; } - float marginTop() { return marginTop; } - - float usableWidth() { - return layoutWidth - marginLeft - marginRight; - } - - float usableHeight() { - return layoutHeight - marginTop - marginBottom; - } - - float outputScale() { - return Math.min(mediaWidth / layoutWidth, mediaHeight / layoutHeight); - } - - float outputOffsetX() { - return (mediaWidth - layoutWidth * outputScale()) / 2.0f; - } - - float outputOffsetY() { - return (mediaHeight - layoutHeight * outputScale()) / 2.0f; - } - } - - private static final class ColumnGroup { - private final int firstColumn; - private final int lastColumn; - private final float[] widths; - private final float scale; - - private ColumnGroup(int firstColumn, int lastColumn, float[] widths, float scale) { - this.firstColumn = firstColumn; - this.lastColumn = lastColumn; - this.widths = widths; - this.scale = scale; - } - - int firstColumn() { return firstColumn; } - int lastColumn() { return lastColumn; } - float[] widths() { return widths; } - float scale() { return scale; } - } - - private static final class RowRange { - private final int firstRow; - private final int lastRow; - - private RowRange(int firstRow, int lastRow) { - this.firstRow = firstRow; - this.lastRow = lastRow; - } - - int firstRow() { return firstRow; } - int lastRow() { return lastRow; } - } - - private static final class TextClip { - private final float x; - private final float width; - - private TextClip(float x, float width) { - this.x = x; - this.width = width; - } - - float x() { return x; } - float width() { return width; } - } - - private static final class PendingText { - private final Cell cell; - private final XSSFCellStyle style; - private final String value; - private final float x; - private final float y; - private final float width; - private final float height; - private final float clipX; - private final float clipWidth; - private final float padding; - - private PendingText(Cell cell, XSSFCellStyle style, String value, float x, float y, - float width, float height, float clipX, float clipWidth, float padding) { - this.cell = cell; - this.style = style; - this.value = value; - this.x = x; - this.y = y; - this.width = width; - this.height = height; - this.clipX = clipX; - this.clipWidth = clipWidth; - this.padding = padding; - } - - Cell cell() { return cell; } - XSSFCellStyle style() { return style; } - String value() { return value; } - float x() { return x; } - float y() { return y; } - float width() { return width; } - float height() { return height; } - float clipX() { return clipX; } - float clipWidth() { return clipWidth; } - float padding() { return padding; } - } - - private static final class ShapeBounds { - private final float x; - private final float top; - private final float width; - private final float height; - - private ShapeBounds(float x, float top, float width, float height) { - this.x = x; - this.top = top; - this.width = width; - this.height = height; - } - - float x() { return x; } - float top() { return top; } - float width() { return width; } - float height() { return height; } - } - - private enum BorderSide { - TOP, - BOTTOM, - LEFT, - RIGHT - } - - private static final class BorderEdge { - private final BorderStyle style; - private final XSSFColor color; - - private BorderEdge(BorderStyle style, XSSFColor color) { - this.style = style; - this.color = color; - } - - BorderStyle style() { return style; } - XSSFColor color() { return color; } - } - - private static final class FontSet { - private final PDFont latin; - private final PDFont latinBold; - private final PDFont verdana; - private final PDFont verdanaBold; - private final PDFont verdanaItalic; - private final PDFont verdanaBoldItalic; - private final PDFont calibri; - private final PDFont calibriBold; - private final PDFont palatino; - private final PDFont palatinoBold; - private final PDFont corbel; - private final PDFont corbelBold; - private final PDFont times; - private final PDFont timesBold; - private final PDFont cjk; - private final PDFont cjkBold; - private final PDFont simsun; - private final PDFont mingliu; - private final PDFont kaiti; - private final PDFont symbol; - - private FontSet( - PDFont latin, - PDFont latinBold, - PDFont verdana, - PDFont verdanaBold, - PDFont verdanaItalic, - PDFont verdanaBoldItalic, - PDFont calibri, - PDFont calibriBold, - PDFont palatino, - PDFont palatinoBold, - PDFont corbel, - PDFont corbelBold, - PDFont times, - PDFont timesBold, - PDFont cjk, - PDFont cjkBold, - PDFont simsun, - PDFont mingliu, - PDFont kaiti, - PDFont symbol) { - this.latin = latin; - this.latinBold = latinBold; - this.verdana = verdana; - this.verdanaBold = verdanaBold; - this.verdanaItalic = verdanaItalic; - this.verdanaBoldItalic = verdanaBoldItalic; - this.calibri = calibri; - this.calibriBold = calibriBold; - this.palatino = palatino; - this.palatinoBold = palatinoBold; - this.corbel = corbel; - this.corbelBold = corbelBold; - this.times = times; - this.timesBold = timesBold; - this.cjk = cjk; - this.cjkBold = cjkBold; - this.simsun = simsun; - this.mingliu = mingliu; - this.kaiti = kaiti; - this.symbol = symbol; - } - - static FontSet load(PDDocument document) throws IOException { - Map registered = new HashMap<>(); - for (RegisteredFont font : MiniPdf.registeredFonts()) { - registered.put(font.name().toLowerCase(Locale.ROOT), font.data()); - } - PDFont latin = load(document, registered, Collections.singletonList("arial"), systemFonts("arial.ttf")); - PDFont latinBold = load(document, registered, Collections.singletonList("arialbd"), systemFonts("arialbd.ttf")); - PDFont verdana = load(document, registered, Collections.singletonList("verdana"), systemFonts("verdana.ttf")); - PDFont verdanaBold = load(document, registered, Collections.singletonList("verdanab"), systemFonts("verdanab.ttf")); - PDFont verdanaItalic = load(document, registered, Collections.singletonList("verdanai"), systemFonts("verdanai.ttf")); - PDFont verdanaBoldItalic = load( - document, - registered, - Collections.singletonList("verdanaz"), - systemFonts("verdanaz.ttf")); - PDFont calibri = load(document, registered, Collections.singletonList("calibri"), systemFonts("calibri.ttf")); - PDFont calibriBold = load( - document, - registered, - Collections.singletonList("calibrib"), - systemFonts("calibrib.ttf")); - PDFont palatino = load(document, registered, Arrays.asList("palatino linotype", "pala"), systemFonts("pala.ttf")); - PDFont palatinoBold = load( - document, - registered, - Arrays.asList("palatino linotype bold", "palab"), - systemFonts("palab.ttf")); - PDFont corbel = load(document, registered, Collections.singletonList("corbel"), systemFonts("corbel.ttf")); - PDFont corbelBold = load(document, registered, Arrays.asList("corbel bold", "corbelb"), systemFonts("corbelb.ttf")); - PDFont times = load(document, registered, Collections.singletonList("times"), systemFonts("times.ttf")); - PDFont timesBold = load(document, registered, Collections.singletonList("timesbd"), systemFonts("timesbd.ttf")); - PDFont cjk = load( - document, - registered, - Arrays.asList("notosanssc", "simhei", "simsun"), - cjkSystemFonts()); - PDFont simsun = load(document, registered, Collections.singletonList("simsun"), systemFonts("simsun.ttc")); - PDFont mingliu = load(document, registered, Collections.singletonList("mingliu"), systemFonts("mingliu.ttc")); - List kaitiPaths = officeCloudFonts("STKaiti"); - kaitiPaths.addAll(systemFonts("simkai.ttf")); - PDFont kaiti = load(document, registered, Arrays.asList("stkaiti", "simkai"), kaitiPaths); - PDFont symbol = load( - document, - registered, - Arrays.asList("seguisym", "segoe ui symbol"), - systemFonts("seguisym.ttf", "unifont.ttf")); - if (latin == null) { - latin = new PDType1Font(Standard14Fonts.FontName.HELVETICA); - } - if (latinBold == null) { - latinBold = new PDType1Font(Standard14Fonts.FontName.HELVETICA_BOLD); - } - if (verdana == null) { - verdana = latin; - } - if (verdanaBold == null) { - verdanaBold = latinBold; - } - if (verdanaItalic == null) { - verdanaItalic = verdana; - } - if (verdanaBoldItalic == null) { - verdanaBoldItalic = verdanaBold; - } - if (calibri == null) { - calibri = latin; - } - if (calibriBold == null) { - calibriBold = latinBold; - } - if (times == null) { - times = latin; - } - if (timesBold == null) { - timesBold = latinBold; - } - if (palatino == null) { - palatino = times; - } - if (palatinoBold == null) { - palatinoBold = timesBold; - } - if (corbel == null) { - corbel = latin; - } - if (corbelBold == null) { - corbelBold = latinBold; - } - if (cjk == null) { - cjk = latin; - } - PDFont cjkBold = cjk; - if (simsun == null) { - simsun = cjk; - } - if (mingliu == null) { - mingliu = simsun; - } - if (kaiti == null) { - kaiti = cjk; - } - return new FontSet( - latin, - latinBold, - verdana, - verdanaBold, - verdanaItalic, - verdanaBoldItalic, - calibri, - calibriBold, - palatino, - palatinoBold, - corbel, - corbelBold, - times, - timesBold, - cjk, - cjkBold, - simsun, - mingliu, - kaiti, - symbol); - } - - PDFont resolve(String requested, String text, boolean bold, boolean italic) { - String name = requested == null ? "" : requested.toLowerCase(Locale.ROOT); - if (name.contains("kaiti") || name.contains("kai") || name.contains("楷")) { - return kaiti; - } - if (name.contains("simsun") || name.contains("宋体")) { - return simsun; - } - if (name.contains("mingliu") || name.contains("細明體") || name.contains("细明体")) { - return mingliu; - } - if (text.codePoints().anyMatch(codePoint -> codePoint > 255)) { - return bold ? cjkBold : cjk; - } - if (name.contains("verdana")) { - if (bold && italic) { - return verdanaBoldItalic; - } - if (italic) { - return verdanaItalic; - } - return bold ? verdanaBold : verdana; - } - if (name.contains("calibri")) { - return bold ? calibriBold : calibri; - } - if (name.contains("palatino")) { - return bold ? palatinoBold : palatino; - } - if (name.contains("corbel")) { - return bold ? corbelBold : corbel; - } - if (name.contains("times")) { - return bold ? timesBold : times; - } - return bold ? latinBold : latin; - } - - boolean requiresSyntheticBold(String requested, String text, boolean italic) { - return resolve(requested, text, true, italic) == resolve(requested, text, false, italic); - } - - String sanitize(PDFont font, String value) throws IOException { - StringBuilder safe = new StringBuilder(); - for (int offset = 0; offset < value.length();) { - int codePoint = value.codePointAt(offset); - offset += Character.charCount(codePoint); - if (codePoint == '\n') { - safe.append('\n'); - continue; - } - if (Character.isISOControl(codePoint)) { - safe.append(' '); - continue; - } - PDFont target = glyphFont(font, codePoint); - if (covers(target, codePoint)) { - safe.appendCodePoint(codePoint); - } else { - safe.append('?'); - } - } - return safe.toString(); - } - - /** - * Returns the font that provides a glyph for the code point: the - * primary font when possible, then a symbol-capable font, then CJK. - * Mirrors the .NET engine's per-code-point font fallback. - */ - PDFont glyphFont(PDFont primary, int codePoint) throws IOException { - if (covers(primary, codePoint)) { - return primary; - } - if (symbol != null && covers(symbol, codePoint)) { - return symbol; - } - if (covers(cjk, codePoint)) { - return cjk; - } - return primary; - } - - private boolean covers(PDFont font, int codePoint) throws IOException { - try { - font.encode(new String(Character.toChars(codePoint))); - return true; - } catch (IllegalArgumentException exception) { - return false; - } - } - - /** - * Splits a line into runs that each use a single font, selecting the - * first font in the fallback chain that covers every code point. - */ - List runs(PDFont font, String line) throws IOException { - List runs = new ArrayList<>(); - PDFont current = null; - StringBuilder currentText = new StringBuilder(); - for (int offset = 0; offset < line.length();) { - int codePoint = line.codePointAt(offset); - offset += Character.charCount(codePoint); - PDFont target = glyphFont(font, codePoint); - if (current != null && current != target) { - runs.add(new TextRun(current, currentText.toString())); - currentText.setLength(0); - } - current = target; - currentText.appendCodePoint(codePoint); - } - if (current != null) { - runs.add(new TextRun(current, currentText.toString())); - } - return runs; - } - - float textWidth(PDFont font, String value, float size) throws IOException { - float total = 0.0f; - for (TextRun run : runs(font, value)) { - total += run.font().getStringWidth(run.text()); - } - return total / 1000.0f * size; - } - - List wrap(PDFont font, String value, float size, float width, boolean enabled) - throws IOException { - List lines = new ArrayList<>(); - for (String paragraph : value.split("\\R", -1)) { - if (!enabled || textWidth(font, paragraph, size) <= width) { - lines.add(paragraph); - continue; - } - String remaining = paragraph; - while (!remaining.isEmpty()) { - int fit = 0; - for (int offset = 0; offset < remaining.length();) { - int next = offset + Character.charCount(remaining.codePointAt(offset)); - if (offset > 0 && textWidth(font, remaining.substring(0, next), size) > width) { - break; - } - fit = next; - offset = next; - } - if (fit >= remaining.length()) { - lines.add(remaining); - break; - } - if (remaining.charAt(fit) == ' ') { - lines.add(remaining.substring(0, fit)); - remaining = remaining.substring(fit + 1); - continue; - } - int breakAt = fit; - for (int index = fit - 1; index >= fit / 2; index--) { - if (remaining.charAt(index) == ' ') { - breakAt = index; - break; - } - } - lines.add(remaining.substring(0, breakAt)); - remaining = remaining.substring(breakAt + (breakAt == fit ? 0 : 1)); - } - } - return lines; - } - - private static final class TextRun { - private final PDFont font; - private final String text; - - private TextRun(PDFont font, String text) { - this.font = font; - this.text = text; - } - - PDFont font() { return font; } - String text() { return text; } - } - - private static PDFont load( - PDDocument document, - Map registered, - List names, - List paths) throws IOException { - for (Map.Entry font : registered.entrySet()) { - if (names.stream().anyMatch(font.getKey()::contains)) { - return PDType0Font.load( - document, - new ByteArrayInputStream(font.getValue()), - FontEmbeddingPolicy.shouldSubset()); - } - } - for (Path path : paths) { - if (Files.isRegularFile(path)) { - try { - String fileName = path.getFileName().toString().toLowerCase(Locale.ROOT); - PDFont loaded = fileName.endsWith(".ttc") || fileName.endsWith(".otc") - ? loadCollectionFont(document, path) - : PDType0Font.load( - document, - Files.newInputStream(path), - FontEmbeddingPolicy.shouldSubset()); - if (loaded != null) { - return loaded; - } - } catch (IOException | RuntimeException ignored) { - } - } - } - return null; - } - - private static PDFont loadCollectionFont(PDDocument document, Path path) throws IOException { - PDFont[] loaded = new PDFont[1]; - try (TrueTypeCollection collection = new TrueTypeCollection(path.toFile())) { - collection.processAllFonts(font -> { - if (loaded[0] == null) { - try { - loaded[0] = PDType0Font.load( - document, - font, - FontEmbeddingPolicy.shouldSubset()); - } catch (IOException | RuntimeException ignored) { - } - } - }); - } - return loaded[0]; - } - - private static List cjkSystemFonts() { - if (!FontEmbeddingPolicy.shouldSubset()) { - return systemFonts( - "wqy-microhei.ttc", - "unifont.ttf", - "NotoSansSC-VF.ttf", - "NotoSansCJK-Regular.ttc", - "simhei.ttf", - "simsun.ttc"); - } - return systemFonts( - "NotoSansSC-VF.ttf", - "wqy-microhei.ttc", - "NotoSansCJK-Regular.ttc", - "simhei.ttf", - "simsun.ttc"); - } - - private static List systemFonts(String... names) { - List paths = new ArrayList<>(); - String windows = System.getenv("WINDIR"); - if (windows != null) { - for (String name : names) { - paths.add(Paths.get(windows, "Fonts", name)); - } - } - for (String name : names) { - paths.add(Paths.get("/usr/share/fonts/truetype/unifont", name)); - paths.add(Paths.get("/usr/share/fonts/truetype/noto", name)); - paths.add(Paths.get("/usr/share/fonts/truetype/wqy", name)); - paths.add(Paths.get("/usr/share/fonts/opentype/noto", name)); - paths.add(Paths.get("/System/Library/Fonts", name)); - paths.add(Paths.get("/System/Library/Fonts/Supplemental", name)); - } - return paths; - } - - private static List officeCloudFonts(String family) { - List paths = new ArrayList<>(); - String localAppData = System.getenv("LOCALAPPDATA"); - if (localAppData == null) { - return paths; - } - Path cacheRoot = Paths.get(localAppData, "Microsoft", "FontCache"); - if (!Files.isDirectory(cacheRoot)) { - return paths; - } - try (Stream candidates = Files.walk(cacheRoot, 4)) { - candidates - .filter(Files::isRegularFile) - .filter(path -> path.getFileName().toString().toLowerCase(Locale.ROOT).endsWith(".ttf")) - .filter(path -> path.getParent() != null - && path.getParent().getFileName().toString().equalsIgnoreCase(family)) - .sorted() - .forEach(paths::add); - } catch (IOException ignored) { - } - return paths; - } - } -} \ No newline at end of file diff --git a/minipdf-java/minipdf/src/main/java/io/github/minisoftware/minipdf/internal/xlsx/XlsxConverter.java b/minipdf-java/minipdf/src/main/java/io/github/minisoftware/minipdf/internal/xlsx/XlsxConverter.java deleted file mode 100644 index e17554d3..00000000 --- a/minipdf-java/minipdf/src/main/java/io/github/minisoftware/minipdf/internal/xlsx/XlsxConverter.java +++ /dev/null @@ -1,126 +0,0 @@ -package io.github.minisoftware.minipdf.internal.xlsx; - -import io.github.minisoftware.minipdf.ConversionOptions; -import io.github.minisoftware.minipdf.MiniPdfException; -import io.github.minisoftware.minipdf.internal.OoxmlPackage; -import io.github.minisoftware.minipdf.internal.SecureXml; -import io.github.minisoftware.minipdf.internal.SimplePdfTextRenderer; - -import javax.xml.stream.XMLStreamConstants; -import javax.xml.stream.XMLStreamException; -import javax.xml.stream.XMLStreamReader; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Comparator; -import java.util.List; -import java.util.stream.Collectors; - -public final class XlsxConverter { - private XlsxConverter() { - } - - public static byte[] convert(byte[] input, ConversionOptions options) throws MiniPdfException { - OoxmlPackage workbook = OoxmlPackage.open(input); - if (workbook.entry("[Content_Types].xml").isPresent() - && workbook.entry("xl/workbook.xml").isPresent()) { - return PoiXlsxRenderer.render(input, options); - } - byte[] sharedStringsXml = workbook.entry("xl/sharedStrings.xml").orElse(null); - List sharedStrings = sharedStringsXml == null - ? Collections.emptyList() - : readSharedStrings(sharedStringsXml); - List worksheetNames = workbook.entryNames().stream() - .filter(name -> name.startsWith("xl/worksheets/") && name.endsWith(".xml")) - .sorted(Comparator.naturalOrder()) - .collect(Collectors.toList()); - if (worksheetNames.isEmpty()) { - throw new MiniPdfException( - MiniPdfException.Kind.INVALID_INPUT, - "XLSX package does not contain a worksheet"); - } - - List lines = new ArrayList<>(); - for (String worksheetName : worksheetNames) { - byte[] worksheet = workbook.entry(worksheetName).orElseThrow(() -> new MiniPdfException( - MiniPdfException.Kind.INVALID_INPUT, - "XLSX worksheet part is missing: " + worksheetName)); - lines.addAll(readWorksheet(worksheet, sharedStrings)); - } - return SimplePdfTextRenderer.render(lines, options); - } - - private static List readSharedStrings(byte[] xml) throws MiniPdfException { - List strings = new ArrayList<>(); - StringBuilder value = null; - try { - XMLStreamReader reader = SecureXml.reader(xml); - while (reader.hasNext()) { - int event = reader.next(); - if (event == XMLStreamConstants.START_ELEMENT && reader.getLocalName().equals("si")) { - value = new StringBuilder(); - } else if (event == XMLStreamConstants.START_ELEMENT - && reader.getLocalName().equals("t") && value != null) { - value.append(reader.getElementText()); - } else if (event == XMLStreamConstants.END_ELEMENT - && reader.getLocalName().equals("si") && value != null) { - strings.add(value.toString()); - value = null; - } - } - reader.close(); - return strings; - } catch (XMLStreamException exception) { - throw SecureXml.parseError(exception); - } - } - - private static List readWorksheet(byte[] xml, List sharedStrings) throws MiniPdfException { - List lines = new ArrayList<>(); - List row = null; - String cellType = null; - String cellValue = null; - try { - XMLStreamReader reader = SecureXml.reader(xml); - while (reader.hasNext()) { - int event = reader.next(); - if (event == XMLStreamConstants.START_ELEMENT && reader.getLocalName().equals("row")) { - row = new ArrayList<>(); - } else if (event == XMLStreamConstants.START_ELEMENT && reader.getLocalName().equals("c")) { - cellType = reader.getAttributeValue(null, "t"); - cellValue = ""; - } else if (event == XMLStreamConstants.START_ELEMENT - && (reader.getLocalName().equals("v") || reader.getLocalName().equals("t")) - && row != null) { - cellValue = reader.getElementText(); - } else if (event == XMLStreamConstants.END_ELEMENT - && reader.getLocalName().equals("c") && row != null) { - row.add(resolveCellValue(cellType, cellValue, sharedStrings)); - } else if (event == XMLStreamConstants.END_ELEMENT - && reader.getLocalName().equals("row") && row != null) { - lines.add(String.join(" ", row)); - row = null; - } - } - reader.close(); - return lines; - } catch (XMLStreamException exception) { - throw SecureXml.parseError(exception); - } - } - - private static String resolveCellValue(String type, String value, List sharedStrings) { - if ("s".equals(type)) { - try { - int index = Integer.parseInt(value); - return index >= 0 && index < sharedStrings.size() ? sharedStrings.get(index) : value; - } catch (NumberFormatException ignored) { - return value; - } - } - if ("b".equals(type)) { - return "1".equals(value) ? "TRUE" : "FALSE"; - } - return value == null ? "" : value; - } - -} \ No newline at end of file diff --git a/minipdf-java/mvnw b/minipdf-java/mvnw deleted file mode 100755 index bd8896bf..00000000 --- a/minipdf-java/mvnw +++ /dev/null @@ -1,295 +0,0 @@ -#!/bin/sh -# ---------------------------------------------------------------------------- -# Licensed to the Apache Software Foundation (ASF) under one -# or more contributor license agreements. See the NOTICE file -# distributed with this work for additional information -# regarding copyright ownership. The ASF licenses this file -# to you under the Apache License, Version 2.0 (the -# "License"); you may not use this file except in compliance -# with the License. You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, -# software distributed under the License is distributed on an -# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -# KIND, either express or implied. See the License for the -# specific language governing permissions and limitations -# under the License. -# ---------------------------------------------------------------------------- - -# ---------------------------------------------------------------------------- -# Apache Maven Wrapper startup batch script, version 3.3.4 -# -# Optional ENV vars -# ----------------- -# JAVA_HOME - location of a JDK home dir, required when download maven via java source -# MVNW_REPOURL - repo url base for downloading maven distribution -# MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven -# MVNW_VERBOSE - true: enable verbose log; debug: trace the mvnw script; others: silence the output -# ---------------------------------------------------------------------------- - -set -euf -[ "${MVNW_VERBOSE-}" != debug ] || set -x - -# OS specific support. -native_path() { printf %s\\n "$1"; } -case "$(uname)" in -CYGWIN* | MINGW*) - [ -z "${JAVA_HOME-}" ] || JAVA_HOME="$(cygpath --unix "$JAVA_HOME")" - native_path() { cygpath --path --windows "$1"; } - ;; -esac - -# set JAVACMD and JAVACCMD -set_java_home() { - # For Cygwin and MinGW, ensure paths are in Unix format before anything is touched - if [ -n "${JAVA_HOME-}" ]; then - if [ -x "$JAVA_HOME/jre/sh/java" ]; then - # IBM's JDK on AIX uses strange locations for the executables - JAVACMD="$JAVA_HOME/jre/sh/java" - JAVACCMD="$JAVA_HOME/jre/sh/javac" - else - JAVACMD="$JAVA_HOME/bin/java" - JAVACCMD="$JAVA_HOME/bin/javac" - - if [ ! -x "$JAVACMD" ] || [ ! -x "$JAVACCMD" ]; then - echo "The JAVA_HOME environment variable is not defined correctly, so mvnw cannot run." >&2 - echo "JAVA_HOME is set to \"$JAVA_HOME\", but \"\$JAVA_HOME/bin/java\" or \"\$JAVA_HOME/bin/javac\" does not exist." >&2 - return 1 - fi - fi - else - JAVACMD="$( - 'set' +e - 'unset' -f command 2>/dev/null - 'command' -v java - )" || : - JAVACCMD="$( - 'set' +e - 'unset' -f command 2>/dev/null - 'command' -v javac - )" || : - - if [ ! -x "${JAVACMD-}" ] || [ ! -x "${JAVACCMD-}" ]; then - echo "The java/javac command does not exist in PATH nor is JAVA_HOME set, so mvnw cannot run." >&2 - return 1 - fi - fi -} - -# hash string like Java String::hashCode -hash_string() { - str="${1:-}" h=0 - while [ -n "$str" ]; do - char="${str%"${str#?}"}" - h=$(((h * 31 + $(LC_CTYPE=C printf %d "'$char")) % 4294967296)) - str="${str#?}" - done - printf %x\\n $h -} - -verbose() { :; } -[ "${MVNW_VERBOSE-}" != true ] || verbose() { printf %s\\n "${1-}"; } - -die() { - printf %s\\n "$1" >&2 - exit 1 -} - -trim() { - # MWRAPPER-139: - # Trims trailing and leading whitespace, carriage returns, tabs, and linefeeds. - # Needed for removing poorly interpreted newline sequences when running in more - # exotic environments such as mingw bash on Windows. - printf "%s" "${1}" | tr -d '[:space:]' -} - -scriptDir="$(dirname "$0")" -scriptName="$(basename "$0")" - -# parse distributionUrl and optional distributionSha256Sum, requires .mvn/wrapper/maven-wrapper.properties -while IFS="=" read -r key value; do - case "${key-}" in - distributionUrl) distributionUrl=$(trim "${value-}") ;; - distributionSha256Sum) distributionSha256Sum=$(trim "${value-}") ;; - esac -done <"$scriptDir/.mvn/wrapper/maven-wrapper.properties" -[ -n "${distributionUrl-}" ] || die "cannot read distributionUrl property in $scriptDir/.mvn/wrapper/maven-wrapper.properties" - -case "${distributionUrl##*/}" in -maven-mvnd-*bin.*) - MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/ - case "${PROCESSOR_ARCHITECTURE-}${PROCESSOR_ARCHITEW6432-}:$(uname -a)" in - *AMD64:CYGWIN* | *AMD64:MINGW*) distributionPlatform=windows-amd64 ;; - :Darwin*x86_64) distributionPlatform=darwin-amd64 ;; - :Darwin*arm64) distributionPlatform=darwin-aarch64 ;; - :Linux*x86_64*) distributionPlatform=linux-amd64 ;; - *) - echo "Cannot detect native platform for mvnd on $(uname)-$(uname -m), use pure java version" >&2 - distributionPlatform=linux-amd64 - ;; - esac - distributionUrl="${distributionUrl%-bin.*}-$distributionPlatform.zip" - ;; -maven-mvnd-*) MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/ ;; -*) MVN_CMD="mvn${scriptName#mvnw}" _MVNW_REPO_PATTERN=/org/apache/maven/ ;; -esac - -# apply MVNW_REPOURL and calculate MAVEN_HOME -# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-,maven-mvnd--}/ -[ -z "${MVNW_REPOURL-}" ] || distributionUrl="$MVNW_REPOURL$_MVNW_REPO_PATTERN${distributionUrl#*"$_MVNW_REPO_PATTERN"}" -distributionUrlName="${distributionUrl##*/}" -distributionUrlNameMain="${distributionUrlName%.*}" -distributionUrlNameMain="${distributionUrlNameMain%-bin}" -MAVEN_USER_HOME="${MAVEN_USER_HOME:-${HOME}/.m2}" -MAVEN_HOME="${MAVEN_USER_HOME}/wrapper/dists/${distributionUrlNameMain-}/$(hash_string "$distributionUrl")" - -exec_maven() { - unset MVNW_VERBOSE MVNW_USERNAME MVNW_PASSWORD MVNW_REPOURL || : - exec "$MAVEN_HOME/bin/$MVN_CMD" "$@" || die "cannot exec $MAVEN_HOME/bin/$MVN_CMD" -} - -if [ -d "$MAVEN_HOME" ]; then - verbose "found existing MAVEN_HOME at $MAVEN_HOME" - exec_maven "$@" -fi - -case "${distributionUrl-}" in -*?-bin.zip | *?maven-mvnd-?*-?*.zip) ;; -*) die "distributionUrl is not valid, must match *-bin.zip or maven-mvnd-*.zip, but found '${distributionUrl-}'" ;; -esac - -# prepare tmp dir -if TMP_DOWNLOAD_DIR="$(mktemp -d)" && [ -d "$TMP_DOWNLOAD_DIR" ]; then - clean() { rm -rf -- "$TMP_DOWNLOAD_DIR"; } - trap clean HUP INT TERM EXIT -else - die "cannot create temp dir" -fi - -mkdir -p -- "${MAVEN_HOME%/*}" - -# Download and Install Apache Maven -verbose "Couldn't find MAVEN_HOME, downloading and installing it ..." -verbose "Downloading from: $distributionUrl" -verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName" - -# select .zip or .tar.gz -if ! command -v unzip >/dev/null; then - distributionUrl="${distributionUrl%.zip}.tar.gz" - distributionUrlName="${distributionUrl##*/}" -fi - -# verbose opt -__MVNW_QUIET_WGET=--quiet __MVNW_QUIET_CURL=--silent __MVNW_QUIET_UNZIP=-q __MVNW_QUIET_TAR='' -[ "${MVNW_VERBOSE-}" != true ] || __MVNW_QUIET_WGET='' __MVNW_QUIET_CURL='' __MVNW_QUIET_UNZIP='' __MVNW_QUIET_TAR=v - -# normalize http auth -case "${MVNW_PASSWORD:+has-password}" in -'') MVNW_USERNAME='' MVNW_PASSWORD='' ;; -has-password) [ -n "${MVNW_USERNAME-}" ] || MVNW_USERNAME='' MVNW_PASSWORD='' ;; -esac - -if [ -z "${MVNW_USERNAME-}" ] && command -v wget >/dev/null; then - verbose "Found wget ... using wget" - wget ${__MVNW_QUIET_WGET:+"$__MVNW_QUIET_WGET"} "$distributionUrl" -O "$TMP_DOWNLOAD_DIR/$distributionUrlName" || die "wget: Failed to fetch $distributionUrl" -elif [ -z "${MVNW_USERNAME-}" ] && command -v curl >/dev/null; then - verbose "Found curl ... using curl" - curl ${__MVNW_QUIET_CURL:+"$__MVNW_QUIET_CURL"} -f -L -o "$TMP_DOWNLOAD_DIR/$distributionUrlName" "$distributionUrl" || die "curl: Failed to fetch $distributionUrl" -elif set_java_home; then - verbose "Falling back to use Java to download" - javaSource="$TMP_DOWNLOAD_DIR/Downloader.java" - targetZip="$TMP_DOWNLOAD_DIR/$distributionUrlName" - cat >"$javaSource" <<-END - public class Downloader extends java.net.Authenticator - { - protected java.net.PasswordAuthentication getPasswordAuthentication() - { - return new java.net.PasswordAuthentication( System.getenv( "MVNW_USERNAME" ), System.getenv( "MVNW_PASSWORD" ).toCharArray() ); - } - public static void main( String[] args ) throws Exception - { - setDefault( new Downloader() ); - java.nio.file.Files.copy( java.net.URI.create( args[0] ).toURL().openStream(), java.nio.file.Paths.get( args[1] ).toAbsolutePath().normalize() ); - } - } - END - # For Cygwin/MinGW, switch paths to Windows format before running javac and java - verbose " - Compiling Downloader.java ..." - "$(native_path "$JAVACCMD")" "$(native_path "$javaSource")" || die "Failed to compile Downloader.java" - verbose " - Running Downloader.java ..." - "$(native_path "$JAVACMD")" -cp "$(native_path "$TMP_DOWNLOAD_DIR")" Downloader "$distributionUrl" "$(native_path "$targetZip")" -fi - -# If specified, validate the SHA-256 sum of the Maven distribution zip file -if [ -n "${distributionSha256Sum-}" ]; then - distributionSha256Result=false - if [ "$MVN_CMD" = mvnd.sh ]; then - echo "Checksum validation is not supported for maven-mvnd." >&2 - echo "Please disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2 - exit 1 - elif command -v sha256sum >/dev/null; then - if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | sha256sum -c - >/dev/null 2>&1; then - distributionSha256Result=true - fi - elif command -v shasum >/dev/null; then - if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | shasum -a 256 -c >/dev/null 2>&1; then - distributionSha256Result=true - fi - else - echo "Checksum validation was requested but neither 'sha256sum' or 'shasum' are available." >&2 - echo "Please install either command, or disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2 - exit 1 - fi - if [ $distributionSha256Result = false ]; then - echo "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised." >&2 - echo "If you updated your Maven version, you need to update the specified distributionSha256Sum property." >&2 - exit 1 - fi -fi - -# unzip and move -if command -v unzip >/dev/null; then - unzip ${__MVNW_QUIET_UNZIP:+"$__MVNW_QUIET_UNZIP"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -d "$TMP_DOWNLOAD_DIR" || die "failed to unzip" -else - tar xzf${__MVNW_QUIET_TAR:+"$__MVNW_QUIET_TAR"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -C "$TMP_DOWNLOAD_DIR" || die "failed to untar" -fi - -# Find the actual extracted directory name (handles snapshots where filename != directory name) -actualDistributionDir="" - -# First try the expected directory name (for regular distributions) -if [ -d "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain" ]; then - if [ -f "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain/bin/$MVN_CMD" ]; then - actualDistributionDir="$distributionUrlNameMain" - fi -fi - -# If not found, search for any directory with the Maven executable (for snapshots) -if [ -z "$actualDistributionDir" ]; then - # enable globbing to iterate over items - set +f - for dir in "$TMP_DOWNLOAD_DIR"/*; do - if [ -d "$dir" ]; then - if [ -f "$dir/bin/$MVN_CMD" ]; then - actualDistributionDir="$(basename "$dir")" - break - fi - fi - done - set -f -fi - -if [ -z "$actualDistributionDir" ]; then - verbose "Contents of $TMP_DOWNLOAD_DIR:" - verbose "$(ls -la "$TMP_DOWNLOAD_DIR")" - die "Could not find Maven distribution directory in extracted archive" -fi - -verbose "Found extracted Maven distribution directory: $actualDistributionDir" -printf %s\\n "$distributionUrl" >"$TMP_DOWNLOAD_DIR/$actualDistributionDir/mvnw.url" -mv -- "$TMP_DOWNLOAD_DIR/$actualDistributionDir" "$MAVEN_HOME" || [ -d "$MAVEN_HOME" ] || die "fail to move MAVEN_HOME" - -clean || : -exec_maven "$@" diff --git a/minipdf-java/mvnw.cmd b/minipdf-java/mvnw.cmd deleted file mode 100644 index 92450f93..00000000 --- a/minipdf-java/mvnw.cmd +++ /dev/null @@ -1,189 +0,0 @@ -<# : batch portion -@REM ---------------------------------------------------------------------------- -@REM Licensed to the Apache Software Foundation (ASF) under one -@REM or more contributor license agreements. See the NOTICE file -@REM distributed with this work for additional information -@REM regarding copyright ownership. The ASF licenses this file -@REM to you under the Apache License, Version 2.0 (the -@REM "License"); you may not use this file except in compliance -@REM with the License. You may obtain a copy of the License at -@REM -@REM http://www.apache.org/licenses/LICENSE-2.0 -@REM -@REM Unless required by applicable law or agreed to in writing, -@REM software distributed under the License is distributed on an -@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -@REM KIND, either express or implied. See the License for the -@REM specific language governing permissions and limitations -@REM under the License. -@REM ---------------------------------------------------------------------------- - -@REM ---------------------------------------------------------------------------- -@REM Apache Maven Wrapper startup batch script, version 3.3.4 -@REM -@REM Optional ENV vars -@REM MVNW_REPOURL - repo url base for downloading maven distribution -@REM MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven -@REM MVNW_VERBOSE - true: enable verbose log; others: silence the output -@REM ---------------------------------------------------------------------------- - -@IF "%__MVNW_ARG0_NAME__%"=="" (SET __MVNW_ARG0_NAME__=%~nx0) -@SET __MVNW_CMD__= -@SET __MVNW_ERROR__= -@SET __MVNW_PSMODULEP_SAVE=%PSModulePath% -@SET PSModulePath= -@FOR /F "usebackq tokens=1* delims==" %%A IN (`powershell -noprofile "& {$scriptDir='%~dp0'; $script='%__MVNW_ARG0_NAME__%'; icm -ScriptBlock ([Scriptblock]::Create((Get-Content -Raw '%~f0'))) -NoNewScope}"`) DO @( - IF "%%A"=="MVN_CMD" (set __MVNW_CMD__=%%B) ELSE IF "%%B"=="" (echo %%A) ELSE (echo %%A=%%B) -) -@SET PSModulePath=%__MVNW_PSMODULEP_SAVE% -@SET __MVNW_PSMODULEP_SAVE= -@SET __MVNW_ARG0_NAME__= -@SET MVNW_USERNAME= -@SET MVNW_PASSWORD= -@IF NOT "%__MVNW_CMD__%"=="" ("%__MVNW_CMD__%" %*) -@echo Cannot start maven from wrapper >&2 && exit /b 1 -@GOTO :EOF -: end batch / begin powershell #> - -$ErrorActionPreference = "Stop" -if ($env:MVNW_VERBOSE -eq "true") { - $VerbosePreference = "Continue" -} - -# calculate distributionUrl, requires .mvn/wrapper/maven-wrapper.properties -$distributionUrl = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionUrl -if (!$distributionUrl) { - Write-Error "cannot read distributionUrl property in $scriptDir/.mvn/wrapper/maven-wrapper.properties" -} - -switch -wildcard -casesensitive ( $($distributionUrl -replace '^.*/','') ) { - "maven-mvnd-*" { - $USE_MVND = $true - $distributionUrl = $distributionUrl -replace '-bin\.[^.]*$',"-windows-amd64.zip" - $MVN_CMD = "mvnd.cmd" - break - } - default { - $USE_MVND = $false - $MVN_CMD = $script -replace '^mvnw','mvn' - break - } -} - -# apply MVNW_REPOURL and calculate MAVEN_HOME -# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-,maven-mvnd--}/ -if ($env:MVNW_REPOURL) { - $MVNW_REPO_PATTERN = if ($USE_MVND -eq $False) { "/org/apache/maven/" } else { "/maven/mvnd/" } - $distributionUrl = "$env:MVNW_REPOURL$MVNW_REPO_PATTERN$($distributionUrl -replace "^.*$MVNW_REPO_PATTERN",'')" -} -$distributionUrlName = $distributionUrl -replace '^.*/','' -$distributionUrlNameMain = $distributionUrlName -replace '\.[^.]*$','' -replace '-bin$','' - -$MAVEN_M2_PATH = "$HOME/.m2" -if ($env:MAVEN_USER_HOME) { - $MAVEN_M2_PATH = "$env:MAVEN_USER_HOME" -} - -if (-not (Test-Path -Path $MAVEN_M2_PATH)) { - New-Item -Path $MAVEN_M2_PATH -ItemType Directory | Out-Null -} - -$MAVEN_WRAPPER_DISTS = $null -if ((Get-Item $MAVEN_M2_PATH).Target[0] -eq $null) { - $MAVEN_WRAPPER_DISTS = "$MAVEN_M2_PATH/wrapper/dists" -} else { - $MAVEN_WRAPPER_DISTS = (Get-Item $MAVEN_M2_PATH).Target[0] + "/wrapper/dists" -} - -$MAVEN_HOME_PARENT = "$MAVEN_WRAPPER_DISTS/$distributionUrlNameMain" -$MAVEN_HOME_NAME = ([System.Security.Cryptography.SHA256]::Create().ComputeHash([byte[]][char[]]$distributionUrl) | ForEach-Object {$_.ToString("x2")}) -join '' -$MAVEN_HOME = "$MAVEN_HOME_PARENT/$MAVEN_HOME_NAME" - -if (Test-Path -Path "$MAVEN_HOME" -PathType Container) { - Write-Verbose "found existing MAVEN_HOME at $MAVEN_HOME" - Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD" - exit $? -} - -if (! $distributionUrlNameMain -or ($distributionUrlName -eq $distributionUrlNameMain)) { - Write-Error "distributionUrl is not valid, must end with *-bin.zip, but found $distributionUrl" -} - -# prepare tmp dir -$TMP_DOWNLOAD_DIR_HOLDER = New-TemporaryFile -$TMP_DOWNLOAD_DIR = New-Item -Itemtype Directory -Path "$TMP_DOWNLOAD_DIR_HOLDER.dir" -$TMP_DOWNLOAD_DIR_HOLDER.Delete() | Out-Null -trap { - if ($TMP_DOWNLOAD_DIR.Exists) { - try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null } - catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" } - } -} - -New-Item -Itemtype Directory -Path "$MAVEN_HOME_PARENT" -Force | Out-Null - -# Download and Install Apache Maven -Write-Verbose "Couldn't find MAVEN_HOME, downloading and installing it ..." -Write-Verbose "Downloading from: $distributionUrl" -Write-Verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName" - -$webclient = New-Object System.Net.WebClient -if ($env:MVNW_USERNAME -and $env:MVNW_PASSWORD) { - $webclient.Credentials = New-Object System.Net.NetworkCredential($env:MVNW_USERNAME, $env:MVNW_PASSWORD) -} -[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 -$webclient.DownloadFile($distributionUrl, "$TMP_DOWNLOAD_DIR/$distributionUrlName") | Out-Null - -# If specified, validate the SHA-256 sum of the Maven distribution zip file -$distributionSha256Sum = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionSha256Sum -if ($distributionSha256Sum) { - if ($USE_MVND) { - Write-Error "Checksum validation is not supported for maven-mvnd. `nPlease disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." - } - Import-Module $PSHOME\Modules\Microsoft.PowerShell.Utility -Function Get-FileHash - if ((Get-FileHash "$TMP_DOWNLOAD_DIR/$distributionUrlName" -Algorithm SHA256).Hash.ToLower() -ne $distributionSha256Sum) { - Write-Error "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised. If you updated your Maven version, you need to update the specified distributionSha256Sum property." - } -} - -# unzip and move -Expand-Archive "$TMP_DOWNLOAD_DIR/$distributionUrlName" -DestinationPath "$TMP_DOWNLOAD_DIR" | Out-Null - -# Find the actual extracted directory name (handles snapshots where filename != directory name) -$actualDistributionDir = "" - -# First try the expected directory name (for regular distributions) -$expectedPath = Join-Path "$TMP_DOWNLOAD_DIR" "$distributionUrlNameMain" -$expectedMvnPath = Join-Path "$expectedPath" "bin/$MVN_CMD" -if ((Test-Path -Path $expectedPath -PathType Container) -and (Test-Path -Path $expectedMvnPath -PathType Leaf)) { - $actualDistributionDir = $distributionUrlNameMain -} - -# If not found, search for any directory with the Maven executable (for snapshots) -if (!$actualDistributionDir) { - Get-ChildItem -Path "$TMP_DOWNLOAD_DIR" -Directory | ForEach-Object { - $testPath = Join-Path $_.FullName "bin/$MVN_CMD" - if (Test-Path -Path $testPath -PathType Leaf) { - $actualDistributionDir = $_.Name - } - } -} - -if (!$actualDistributionDir) { - Write-Error "Could not find Maven distribution directory in extracted archive" -} - -Write-Verbose "Found extracted Maven distribution directory: $actualDistributionDir" -Rename-Item -Path "$TMP_DOWNLOAD_DIR/$actualDistributionDir" -NewName $MAVEN_HOME_NAME | Out-Null -try { - Move-Item -Path "$TMP_DOWNLOAD_DIR/$MAVEN_HOME_NAME" -Destination $MAVEN_HOME_PARENT | Out-Null -} catch { - if (! (Test-Path -Path "$MAVEN_HOME" -PathType Container)) { - Write-Error "fail to move MAVEN_HOME" - } -} finally { - try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null } - catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" } -} - -Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD" diff --git a/minipdf-java/pom.xml b/minipdf-java/pom.xml deleted file mode 100644 index 04ee835b..00000000 --- a/minipdf-java/pom.xml +++ /dev/null @@ -1,165 +0,0 @@ - - - 4.0.0 - - io.github.mini-software - minipdf-java-parent - 0.4.1 - pom - - MiniPdf for Java - Native Java Office-to-PDF conversion. - https://github.com/mini-software/MiniPdf - - - - Apache License, Version 2.0 - https://www.apache.org/licenses/LICENSE-2.0.txt - repo - - - - - - shps951023 - Wei Lin - https://github.com/shps951023 - MiniSoftware - https://github.com/mini-software - - - - - scm:git:https://github.com/mini-software/MiniPdf.git - scm:git:ssh://git@github.com/mini-software/MiniPdf.git - https://github.com/mini-software/MiniPdf - HEAD - - - - minipdf - minipdf-cli - minipdf-tests - - - - UTF-8 - 8 - 3.0.3 - 3.0.8 - 5.4.1 - 0.11.0 - 3.2.8 - 3.11.2 - 3.3.1 - - - - - - org.apache.pdfbox - pdfbox - ${pdfbox.version} - - - de.rototor.pdfbox - graphics2d - ${pdfbox-graphics2d.version} - - - org.apache.poi - poi-ooxml - ${poi.version} - - - org.apache.poi - poi-scratchpad - ${poi.version} - - - - - - - - - org.apache.maven.plugins - maven-compiler-plugin - 3.14.1 - - - org.apache.maven.plugins - maven-surefire-plugin - 3.5.4 - - false - - - - - - - - - release - - - - org.apache.maven.plugins - maven-source-plugin - ${maven-source-plugin.version} - - - attach-sources - - jar-no-fork - - - - - - org.apache.maven.plugins - maven-javadoc-plugin - ${maven-javadoc-plugin.version} - - - attach-javadocs - - jar - - - - - - org.apache.maven.plugins - maven-gpg-plugin - ${maven-gpg-plugin.version} - - - sign-artifacts - verify - - sign - - - - - - org.sonatype.central - central-publishing-maven-plugin - ${central-publishing-maven-plugin.version} - true - - central - true - published - 3600 - - - - - - - \ No newline at end of file diff --git a/minipdf-node/Cargo.lock b/minipdf-node/Cargo.lock deleted file mode 100644 index f44fab1d..00000000 --- a/minipdf-node/Cargo.lock +++ /dev/null @@ -1,920 +0,0 @@ -# This file is automatically @generated by Cargo. -# It is not intended for manual editing. -version = 4 - -[[package]] -name = "adler2" -version = "2.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" - -[[package]] -name = "aho-corasick" -version = "1.1.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba" -dependencies = [ - "memchr", -] - -[[package]] -name = "android_system_properties" -version = "0.1.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ae221649c9976a6f6c56ae1facf410f3ddb33cc661c4b7b61020a912d4237fbc" -dependencies = [ - "libc", -] - -[[package]] -name = "arbitrary" -version = "1.4.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c3d036a3c4ab069c7b410a2ce876bd74808d2d0888a82667669f8e783a898bf1" -dependencies = [ - "derive_arbitrary", -] - -[[package]] -name = "arrayvec" -version = "0.7.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d3fb67a6e08acf24fdeccbac2cb6ac4305825bd1f117462e0e6f2f193345ad56" - -[[package]] -name = "autocfg" -version = "1.5.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" - -[[package]] -name = "bitflags" -version = "2.13.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b588b76d00fde79687d7646a9b5bdf3cc0f655e0bbd080335a95d7e96f3587da" - -[[package]] -name = "bumpalo" -version = "3.20.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649" - -[[package]] -name = "bytemuck" -version = "1.25.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "95832e849adfb21180ccb6826a99da14e5d266ae5c2e668e1602cf234f153797" -dependencies = [ - "bytemuck_derive", -] - -[[package]] -name = "bytemuck_derive" -version = "1.12.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fc0e56a716f1e132ff6bf4bdac1c944a3fcdc1cae65f70a4a2a1ac3b401d2d1f" -dependencies = [ - "proc-macro2", - "quote", - "syn 3.0.4", -] - -[[package]] -name = "byteorder-lite" -version = "0.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8f1fe948ff07f4bd06c30984e69f5b4899c516a3ef74f34df92a2df2ab535495" - -[[package]] -name = "cc" -version = "1.4.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0ad534f4357a5264cce5019c989cf66a4f0dc4e0d1b1d15f8aacec0ff7360273" -dependencies = [ - "find-msvc-tools", - "shlex", -] - -[[package]] -name = "cfg-if" -version = "1.0.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801" - -[[package]] -name = "chrono" -version = "0.4.45" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1aa79e62e7697b8e29b513a68abacf485adcd1fe8284a4316c5ae868e6633327" -dependencies = [ - "iana-time-zone", - "num-traits", - "windows-link", -] - -[[package]] -name = "convert_case" -version = "0.6.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ec182b0ca2f35d8fc196cf3404988fd8b8c739a4d270ff118a398feb0cbec1ca" -dependencies = [ - "unicode-segmentation", -] - -[[package]] -name = "core-foundation-sys" -version = "0.8.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" - -[[package]] -name = "core_maths" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "77745e017f5edba1a9c1d854f6f3a52dac8a12dd5af5d2f54aecf61e43d80d30" -dependencies = [ - "libm", -] - -[[package]] -name = "crc32fast" -version = "1.5.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8498c871161e1742aaa9d52551b2d6ebdd4c3d45a3be423e3728f33b955be550" -dependencies = [ - "cfg-if", -] - -[[package]] -name = "crossbeam-utils" -version = "0.8.22" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "61803da095bee82a81bb1a452ecc25d3b2f1416d1897eb86430c6159ef717c17" - -[[package]] -name = "ctor" -version = "0.2.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "32a2785755761f3ddc1492979ce1e48d2c00d09311c39e4466429188f3dd6501" -dependencies = [ - "quote", - "syn 2.0.119", -] - -[[package]] -name = "derive_arbitrary" -version = "1.4.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1e567bd82dcff979e4b03460c307b3cdc9e96fde3d73bed1496d2bc75d9dd62a" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.119", -] - -[[package]] -name = "displaydoc" -version = "0.2.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c6232dd377dcc64799954cbd3a9bb882e9cdc1308ccd87b1c098f1fb2eaf82a8" -dependencies = [ - "proc-macro2", - "quote", - "syn 3.0.4", -] - -[[package]] -name = "equivalent" -version = "1.0.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f" - -[[package]] -name = "euclid" -version = "0.22.14" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f1a05365e3b1c6d1650318537c7460c6923f1abdd272ad6842baa2b509957a06" -dependencies = [ - "num-traits", -] - -[[package]] -name = "fdeflate" -version = "0.3.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1e6853b52649d4ac5c0bd02320cddc5ba956bdb407c4b75a2c6b75bf51500f8c" -dependencies = [ - "simd-adler32", -] - -[[package]] -name = "find-msvc-tools" -version = "0.1.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d45db016d36b838f563236e9193d0ee6ce38f3f68b6c94e914b4929c96bbb890" - -[[package]] -name = "flate2" -version = "1.1.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6e634e2e0ebac1ee034020da1ca582e17ffe4e0f5e985823721e168928136dcb" -dependencies = [ - "crc32fast", - "miniz_oxide 0.9.1", - "zlib-rs", -] - -[[package]] -name = "font-types" -version = "0.10.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "39a654f404bbcbd48ea58c617c2993ee91d1cb63727a37bf2323a4edeed1b8c5" -dependencies = [ - "bytemuck", -] - -[[package]] -name = "futures-core" -version = "0.3.34" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" - -[[package]] -name = "futures-task" -version = "0.3.34" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd" - -[[package]] -name = "futures-util" -version = "0.3.34" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" -dependencies = [ - "futures-core", - "futures-task", - "pin-project-lite", - "slab", -] - -[[package]] -name = "hashbrown" -version = "0.17.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" - -[[package]] -name = "iana-time-zone" -version = "0.1.65" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e31bc9ad994ba00e440a8aa5c9ef0ec67d5cb5e5cb0cc7f8b744a35b389cc470" -dependencies = [ - "android_system_properties", - "core-foundation-sys", - "iana-time-zone-haiku", - "js-sys", - "log", - "wasm-bindgen", - "windows-core", -] - -[[package]] -name = "iana-time-zone-haiku" -version = "0.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f31827a206f56af32e590ba56d5d2d085f558508192593743f16b2306495269f" -dependencies = [ - "cc", -] - -[[package]] -name = "image" -version = "0.25.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "85ab80394333c02fe689eaf900ab500fbd0c2213da414687ebf995a65d5a6104" -dependencies = [ - "bytemuck", - "byteorder-lite", - "moxcms", - "num-traits", - "png", -] - -[[package]] -name = "indexmap" -version = "2.14.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "07aa2048142242915a31d35844fb311e0e53fcca590c3a0a40dcf1b841fa09eb" -dependencies = [ - "equivalent", - "hashbrown", -] - -[[package]] -name = "js-sys" -version = "0.3.104" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0e0c1080212aad755ea003d18543e8768dd432c48819efd73a7bf1e39b7a5a3a" -dependencies = [ - "cfg-if", - "futures-util", - "wasm-bindgen", -] - -[[package]] -name = "kurbo" -version = "0.12.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ce9729cc38c18d86123ab736fd2e7151763ba226ac2490ec092d1dd148825e32" -dependencies = [ - "arrayvec", - "euclid", - "smallvec", -] - -[[package]] -name = "libc" -version = "0.2.189" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3eaf3ede3fee6db1a4c2ee091bf8a8b4dccdc6d17f656fb07896ee72867612f2" - -[[package]] -name = "libloading" -version = "0.8.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d7c4b02199fee7c5d21a5ae7d8cfa79a6ef5bb2fc834d6e9058e89c825efdc55" -dependencies = [ - "cfg-if", - "windows-link", -] - -[[package]] -name = "libm" -version = "0.2.16" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981" - -[[package]] -name = "log" -version = "0.4.34" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6" - -[[package]] -name = "memchr" -version = "2.8.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" - -[[package]] -name = "minipdf" -version = "0.7.0" -dependencies = [ - "chrono", - "flate2", - "image", - "roxmltree", - "rustybuzz", - "subsetter", - "thiserror", - "ttf-parser", - "unicode-bidi", - "windows-sys", - "zip", -] - -[[package]] -name = "minipdf-node" -version = "0.7.0" -dependencies = [ - "minipdf", - "napi", - "napi-build", - "napi-derive", -] - -[[package]] -name = "miniz_oxide" -version = "0.8.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1fa76a2c86f704bdb222d66965fb3d63269ce38518b83cb0575fca855ebb6316" -dependencies = [ - "adler2", - "simd-adler32", -] - -[[package]] -name = "miniz_oxide" -version = "0.9.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b63fbc4a50860e98e7b2aa7804ded1db5cbc3aff9193adaff57a6931bf7c4b4c" -dependencies = [ - "adler2", - "simd-adler32", -] - -[[package]] -name = "moxcms" -version = "0.8.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bb85c154ba489f01b25c0d36ae69a87e4a1c73a72631fc6c0eb6dde34a73e44b" -dependencies = [ - "num-traits", - "pxfm", -] - -[[package]] -name = "napi" -version = "2.16.17" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "55740c4ae1d8696773c78fdafd5d0e5fe9bc9f1b071c7ba493ba5c413a9184f3" -dependencies = [ - "bitflags", - "ctor", - "napi-derive", - "napi-sys", - "once_cell", -] - -[[package]] -name = "napi-build" -version = "2.4.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "60fdf9b392c50e7c4170fa633bd909490ed7835cea4c046776d1a4dd8d2ae0ab" - -[[package]] -name = "napi-derive" -version = "2.16.13" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7cbe2585d8ac223f7d34f13701434b9d5f4eb9c332cccce8dee57ea18ab8ab0c" -dependencies = [ - "cfg-if", - "convert_case", - "napi-derive-backend", - "proc-macro2", - "quote", - "syn 2.0.119", -] - -[[package]] -name = "napi-derive-backend" -version = "1.0.75" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1639aaa9eeb76e91c6ae66da8ce3e89e921cd3885e99ec85f4abacae72fc91bf" -dependencies = [ - "convert_case", - "once_cell", - "proc-macro2", - "quote", - "regex", - "semver", - "syn 2.0.119", -] - -[[package]] -name = "napi-sys" -version = "2.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "427802e8ec3a734331fec1035594a210ce1ff4dc5bc1950530920ab717964ea3" -dependencies = [ - "libloading", -] - -[[package]] -name = "num-traits" -version = "0.2.19" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" -dependencies = [ - "autocfg", -] - -[[package]] -name = "once_cell" -version = "1.21.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" - -[[package]] -name = "pin-project-lite" -version = "0.2.17" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" - -[[package]] -name = "png" -version = "0.18.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "60769b8b31b2a9f263dae2776c37b1b28ae246943cf719eb6946a1db05128a61" -dependencies = [ - "bitflags", - "crc32fast", - "fdeflate", - "flate2", - "miniz_oxide 0.8.9", -] - -[[package]] -name = "proc-macro2" -version = "1.0.107" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" -dependencies = [ - "unicode-ident", -] - -[[package]] -name = "pxfm" -version = "0.1.30" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d55d956fa96f5ec02be2e13af0e20391a5aa83d6a074e3ad368959d0fab299ea" - -[[package]] -name = "quote" -version = "1.0.47" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" -dependencies = [ - "proc-macro2", -] - -[[package]] -name = "read-fonts" -version = "0.35.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6717cf23b488adf64b9d711329542ba34de147df262370221940dfabc2c91358" -dependencies = [ - "bytemuck", - "font-types", -] - -[[package]] -name = "regex" -version = "1.13.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f020237b6c8eed93db2e2cb53c00c60a8e1bc73da7d073199a1180401450218d" -dependencies = [ - "aho-corasick", - "memchr", - "regex-automata", - "regex-syntax", -] - -[[package]] -name = "regex-automata" -version = "0.4.18" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ad8553b9b26413251cbf30e620595c7a41b3887f03da04579c0e6b0d6a06b4b2" -dependencies = [ - "aho-corasick", - "memchr", - "regex-syntax", -] - -[[package]] -name = "regex-syntax" -version = "0.8.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4" - -[[package]] -name = "roxmltree" -version = "0.20.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6c20b6793b5c2fa6553b250154b78d6d0db37e72700ae35fad9387a46f487c97" - -[[package]] -name = "rustc-hash" -version = "2.1.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d" - -[[package]] -name = "rustversion" -version = "1.0.23" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" - -[[package]] -name = "rustybuzz" -version = "0.20.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fd3c7c96f8a08ee34eff8857b11b49b07d71d1c3f4e88f8a88d4c9e9f90b1702" -dependencies = [ - "bitflags", - "bytemuck", - "core_maths", - "log", - "smallvec", - "ttf-parser", - "unicode-bidi-mirroring", - "unicode-ccc", - "unicode-properties", - "unicode-script", -] - -[[package]] -name = "semver" -version = "1.0.28" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" - -[[package]] -name = "shlex" -version = "2.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" - -[[package]] -name = "simd-adler32" -version = "0.3.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea" - -[[package]] -name = "skrifa" -version = "0.37.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8c31071dedf532758ecf3fed987cdb4bd9509f900e026ab684b4ecb81ea49841" -dependencies = [ - "bytemuck", - "read-fonts", -] - -[[package]] -name = "slab" -version = "0.4.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" - -[[package]] -name = "smallvec" -version = "1.16.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b9be42f50aa861c555654aa3a37f52f4b1074bacf4e48fe0ef7fa584e80f1f0f" - -[[package]] -name = "subsetter" -version = "0.2.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cb6895a12ac5599bb6057362f00e8a3cf1daab4df33f553a55690a44e4fed8d0" -dependencies = [ - "kurbo", - "rustc-hash", - "skrifa", - "write-fonts", -] - -[[package]] -name = "syn" -version = "2.0.119" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" -dependencies = [ - "proc-macro2", - "quote", - "unicode-ident", -] - -[[package]] -name = "syn" -version = "3.0.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e6275cddf4610d1775e6d1fe9469b2e77d0f39fd98fb7450901b821e0c53649f" -dependencies = [ - "proc-macro2", - "quote", - "unicode-ident", -] - -[[package]] -name = "thiserror" -version = "2.0.20" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ec86235f5fcc2a73650310756d2ac5b138a5780bbbdfae3eeccec992c435ba4f" -dependencies = [ - "thiserror-impl", -] - -[[package]] -name = "thiserror-impl" -version = "2.0.20" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bc04cd3e1236dd4a98afca4569f2deb3f120e5422a4023be2cb683f8486292af" -dependencies = [ - "proc-macro2", - "quote", - "syn 3.0.4", -] - -[[package]] -name = "ttf-parser" -version = "0.25.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d2df906b07856748fa3f6e0ad0cbaa047052d4a7dd609e231c4f72cee8c36f31" -dependencies = [ - "core_maths", -] - -[[package]] -name = "unicode-bidi" -version = "0.3.18" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5c1cb5db39152898a79168971543b1cb5020dff7fe43c8dc468b0885f5e29df5" - -[[package]] -name = "unicode-bidi-mirroring" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5dfa6e8c60bb66d49db113e0125ee8711b7647b5579dc7f5f19c42357ed039fe" - -[[package]] -name = "unicode-ccc" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ce61d488bcdc9bc8b5d1772c404828b17fc481c0a582b5581e95fb233aef503e" - -[[package]] -name = "unicode-ident" -version = "1.0.24" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75" - -[[package]] -name = "unicode-properties" -version = "0.1.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7df058c713841ad818f1dc5d3fd88063241cc61f49f5fbea4b951e8cf5a8d71d" - -[[package]] -name = "unicode-script" -version = "0.5.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "383ad40bb927465ec0ce7720e033cb4ca06912855fc35db31b5755d0de75b1ee" - -[[package]] -name = "unicode-segmentation" -version = "1.13.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c6f5d3c3b1bf09027a88a6bc961fc00497d651009560b5463668dc81b0fa87a8" - -[[package]] -name = "wasm-bindgen" -version = "0.2.127" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1b70935747edd64d89de3efa29d73789b806c15798f8e7dca4d8ac356b50ce70" -dependencies = [ - "cfg-if", - "once_cell", - "rustversion", - "wasm-bindgen-macro", - "wasm-bindgen-shared", -] - -[[package]] -name = "wasm-bindgen-macro" -version = "0.2.127" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "77775f8f3f7217702089053b94958f8f54061a3f663417df76e19cbdcca29bc1" -dependencies = [ - "quote", - "wasm-bindgen-macro-support", -] - -[[package]] -name = "wasm-bindgen-macro-support" -version = "0.2.127" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e11d33f857dc2fb11b8bc75aee111aa9cbeb12cd9f25efd3d4c2a3dd4e235284" -dependencies = [ - "bumpalo", - "proc-macro2", - "quote", - "syn 2.0.119", - "wasm-bindgen-shared", -] - -[[package]] -name = "wasm-bindgen-shared" -version = "0.2.127" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7ef64dbcc55df09c7e5a46182d181c2cfa3e925f3da937ea764728b4bbb9dcbf" -dependencies = [ - "unicode-ident", -] - -[[package]] -name = "windows-core" -version = "0.62.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb" -dependencies = [ - "windows-implement", - "windows-interface", - "windows-link", - "windows-result", - "windows-strings", -] - -[[package]] -name = "windows-implement" -version = "0.60.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.119", -] - -[[package]] -name = "windows-interface" -version = "0.59.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.119", -] - -[[package]] -name = "windows-link" -version = "0.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" - -[[package]] -name = "windows-result" -version = "0.4.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5" -dependencies = [ - "windows-link", -] - -[[package]] -name = "windows-strings" -version = "0.5.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091" -dependencies = [ - "windows-link", -] - -[[package]] -name = "windows-sys" -version = "0.61.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" -dependencies = [ - "windows-link", -] - -[[package]] -name = "write-fonts" -version = "0.43.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "886614b5ce857341226aa091f3c285e450683894acaaa7887f366c361efef79d" -dependencies = [ - "font-types", - "indexmap", - "kurbo", - "log", - "read-fonts", -] - -[[package]] -name = "zip" -version = "2.4.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fabe6324e908f85a1c52063ce7aa26b68dcb7eb6dbc83a2d148403c9bc3eba50" -dependencies = [ - "arbitrary", - "crc32fast", - "crossbeam-utils", - "displaydoc", - "flate2", - "indexmap", - "memchr", - "thiserror", - "zopfli", -] - -[[package]] -name = "zlib-rs" -version = "0.6.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "34b31d188d9d685a4f9c7b46d6e36631b07058d2cfe190267adce54dc230bf12" - -[[package]] -name = "zopfli" -version = "0.8.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f05cd8797d63865425ff89b5c4a48804f35ba0ce8d125800027ad6017d2b5249" -dependencies = [ - "bumpalo", - "crc32fast", - "log", - "simd-adler32", -] diff --git a/minipdf-node/Cargo.toml b/minipdf-node/Cargo.toml deleted file mode 100644 index fd389f34..00000000 --- a/minipdf-node/Cargo.toml +++ /dev/null @@ -1,23 +0,0 @@ -[package] -name = "minipdf-node" -version = "0.7.0" -edition = "2021" -license = "Apache-2.0" -repository = "https://github.com/mini-software/MiniPdf" -description = "Node.js bindings for MiniPdf Office-to-PDF conversion." -publish = false - -[lib] -crate-type = ["cdylib"] - -[dependencies] -minipdf = { path = "../minipdf-rs/crates/minipdf" } -napi = { version = "2", default-features = false, features = ["napi6"] } -napi-derive = "2" - -[build-dependencies] -napi-build = "2" - -[profile.release] -lto = true -strip = "symbols" diff --git a/minipdf-node/LICENSE b/minipdf-node/LICENSE deleted file mode 100644 index 422b9f1e..00000000 --- a/minipdf-node/LICENSE +++ /dev/null @@ -1,194 +0,0 @@ - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship made available under - the License, as indicated by a copyright notice that is included in - or attached to the work (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean, as submitted to the Licensor for inclusion - in the Work by the copyright owner or by an individual or Legal Entity - authorized to submit on behalf of the copyright owner. For the purposes - of this definition, "submitted" means any form of electronic, verbal, - or written communication sent to the Licensor or its representatives, - including but not limited to communication on electronic mailing lists, - source code control systems, and issue tracking systems that are managed - by, or on behalf of, the Licensor for the purpose of discussing and - improving the Work, but excluding communication that is conspicuously - marked or designated in writing by the copyright owner as "Not a - Contribution." - - "Contributor" shall mean Licensor and any Legal Entity on behalf of - whom a Contribution has been received by the Licensor and included - within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by the combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a cross-claim - or counterclaim in a lawsuit) alleging that the Work or any - Contribution embodied within the Work constitutes direct or contributory - patent infringement, then any patent licenses granted to You under - this License for that Work shall terminate as of the date such - litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or Derivative - Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, You must include a readable copy of the - attribution notices contained within such NOTICE file, in - at least one of the following places: within a NOTICE text - file distributed as part of the Derivative Works; within - the Source form or documentation, if provided along with the - Derivative Works; or, within a display generated by the - Derivative Works, if and wherever such third-party notices - normally appear. The contents of the NOTICE file are for - informational purposes only and do not modify the License. - You may add Your own attribution notices within Derivative - Works that You distribute, alongside or in addition to the - NOTICE text from the Work, provided that such additional - attribution notices cannot be construed as modifying the License. - - You may add Your own license statement for Your modifications and - may provide additional grant of rights to use, copy, modify, merge, - publish, distribute, sublicense, and/or sell copies of the - Contribution, either on an "unrestricted" basis, provided such - additional grant does not modify this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any conditions of title, - MERCHANTIBILITY, or FITNESS FOR A PARTICULAR PURPOSE, and - non-infringement. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or exemplary damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or all other - commercial damages or losses), even if such Contributor has been - advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may offer such - obligations only on Your own behalf and on Your sole responsibility, - not on behalf of any other Contributor, and only if You agree to - indemnify, defend, and hold each Contributor harmless for any - liability incurred by, or claims asserted against, such Contributor - by reason of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the format in use. Please also include a - "NOTICE" file alongside your work indicating the contributing - entities or legal organization. - - Copyright 2026 Wei Lin - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. diff --git a/minipdf-node/README.md b/minipdf-node/README.md deleted file mode 100644 index 9498371f..00000000 --- a/minipdf-node/README.md +++ /dev/null @@ -1,110 +0,0 @@ -# MiniPdf for Node.js - -[![License](https://img.shields.io/badge/license-Apache%202.0-blue.svg)](../LICENSE) - -Experimental native Node.js bindings for the MiniPdf Rust conversion engine. -The package converts XLSX, DOCX, and PPTX files without requiring Microsoft -Office, LibreOffice, Adobe Acrobat, or .NET at runtime. - -> The Node.js implementation is under active development and is not yet -> feature-equivalent with MiniPdf for .NET. - -## Requirements - -- Node.js 18 or later -- Rust 1.82 or later when building the package from source - -## Installation - -```powershell -npm install minipdf -``` - -Precompiled native addons are provided for Windows, macOS, glibc Linux, and -musl Linux on x64 and ARM64. - -## Development - -```powershell -Set-Location minipdf-node -npm install -npm run build -``` - -## Usage - -Convert an Office file to a PDF on disk: - -```javascript -const minipdf = require('minipdf') - -minipdf.convertToPdf('report.docx', 'report.pdf') -``` - -Return a Node.js `Buffer` instead: - -```javascript -const pdf = minipdf.convertToPdfBytes('data.xlsx') -``` - -Convert an in-memory Office package: - -```javascript -const fs = require('node:fs') -const minipdf = require('minipdf') - -const input = fs.readFileSync('slides.pptx') -const pdf = minipdf.convertBytesToPdf(input) -``` - -Override the output page size with a preset or custom dimensions in PDF points: - -```javascript -minipdf.convertToPdf('data.xlsx', 'data.pdf', { - pageSize: minipdf.PageSize.A4 -}) - -minipdf.convertToPdf('report.docx', 'report.pdf', { - pageSize: { width: 400, height: 500 } -}) -``` - -Register font bytes before conversion when the host has limited system fonts: - -```javascript -const font = fs.readFileSync('fonts/NotoSansSC-Regular.ttf') -minipdf.registerFont('NotoSansSC', font) -``` - -The conversion functions are synchronous and occupy the calling Node.js thread. -Use a worker thread when converting documents in a latency-sensitive server. - -## API - -- `convertToPdf(inputPath, outputPath, options?)` -- `convertToPdfBytes(inputPath, options?)` -- `convertBytesToPdf(input, options?)` -- `detectOfficeFormat(input)` -- `registerFont(name, fontData)` -- `registeredFonts()` -- `PageSize.A4` and `PageSize.LETTER` - -## Validation - -```powershell -npm install -npm run build -npm test -npm pack --dry-run -``` - -## Publishing - -The `NPM Publish` GitHub Actions workflow builds all native addons before it -publishes any package. For the first release, run it manually in `initial` mode -with a short-lived granular npm token that can publish new packages and bypass -2FA, stored as the `NPM_TOKEN` Actions secret. - -After the initial release, configure `npm-publish.yml` as the trusted GitHub -Actions publisher for the main package and all eight platform packages. Future -`node-v*` GitHub releases use OIDC to stage packages for maintainer approval. \ No newline at end of file diff --git a/minipdf-node/build.rs b/minipdf-node/build.rs deleted file mode 100644 index 0f1b0100..00000000 --- a/minipdf-node/build.rs +++ /dev/null @@ -1,3 +0,0 @@ -fn main() { - napi_build::setup(); -} diff --git a/minipdf-node/index.d.ts b/minipdf-node/index.d.ts deleted file mode 100644 index 4fc598ff..00000000 --- a/minipdf-node/index.d.ts +++ /dev/null @@ -1,22 +0,0 @@ -/* tslint:disable */ -/* eslint-disable */ - -/* auto-generated by NAPI-RS */ - -export interface PageSize { - width: number - height: number -} -export interface ConversionOptions { - pageSize?: PageSize -} -export interface RegisteredFont { - name: string - data: Buffer -} -export declare function convertToPdf(inputPath: string, outputPath: string, options?: ConversionOptions | undefined | null): void -export declare function convertToPdfBytes(inputPath: string, options?: ConversionOptions | undefined | null): Buffer -export declare function convertBytesToPdf(input: Buffer, options?: ConversionOptions | undefined | null): Buffer -export declare function detectOfficeFormat(input: Buffer): string -export declare function registerFont(name: string, fontData: Buffer): void -export declare function registeredFonts(): Array diff --git a/minipdf-node/index.js b/minipdf-node/index.js deleted file mode 100644 index 0977b84c..00000000 --- a/minipdf-node/index.js +++ /dev/null @@ -1,312 +0,0 @@ -/* tslint:disable */ -/* eslint-disable */ -/* prettier-ignore */ - -/* auto-generated by NAPI-RS */ - -const { existsSync } = require('fs') -const { join } = require('path') - -const { platform, arch } = process - -let nativeBinding = null -let localFileExisted = false -let loadError = null - -function isMusl() { - const { glibcVersionRuntime } = process.report.getReport().header - return !glibcVersionRuntime -} - -switch (platform) { - case 'android': - switch (arch) { - case 'arm64': - localFileExisted = existsSync(join(__dirname, 'minipdf-node.android-arm64.node')) - try { - if (localFileExisted) { - nativeBinding = require('./minipdf-node.android-arm64.node') - } else { - nativeBinding = require('minipdf-android-arm64') - } - } catch (e) { - loadError = e - } - break - case 'arm': - localFileExisted = existsSync(join(__dirname, 'minipdf-node.android-arm-eabi.node')) - try { - if (localFileExisted) { - nativeBinding = require('./minipdf-node.android-arm-eabi.node') - } else { - nativeBinding = require('minipdf-android-arm-eabi') - } - } catch (e) { - loadError = e - } - break - default: - throw new Error(`Unsupported architecture on Android ${arch}`) - } - break - case 'win32': - switch (arch) { - case 'x64': - localFileExisted = existsSync( - join(__dirname, 'minipdf-node.win32-x64-msvc.node') - ) - try { - if (localFileExisted) { - nativeBinding = require('./minipdf-node.win32-x64-msvc.node') - } else { - nativeBinding = require('@mini-software/minipdf-win32-x64-msvc') - } - } catch (e) { - loadError = e - } - break - case 'ia32': - localFileExisted = existsSync( - join(__dirname, 'minipdf-node.win32-ia32-msvc.node') - ) - try { - if (localFileExisted) { - nativeBinding = require('./minipdf-node.win32-ia32-msvc.node') - } else { - nativeBinding = require('minipdf-win32-ia32-msvc') - } - } catch (e) { - loadError = e - } - break - case 'arm64': - localFileExisted = existsSync( - join(__dirname, 'minipdf-node.win32-arm64-msvc.node') - ) - try { - if (localFileExisted) { - nativeBinding = require('./minipdf-node.win32-arm64-msvc.node') - } else { - nativeBinding = require('minipdf-win32-arm64-msvc') - } - } catch (e) { - loadError = e - } - break - default: - throw new Error(`Unsupported architecture on Windows: ${arch}`) - } - break - case 'darwin': - localFileExisted = existsSync(join(__dirname, 'minipdf-node.darwin-universal.node')) - try { - if (localFileExisted) { - nativeBinding = require('./minipdf-node.darwin-universal.node') - } else { - nativeBinding = require('minipdf-darwin-universal') - } - break - } catch {} - switch (arch) { - case 'x64': - localFileExisted = existsSync(join(__dirname, 'minipdf-node.darwin-x64.node')) - try { - if (localFileExisted) { - nativeBinding = require('./minipdf-node.darwin-x64.node') - } else { - nativeBinding = require('minipdf-darwin-x64') - } - } catch (e) { - loadError = e - } - break - case 'arm64': - localFileExisted = existsSync( - join(__dirname, 'minipdf-node.darwin-arm64.node') - ) - try { - if (localFileExisted) { - nativeBinding = require('./minipdf-node.darwin-arm64.node') - } else { - nativeBinding = require('minipdf-darwin-arm64') - } - } catch (e) { - loadError = e - } - break - default: - throw new Error(`Unsupported architecture on macOS: ${arch}`) - } - break - case 'freebsd': - if (arch !== 'x64') { - throw new Error(`Unsupported architecture on FreeBSD: ${arch}`) - } - localFileExisted = existsSync(join(__dirname, 'minipdf-node.freebsd-x64.node')) - try { - if (localFileExisted) { - nativeBinding = require('./minipdf-node.freebsd-x64.node') - } else { - nativeBinding = require('minipdf-freebsd-x64') - } - } catch (e) { - loadError = e - } - break - case 'linux': - switch (arch) { - case 'x64': - if (isMusl()) { - localFileExisted = existsSync( - join(__dirname, 'minipdf-node.linux-x64-musl.node') - ) - try { - if (localFileExisted) { - nativeBinding = require('./minipdf-node.linux-x64-musl.node') - } else { - nativeBinding = require('minipdf-linux-x64-musl') - } - } catch (e) { - loadError = e - } - } else { - localFileExisted = existsSync( - join(__dirname, 'minipdf-node.linux-x64-gnu.node') - ) - try { - if (localFileExisted) { - nativeBinding = require('./minipdf-node.linux-x64-gnu.node') - } else { - nativeBinding = require('minipdf-linux-x64-gnu') - } - } catch (e) { - loadError = e - } - } - break - case 'arm64': - if (isMusl()) { - localFileExisted = existsSync( - join(__dirname, 'minipdf-node.linux-arm64-musl.node') - ) - try { - if (localFileExisted) { - nativeBinding = require('./minipdf-node.linux-arm64-musl.node') - } else { - nativeBinding = require('minipdf-linux-arm64-musl') - } - } catch (e) { - loadError = e - } - } else { - localFileExisted = existsSync( - join(__dirname, 'minipdf-node.linux-arm64-gnu.node') - ) - try { - if (localFileExisted) { - nativeBinding = require('./minipdf-node.linux-arm64-gnu.node') - } else { - nativeBinding = require('minipdf-linux-arm64-gnu') - } - } catch (e) { - loadError = e - } - } - break - case 'arm': - if (isMusl()) { - localFileExisted = existsSync( - join(__dirname, 'minipdf-node.linux-arm-musleabihf.node') - ) - try { - if (localFileExisted) { - nativeBinding = require('./minipdf-node.linux-arm-musleabihf.node') - } else { - nativeBinding = require('minipdf-linux-arm-musleabihf') - } - } catch (e) { - loadError = e - } - } else { - localFileExisted = existsSync( - join(__dirname, 'minipdf-node.linux-arm-gnueabihf.node') - ) - try { - if (localFileExisted) { - nativeBinding = require('./minipdf-node.linux-arm-gnueabihf.node') - } else { - nativeBinding = require('minipdf-linux-arm-gnueabihf') - } - } catch (e) { - loadError = e - } - } - break - case 'riscv64': - if (isMusl()) { - localFileExisted = existsSync( - join(__dirname, 'minipdf-node.linux-riscv64-musl.node') - ) - try { - if (localFileExisted) { - nativeBinding = require('./minipdf-node.linux-riscv64-musl.node') - } else { - nativeBinding = require('minipdf-linux-riscv64-musl') - } - } catch (e) { - loadError = e - } - } else { - localFileExisted = existsSync( - join(__dirname, 'minipdf-node.linux-riscv64-gnu.node') - ) - try { - if (localFileExisted) { - nativeBinding = require('./minipdf-node.linux-riscv64-gnu.node') - } else { - nativeBinding = require('minipdf-linux-riscv64-gnu') - } - } catch (e) { - loadError = e - } - } - break - case 's390x': - localFileExisted = existsSync( - join(__dirname, 'minipdf-node.linux-s390x-gnu.node') - ) - try { - if (localFileExisted) { - nativeBinding = require('./minipdf-node.linux-s390x-gnu.node') - } else { - nativeBinding = require('minipdf-linux-s390x-gnu') - } - } catch (e) { - loadError = e - } - break - default: - throw new Error(`Unsupported architecture on Linux: ${arch}`) - } - break - default: - throw new Error(`Unsupported OS: ${platform}, architecture: ${arch}`) -} - -if (!nativeBinding) { - const detail = loadError ? `: ${loadError.message}` : '' - throw new Error( - `Failed to load MiniPdf native binding for ${platform}/${arch}${detail}. ` + - 'Reinstall minipdf with optional dependencies enabled or build it from source.', - { cause: loadError || undefined } - ) -} - -const { convertToPdf, convertToPdfBytes, convertBytesToPdf, detectOfficeFormat, registerFont, registeredFonts } = nativeBinding - -module.exports.convertToPdf = convertToPdf -module.exports.convertToPdfBytes = convertToPdfBytes -module.exports.convertBytesToPdf = convertBytesToPdf -module.exports.detectOfficeFormat = detectOfficeFormat -module.exports.registerFont = registerFont -module.exports.registeredFonts = registeredFonts diff --git a/minipdf-node/lib/index.d.ts b/minipdf-node/lib/index.d.ts deleted file mode 100644 index ce537c7b..00000000 --- a/minipdf-node/lib/index.d.ts +++ /dev/null @@ -1,44 +0,0 @@ -/// - -export type OfficeFormat = 'unknown' | 'xlsx' | 'docx' | 'pptx' - -export interface PageSizeValue { - readonly width: number - readonly height: number -} - -export declare const PageSize: { - readonly A4: Readonly - readonly LETTER: Readonly -} - -export interface ConversionOptions { - pageSize?: PageSizeValue -} - -export interface RegisteredFont { - name: string - data: Buffer -} - -export declare function convertToPdf( - inputPath: string, - outputPath: string, - options?: ConversionOptions -): void - -export declare function convertToPdfBytes( - inputPath: string, - options?: ConversionOptions -): Buffer - -export declare function convertBytesToPdf( - input: Buffer, - options?: ConversionOptions -): Buffer - -export declare function detectOfficeFormat(input: Buffer): OfficeFormat - -export declare function registerFont(name: string, fontData: Buffer): void - -export declare function registeredFonts(): RegisteredFont[] diff --git a/minipdf-node/lib/index.js b/minipdf-node/lib/index.js deleted file mode 100644 index 8ff72dae..00000000 --- a/minipdf-node/lib/index.js +++ /dev/null @@ -1,13 +0,0 @@ -'use strict' - -const binding = require('../index.js') - -const PageSize = Object.freeze({ - A4: Object.freeze({ width: 595.28, height: 841.89 }), - LETTER: Object.freeze({ width: 612, height: 792 }) -}) - -module.exports = { - ...binding, - PageSize -} diff --git a/minipdf-node/package-lock.json b/minipdf-node/package-lock.json deleted file mode 100644 index 0361db93..00000000 --- a/minipdf-node/package-lock.json +++ /dev/null @@ -1,51 +0,0 @@ -{ - "name": "minipdf", - "version": "0.7.0", - "lockfileVersion": 3, - "requires": true, - "packages": { - "": { - "name": "minipdf", - "version": "0.7.0", - "license": "Apache-2.0", - "devDependencies": { - "@napi-rs/cli": "^2.18.4", - "@types/node": "^20.17.0" - }, - "engines": { - "node": ">=18.13.0" - } - }, - "node_modules/@napi-rs/cli": { - "version": "2.18.4", - "resolved": "https://registry.npmjs.org/@napi-rs/cli/-/cli-2.18.4.tgz", - "integrity": "sha512-SgJeA4df9DE2iAEpr3M2H0OKl/yjtg1BnRI5/JyowS71tUWhrfSu2LT0V3vlHET+g1hBVlrO60PmEXwUEKp8Mg==", - "dev": true, - "bin": { - "napi": "scripts/index.js" - }, - "engines": { - "node": ">= 10" - }, - "funding": { - "type": "github", - "url": "https://github.com/sponsors/Brooooooklyn" - } - }, - "node_modules/@types/node": { - "version": "20.19.43", - "resolved": "https://registry.npmjs.org/@types/node/-/node-20.19.43.tgz", - "integrity": "sha512-6oYBAi5ikg4Pl+kGsoYtawUMBT2zZMCvPNF7pVLnHZfd1zf38DRiWn/gT01RYCdUqkv7Fhr+C9ot4/tb+2sVvA==", - "dev": true, - "dependencies": { - "undici-types": "~6.21.0" - } - }, - "node_modules/undici-types": { - "version": "6.21.0", - "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.21.0.tgz", - "integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==", - "dev": true - } - } -} diff --git a/minipdf-node/package.json b/minipdf-node/package.json deleted file mode 100644 index 3ca22d15..00000000 --- a/minipdf-node/package.json +++ /dev/null @@ -1,65 +0,0 @@ -{ - "name": "minipdf", - "version": "0.7.0", - "description": "Native Node.js Office-to-PDF conversion powered by MiniPdf for Rust", - "license": "Apache-2.0", - "author": "MiniPdf contributors", - "repository": { - "type": "git", - "url": "git+https://github.com/mini-software/MiniPdf.git", - "directory": "minipdf-node" - }, - "homepage": "https://github.com/mini-software/MiniPdf/tree/main/minipdf-node", - "bugs": "https://github.com/mini-software/MiniPdf/issues", - "main": "lib/index.js", - "types": "lib/index.d.ts", - "files": [ - "LICENSE", - "lib/", - "index.js", - "index.d.ts", - "README.md" - ], - "engines": { - "node": ">=18.13.0" - }, - "scripts": { - "artifacts": "napi artifacts", - "build": "napi build --platform --release", - "postbuild": "node scripts/postprocess-loader.js", - "build:debug": "napi build --platform", - "postbuild:debug": "node scripts/postprocess-loader.js", - "create-npm-dir": "napi create-npm-dir -t .", - "prepare-release": "node scripts/prepare-release.js", - "test": "node --test test/index.test.js" - }, - "publishConfig": { - "access": "public", - "registry": "https://registry.npmjs.org/" - }, - "napi": { - "name": "minipdf-node", - "triples": { - "defaults": true, - "additional": [ - "aarch64-pc-windows-msvc", - "aarch64-apple-darwin", - "aarch64-unknown-linux-gnu", - "x86_64-unknown-linux-musl", - "aarch64-unknown-linux-musl" - ] - } - }, - "devDependencies": { - "@napi-rs/cli": "^2.18.4", - "@types/node": "^20.17.0" - }, - "keywords": [ - "pdf", - "docx", - "xlsx", - "pptx", - "converter", - "office" - ] -} diff --git a/minipdf-node/scripts/postprocess-loader.js b/minipdf-node/scripts/postprocess-loader.js deleted file mode 100644 index a3ce0b65..00000000 --- a/minipdf-node/scripts/postprocess-loader.js +++ /dev/null @@ -1,62 +0,0 @@ -'use strict' - -const fs = require('node:fs') -const path = require('node:path') - -const oldWindowsX64Require = "require('minipdf-win32-x64-msvc')" -const newWindowsX64Require = "require('@mini-software/minipdf-win32-x64-msvc')" -const oldMuslFunction = /function isMusl\(\) \{[\s\S]*?\n\}\n\nswitch \(platform\)/ -const newMuslFunction = `function isMusl() { - const { glibcVersionRuntime } = process.report.getReport().header - return !glibcVersionRuntime -} - -switch (platform)` - -const oldLoadFailure = `if (!nativeBinding) { - if (loadError) { - throw loadError - } - throw new Error(\`Failed to load native binding\`) -}` -const newLoadFailure = `if (!nativeBinding) { - const detail = loadError ? \`: \${loadError.message}\` : '' - throw new Error( - \`Failed to load MiniPdf native binding for \${platform}/\${arch}\${detail}. \` + - 'Reinstall minipdf with optional dependencies enabled or build it from source.', - { cause: loadError || undefined } - ) -}` - -function postprocessLoader(source) { - let output = source.replaceAll('\r\n', '\n').replace( - "const { existsSync, readFileSync } = require('fs')", - "const { existsSync } = require('fs')" - ) - output = output.replaceAll(oldWindowsX64Require, newWindowsX64Require) - - if (!output.includes(newMuslFunction)) { - output = output.replace(oldMuslFunction, newMuslFunction) - } - if (!output.includes(newLoadFailure)) { - output = output.replace(oldLoadFailure, newLoadFailure) - } - - if ( - !output.includes(newWindowsX64Require) || - !output.includes(newMuslFunction) || - !output.includes(newLoadFailure) - ) { - throw new Error('Generated N-API loader did not match the expected structure') - } - - return output -} - -if (require.main === module) { - const loaderPath = path.join(__dirname, '..', 'index.js') - const source = fs.readFileSync(loaderPath, 'utf8') - fs.writeFileSync(loaderPath, postprocessLoader(source)) -} - -module.exports = { postprocessLoader } \ No newline at end of file diff --git a/minipdf-node/scripts/prepare-release.js b/minipdf-node/scripts/prepare-release.js deleted file mode 100644 index eb2066f0..00000000 --- a/minipdf-node/scripts/prepare-release.js +++ /dev/null @@ -1,92 +0,0 @@ -'use strict' - -const fs = require('node:fs') -const path = require('node:path') -const { postprocessLoader } = require('./postprocess-loader.js') - -const SUPPORTED_NATIVE_PACKAGES = [ - 'minipdf-darwin-arm64', - 'minipdf-darwin-x64', - 'minipdf-linux-arm64-gnu', - 'minipdf-linux-arm64-musl', - 'minipdf-linux-x64-gnu', - 'minipdf-linux-x64-musl', - 'minipdf-win32-arm64-msvc', - 'minipdf-win32-x64-msvc' -] - -const PUBLISHED_PACKAGE_NAMES = { - 'minipdf-win32-x64-msvc': '@mini-software/minipdf-win32-x64-msvc' -} - -function prepareRelease(packageRoot = process.cwd()) { - const packagePath = path.join(packageRoot, 'package.json') - const licensePath = path.join(packageRoot, 'LICENSE') - const platformRoot = path.join(packageRoot, 'npm') - const packageJson = JSON.parse(fs.readFileSync(packagePath, 'utf8')) - const platformDirectories = fs.readdirSync(platformRoot, { withFileTypes: true }) - .filter((entry) => entry.isDirectory()) - .map((entry) => entry.name) - .sort() - - if (platformDirectories.length !== SUPPORTED_NATIVE_PACKAGES.length) { - throw new Error( - `Expected ${SUPPORTED_NATIVE_PACKAGES.length} platform packages, found ${platformDirectories.length}` - ) - } - - const optionalDependencies = {} - for (const directory of platformDirectories) { - const platformDirectory = path.join(platformRoot, directory) - const platformPackage = JSON.parse( - fs.readFileSync(path.join(platformDirectory, 'package.json'), 'utf8') - ) - - if (platformPackage.version !== packageJson.version) { - throw new Error( - `${platformPackage.name} version ${platformPackage.version} does not match ${packageJson.version}` - ) - } - - const generatedName = platformPackage.name - platformPackage.name = PUBLISHED_PACKAGE_NAMES[generatedName] || generatedName - fs.writeFileSync( - path.join(platformDirectory, 'package.json'), - `${JSON.stringify(platformPackage, null, 2)}\n` - ) - - const readmePath = path.join(platformDirectory, 'README.md') - if (platformPackage.name !== generatedName && fs.existsSync(readmePath)) { - const readme = fs.readFileSync(readmePath, 'utf8') - fs.writeFileSync(readmePath, readme.replaceAll(generatedName, platformPackage.name)) - } - - optionalDependencies[platformPackage.name] = platformPackage.version - fs.copyFileSync(licensePath, path.join(platformDirectory, 'LICENSE')) - } - - const nativePackageNames = Object.keys(optionalDependencies).sort() - const publishedPackageNames = SUPPORTED_NATIVE_PACKAGES - .map((name) => PUBLISHED_PACKAGE_NAMES[name] || name) - .sort() - if (!publishedPackageNames.every((name, index) => name === nativePackageNames[index])) { - throw new Error(`Unexpected platform package set: ${nativePackageNames.join(', ')}`) - } - - packageJson.optionalDependencies = optionalDependencies - fs.writeFileSync(packagePath, `${JSON.stringify(packageJson, null, 2)}\n`) - - const loaderPath = path.join(packageRoot, 'index.js') - if (fs.existsSync(loaderPath)) { - const loader = fs.readFileSync(loaderPath, 'utf8') - fs.writeFileSync(loaderPath, postprocessLoader(loader)) - } - - return optionalDependencies -} - -if (require.main === module) { - prepareRelease() -} - -module.exports = { prepareRelease } \ No newline at end of file diff --git a/minipdf-node/src/lib.rs b/minipdf-node/src/lib.rs deleted file mode 100644 index dea666e3..00000000 --- a/minipdf-node/src/lib.rs +++ /dev/null @@ -1,114 +0,0 @@ -use std::panic::{catch_unwind, AssertUnwindSafe}; - -use minipdf::{ConversionOptions as CoreConversionOptions, PageSize as CorePageSize}; -use napi::bindgen_prelude::{Buffer, Error, Result, Status}; -use napi_derive::napi; - -#[napi(object)] -pub struct PageSize { - pub width: f64, - pub height: f64, -} - -#[napi(object)] -pub struct ConversionOptions { - pub page_size: Option, -} - -#[napi(object)] -pub struct RegisteredFont { - pub name: String, - pub data: Buffer, -} - -#[napi(js_name = "convertToPdf")] -pub fn convert_to_pdf( - input_path: String, - output_path: String, - options: Option, -) -> Result<()> { - minipdf::register_system_fonts().map_err(to_napi_error)?; - let options = to_core_options(options)?; - minipdf::convert_to_pdf_with_options(input_path, output_path, &options).map_err(to_napi_error) -} - -#[napi(js_name = "convertToPdfBytes")] -pub fn convert_to_pdf_bytes( - input_path: String, - options: Option, -) -> Result { - minipdf::register_system_fonts().map_err(to_napi_error)?; - let options = to_core_options(options)?; - minipdf::convert_to_pdf_bytes_with_options(input_path, &options) - .map(Buffer::from) - .map_err(to_napi_error) -} - -#[napi(js_name = "convertBytesToPdf")] -pub fn convert_bytes_to_pdf(input: Buffer, options: Option) -> Result { - minipdf::register_system_fonts().map_err(to_napi_error)?; - let options = to_core_options(options)?; - minipdf::convert_bytes_to_pdf_with_options(input.as_ref(), &options) - .map(Buffer::from) - .map_err(to_napi_error) -} - -#[napi(js_name = "detectOfficeFormat")] -pub fn detect_office_format(input: Buffer) -> Result { - minipdf::detect_office_format(input.as_ref()) - .map(|format| match format { - minipdf::OfficeFormat::Unknown => "unknown", - minipdf::OfficeFormat::Xlsx => "xlsx", - minipdf::OfficeFormat::Docx => "docx", - minipdf::OfficeFormat::Pptx => "pptx", - }) - .map(str::to_owned) - .map_err(to_napi_error) -} - -#[napi(js_name = "registerFont")] -pub fn register_font(name: String, font_data: Buffer) -> Result<()> { - catch_core_panic(|| minipdf::register_font(name, font_data.to_vec())) -} - -#[napi(js_name = "registeredFonts")] -pub fn registered_fonts() -> Result> { - catch_core_panic(minipdf::registered_fonts).map(|fonts| { - fonts - .into_iter() - .map(|font| RegisteredFont { - name: font.name, - data: Buffer::from(font.data), - }) - .collect() - }) -} - -fn to_core_options(options: Option) -> Result { - let page_size = options - .and_then(|options| options.page_size) - .map(|page_size| CorePageSize::new(page_size.width as f32, page_size.height as f32)) - .transpose() - .map_err(to_napi_error)?; - - Ok(CoreConversionOptions { page_size }) -} - -fn to_napi_error(error: minipdf::MiniPdfError) -> Error { - let status = match &error { - minipdf::MiniPdfError::InvalidInput(_) | minipdf::MiniPdfError::UnsupportedFormat => { - Status::InvalidArg - } - _ => Status::GenericFailure, - }; - Error::new(status, error.to_string()) -} - -fn catch_core_panic(operation: impl FnOnce() -> T) -> Result { - catch_unwind(AssertUnwindSafe(operation)).map_err(|_| { - Error::new( - Status::GenericFailure, - "MiniPdf core operation panicked".to_owned(), - ) - }) -} diff --git a/minipdf-node/test/index.test.js b/minipdf-node/test/index.test.js deleted file mode 100644 index 199bf9f3..00000000 --- a/minipdf-node/test/index.test.js +++ /dev/null @@ -1,155 +0,0 @@ -'use strict' - -const assert = require('node:assert/strict') -const fs = require('node:fs') -const os = require('node:os') -const path = require('node:path') -const test = require('node:test') - -const minipdf = require('../lib/index.js') -const packageJson = require('../package.json') -const { postprocessLoader } = require('../scripts/postprocess-loader.js') -const { prepareRelease } = require('../scripts/prepare-release.js') - -const generatedNativePackages = [ - 'minipdf-darwin-arm64', - 'minipdf-darwin-x64', - 'minipdf-linux-arm64-gnu', - 'minipdf-linux-arm64-musl', - 'minipdf-linux-x64-gnu', - 'minipdf-linux-x64-musl', - 'minipdf-win32-arm64-msvc', - 'minipdf-win32-x64-msvc' -] - -const expectedNativePackages = generatedNativePackages.map((name) => - name === 'minipdf-win32-x64-msvc' - ? '@mini-software/minipdf-win32-x64-msvc' - : name -) - -const fixturePath = path.join( - __dirname, - '..', - '..', - 'tests', - 'Issue_Files', - 'docx', - 'Invoice.docx' -) - -test('detects Office format from a Buffer', () => { - const input = fs.readFileSync(fixturePath) - assert.equal(minipdf.detectOfficeFormat(input), 'docx') -}) - -test('converts path and Buffer inputs to PDF', () => { - const input = fs.readFileSync(fixturePath) - const fromBuffer = minipdf.convertBytesToPdf(input) - const fromPath = minipdf.convertToPdfBytes(fixturePath, { - pageSize: minipdf.PageSize.A4 - }) - - assert.equal(fromBuffer.subarray(0, 8).toString(), '%PDF-1.4') - assert.equal(fromPath.subarray(0, 8).toString(), '%PDF-1.4') - if (process.platform === 'win32') { - assert.equal( - minipdf.registeredFonts().filter((font) => font.name === 'arial').length, - 1 - ) - } -}) - -test('writes converted PDF to an output path', (context) => { - const outputDirectory = fs.mkdtempSync(path.join(os.tmpdir(), 'minipdf-node-')) - context.after(() => fs.rmSync(outputDirectory, { recursive: true, force: true })) - - const outputPath = path.join(outputDirectory, 'invoice.pdf') - minipdf.convertToPdf(fixturePath, outputPath) - - assert.equal(fs.readFileSync(outputPath).subarray(0, 8).toString(), '%PDF-1.4') -}) - -test('rejects invalid custom page dimensions', () => { - assert.throws( - () => minipdf.convertToPdfBytes(fixturePath, { - pageSize: { width: 0, height: 841.89 } - }), - (error) => { - assert.equal(error.code, 'InvalidArg') - assert.match(error.message, /page width and height must be positive finite values/) - return true - } - ) -}) - -test('is configured for public publication', () => { - assert.equal(packageJson.private, undefined) - assert.equal(packageJson.publishConfig.access, 'public') - assert.equal(packageJson.optionalDependencies, undefined) -}) - -test('registers fonts through the protected native boundary', () => { - minipdf.registerFont('TestFont', Buffer.from([0, 1, 2, 3])) - - assert.ok(minipdf.registeredFonts().some((font) => font.name === 'TestFont')) -}) - -test('keeps native loader diagnostics compatible with Node 18', () => { - const loaderPath = path.join(__dirname, '..', 'index.js') - const loader = fs.readFileSync(loaderPath, 'utf8') - - assert.doesNotMatch(loader, /which ldd|readFileSync/) - assert.doesNotMatch(loader, /require\('minipdf-win32-x64-msvc'\)/) - assert.match(loader, /require\('@mini-software\/minipdf-win32-x64-msvc'\)/) - assert.match(loader, /Failed to load MiniPdf native binding for \$\{platform\}\/\$\{arch\}/) - assert.equal(postprocessLoader(loader), loader) -}) - -test('prepares aligned platform packages for release', (context) => { - const packageRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'minipdf-release-')) - context.after(() => fs.rmSync(packageRoot, { recursive: true, force: true })) - - fs.writeFileSync( - path.join(packageRoot, 'package.json'), - JSON.stringify({ name: 'minipdf', version: '0.1.0' }) - ) - fs.writeFileSync(path.join(packageRoot, 'LICENSE'), 'license text') - fs.copyFileSync(path.join(__dirname, '..', 'index.js'), path.join(packageRoot, 'index.js')) - - for (const packageName of generatedNativePackages) { - const platformDirectory = path.join( - packageRoot, - 'npm', - packageName.replace('minipdf-', '') - ) - fs.mkdirSync(platformDirectory, { recursive: true }) - fs.writeFileSync( - path.join(platformDirectory, 'package.json'), - JSON.stringify({ name: packageName, version: '0.1.0' }) - ) - } - - const dependencies = prepareRelease(packageRoot) - const preparedPackage = JSON.parse( - fs.readFileSync(path.join(packageRoot, 'package.json'), 'utf8') - ) - - const expectedDependencies = Object.fromEntries( - expectedNativePackages.map((name) => [name, '0.1.0']) - ) - assert.deepEqual(dependencies, expectedDependencies) - assert.deepEqual(preparedPackage.optionalDependencies, expectedDependencies) - const windowsX64Package = JSON.parse( - fs.readFileSync(path.join(packageRoot, 'npm', 'win32-x64-msvc', 'package.json'), 'utf8') - ) - assert.equal(windowsX64Package.name, '@mini-software/minipdf-win32-x64-msvc') - assert.match( - fs.readFileSync(path.join(packageRoot, 'index.js'), 'utf8'), - /require\('@mini-software\/minipdf-win32-x64-msvc'\)/ - ) - assert.equal( - fs.readFileSync(path.join(packageRoot, 'npm', 'darwin-arm64', 'LICENSE'), 'utf8'), - 'license text' - ) -}) diff --git a/minipdf-python/LICENSE b/minipdf-python/LICENSE deleted file mode 100644 index fea296d8..00000000 --- a/minipdf-python/LICENSE +++ /dev/null @@ -1,200 +0,0 @@ - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship made available under - the License, as indicated by a copyright notice that is included in - or attached to the work (an example is provided in the Appendix below). - - "Derivative Works" shall mean any form of the Work that is based on - (or derived from) the Work and for which the editorial revisions, - annotations, elaborations, or other modifications represent, as a whole, - an original work of authorship. For the purposes of this License, - Derivative Works shall not include works that remain separable from, - or merely link (or bind by name) to the interfaces of, the Work and - Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright [yyyy] [name of copyright owner] - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. diff --git a/minipdf-python/README.md b/minipdf-python/README.md deleted file mode 100644 index 39bdd990..00000000 --- a/minipdf-python/README.md +++ /dev/null @@ -1,66 +0,0 @@ -# MiniPdf for Python - -MiniPdf converts basic DOCX, XLSX, and PPTX content to PDF 1.4 without -requiring Microsoft Office or LibreOffice. Conversion runs through the Rust -MiniPdf engine in `minipdf-rs` via the PyO3 extension `minipdf._native`, which -the package build backend compiles from [`native/`](native/). A pure Python -renderer with reduced feature coverage remains as a fallback for source-tree -runs where the extension has not been built. - -The package requires Python 3.10 or later, and building it requires a Rust -toolchain. - -## Native Rust Engine - -`minipdf._native` is a PyO3 extension that delegates conversion to the Rust -engine in `minipdf-rs`. When the module is importable, the Python API uses it -automatically and the pure Python renderers are only used as a fallback. - -Installing the package builds the extension: - -```bash -pip install . -``` - -To rebuild only the extension into the package source tree, use PowerShell: - -```powershell -scripts/Build-Python-Native.ps1 -``` - -The visual benchmark runner builds the extension automatically. - -## Install - -```bash -pip install minipdf -``` - -## Python API - -```python -import minipdf - -minipdf.convert_to_pdf("report.docx", "report.pdf") -pdf_bytes = minipdf.convert_to_pdf_bytes("report.docx") -``` - -## Command Line - -```bash -minipdf report.docx -minipdf workbook.xlsx -o workbook.pdf -minipdf slides.pptx -o slides.pdf -minipdf convert report.docx -o report.pdf -minipdf report.docx --paper-size a4 -minipdf report.docx --page-width 400 --page-height 500 -``` - -## Initial Scope - -Version 0.1 supports document page geometry, margins, paragraphs, explicit page -breaks, and basic bold, italic, and font-size run formatting. Text currently -uses PDF built-in Latin fonts. Tables, images, embedded fonts, CJK/RTL shaping, -headers, footers, and lists are not yet supported. XLSX rendering currently -extracts common cell value types into text rows, while PPTX rendering extracts -paragraph text and preserves slide page dimensions and boundaries. diff --git a/minipdf-python/native/Cargo.lock b/minipdf-python/native/Cargo.lock deleted file mode 100644 index 21720110..00000000 --- a/minipdf-python/native/Cargo.lock +++ /dev/null @@ -1,886 +0,0 @@ -# This file is automatically @generated by Cargo. -# It is not intended for manual editing. -version = 4 - -[[package]] -name = "adler2" -version = "2.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" - -[[package]] -name = "android_system_properties" -version = "0.1.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ae221649c9976a6f6c56ae1facf410f3ddb33cc661c4b7b61020a912d4237fbc" -dependencies = [ - "libc", -] - -[[package]] -name = "arbitrary" -version = "1.4.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c3d036a3c4ab069c7b410a2ce876bd74808d2d0888a82667669f8e783a898bf1" -dependencies = [ - "derive_arbitrary", -] - -[[package]] -name = "arrayvec" -version = "0.7.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d3fb67a6e08acf24fdeccbac2cb6ac4305825bd1f117462e0e6f2f193345ad56" - -[[package]] -name = "autocfg" -version = "1.5.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" - -[[package]] -name = "bitflags" -version = "2.13.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" - -[[package]] -name = "bumpalo" -version = "3.20.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649" - -[[package]] -name = "bytemuck" -version = "1.25.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "95832e849adfb21180ccb6826a99da14e5d266ae5c2e668e1602cf234f153797" -dependencies = [ - "bytemuck_derive", -] - -[[package]] -name = "bytemuck_derive" -version = "1.12.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6a1f896587b6f2c069c73d2f0913e2d590c3990285cd2f0b6aa02b786b4c679c" -dependencies = [ - "proc-macro2", - "quote", - "syn 3.0.6", -] - -[[package]] -name = "byteorder-lite" -version = "0.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8f1fe948ff07f4bd06c30984e69f5b4899c516a3ef74f34df92a2df2ab535495" - -[[package]] -name = "cc" -version = "1.4.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "54413ede23c2daf518f35156dfde027feb2374004d63bd497f983c8db9c0e313" -dependencies = [ - "find-msvc-tools", - "shlex", -] - -[[package]] -name = "cfg-if" -version = "1.0.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" - -[[package]] -name = "chrono" -version = "0.4.45" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1aa79e62e7697b8e29b513a68abacf485adcd1fe8284a4316c5ae868e6633327" -dependencies = [ - "iana-time-zone", - "num-traits", - "windows-link", -] - -[[package]] -name = "core-foundation-sys" -version = "0.8.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" - -[[package]] -name = "core_maths" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "77745e017f5edba1a9c1d854f6f3a52dac8a12dd5af5d2f54aecf61e43d80d30" -dependencies = [ - "libm", -] - -[[package]] -name = "crc32fast" -version = "1.5.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "01a7799fd6b852db0e61728dde9a204c423b44d689dbd432522543614b490e78" -dependencies = [ - "cfg-if", -] - -[[package]] -name = "crossbeam-utils" -version = "0.8.23" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a31eee39dddec8330830986fcd7625edb5a24ec90ea038215273bbc3adb08ac6" - -[[package]] -name = "derive_arbitrary" -version = "1.4.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1e567bd82dcff979e4b03460c307b3cdc9e96fde3d73bed1496d2bc75d9dd62a" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.119", -] - -[[package]] -name = "displaydoc" -version = "0.2.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c6232dd377dcc64799954cbd3a9bb882e9cdc1308ccd87b1c098f1fb2eaf82a8" -dependencies = [ - "proc-macro2", - "quote", - "syn 3.0.6", -] - -[[package]] -name = "equivalent" -version = "1.0.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f" - -[[package]] -name = "euclid" -version = "0.22.14" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f1a05365e3b1c6d1650318537c7460c6923f1abdd272ad6842baa2b509957a06" -dependencies = [ - "num-traits", -] - -[[package]] -name = "fdeflate" -version = "0.3.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1e6853b52649d4ac5c0bd02320cddc5ba956bdb407c4b75a2c6b75bf51500f8c" -dependencies = [ - "simd-adler32", -] - -[[package]] -name = "find-msvc-tools" -version = "0.1.13" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ef25905e51abafe4dcea6c15fec58c57b601cdbd0ee53d22ea1d3016c587d39b" - -[[package]] -name = "flate2" -version = "1.1.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6e634e2e0ebac1ee034020da1ca582e17ffe4e0f5e985823721e168928136dcb" -dependencies = [ - "crc32fast", - "miniz_oxide 0.9.1", - "zlib-rs", -] - -[[package]] -name = "font-types" -version = "0.10.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "39a654f404bbcbd48ea58c617c2993ee91d1cb63727a37bf2323a4edeed1b8c5" -dependencies = [ - "bytemuck", -] - -[[package]] -name = "futures-core" -version = "0.3.34" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" - -[[package]] -name = "futures-task" -version = "0.3.34" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd" - -[[package]] -name = "futures-util" -version = "0.3.34" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" -dependencies = [ - "futures-core", - "futures-task", - "pin-project-lite", - "slab", -] - -[[package]] -name = "hashbrown" -version = "0.17.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" - -[[package]] -name = "heck" -version = "0.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" - -[[package]] -name = "iana-time-zone" -version = "0.1.65" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e31bc9ad994ba00e440a8aa5c9ef0ec67d5cb5e5cb0cc7f8b744a35b389cc470" -dependencies = [ - "android_system_properties", - "core-foundation-sys", - "iana-time-zone-haiku", - "js-sys", - "log", - "wasm-bindgen", - "windows-core", -] - -[[package]] -name = "iana-time-zone-haiku" -version = "0.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f31827a206f56af32e590ba56d5d2d085f558508192593743f16b2306495269f" -dependencies = [ - "cc", -] - -[[package]] -name = "image" -version = "0.25.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "85ab80394333c02fe689eaf900ab500fbd0c2213da414687ebf995a65d5a6104" -dependencies = [ - "bytemuck", - "byteorder-lite", - "moxcms", - "num-traits", - "png", -] - -[[package]] -name = "indexmap" -version = "2.14.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" -dependencies = [ - "equivalent", - "hashbrown", -] - -[[package]] -name = "indoc" -version = "2.0.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "79cf5c93f93228cf8efb3ba362535fb11199ac548a09ce117c9b1adc3030d706" -dependencies = [ - "rustversion", -] - -[[package]] -name = "js-sys" -version = "0.3.105" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ce57d20d1ea864ce2ac172ab472d409214f4fd359f0b2a2775abdf522e2af99e" -dependencies = [ - "cfg-if", - "futures-util", - "wasm-bindgen", -] - -[[package]] -name = "kurbo" -version = "0.12.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ce9729cc38c18d86123ab736fd2e7151763ba226ac2490ec092d1dd148825e32" -dependencies = [ - "arrayvec", - "euclid", - "smallvec", -] - -[[package]] -name = "libc" -version = "0.2.189" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3eaf3ede3fee6db1a4c2ee091bf8a8b4dccdc6d17f656fb07896ee72867612f2" - -[[package]] -name = "libm" -version = "0.2.16" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981" - -[[package]] -name = "log" -version = "0.4.34" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6" - -[[package]] -name = "memchr" -version = "2.8.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" - -[[package]] -name = "memoffset" -version = "0.9.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "488016bfae457b036d996092f6cb448677611ce4449e970ceaf42695203f218a" -dependencies = [ - "autocfg", -] - -[[package]] -name = "minipdf" -version = "0.7.0" -dependencies = [ - "chrono", - "flate2", - "image", - "roxmltree", - "rustybuzz", - "subsetter", - "thiserror", - "ttf-parser", - "unicode-bidi", - "windows-sys", - "zip", -] - -[[package]] -name = "minipdf-python-native" -version = "0.7.0" -dependencies = [ - "minipdf", - "pyo3", -] - -[[package]] -name = "miniz_oxide" -version = "0.8.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1fa76a2c86f704bdb222d66965fb3d63269ce38518b83cb0575fca855ebb6316" -dependencies = [ - "adler2", - "simd-adler32", -] - -[[package]] -name = "miniz_oxide" -version = "0.9.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b63fbc4a50860e98e7b2aa7804ded1db5cbc3aff9193adaff57a6931bf7c4b4c" -dependencies = [ - "adler2", - "simd-adler32", -] - -[[package]] -name = "moxcms" -version = "0.8.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bb85c154ba489f01b25c0d36ae69a87e4a1c73a72631fc6c0eb6dde34a73e44b" -dependencies = [ - "num-traits", - "pxfm", -] - -[[package]] -name = "num-traits" -version = "0.2.19" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" -dependencies = [ - "autocfg", -] - -[[package]] -name = "once_cell" -version = "1.21.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" - -[[package]] -name = "pin-project-lite" -version = "0.2.17" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" - -[[package]] -name = "png" -version = "0.18.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "60769b8b31b2a9f263dae2776c37b1b28ae246943cf719eb6946a1db05128a61" -dependencies = [ - "bitflags", - "crc32fast", - "fdeflate", - "flate2", - "miniz_oxide 0.8.9", -] - -[[package]] -name = "portable-atomic" -version = "1.15.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "05c8b63e8d9609db387f0324918f81d68fe27748f084ef092fb35954d0539a85" - -[[package]] -name = "proc-macro2" -version = "1.0.107" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" -dependencies = [ - "unicode-ident", -] - -[[package]] -name = "pxfm" -version = "0.1.30" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d55d956fa96f5ec02be2e13af0e20391a5aa83d6a074e3ad368959d0fab299ea" - -[[package]] -name = "pyo3" -version = "0.25.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8970a78afe0628a3e3430376fc5fd76b6b45c4d43360ffd6cdd40bdde72b682a" -dependencies = [ - "indoc", - "libc", - "memoffset", - "once_cell", - "portable-atomic", - "pyo3-build-config", - "pyo3-ffi", - "pyo3-macros", - "unindent", -] - -[[package]] -name = "pyo3-build-config" -version = "0.25.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "458eb0c55e7ece017adeba38f2248ff3ac615e53660d7c71a238d7d2a01c7598" -dependencies = [ - "once_cell", - "target-lexicon", -] - -[[package]] -name = "pyo3-ffi" -version = "0.25.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7114fe5457c61b276ab77c5055f206295b812608083644a5c5b2640c3102565c" -dependencies = [ - "libc", - "pyo3-build-config", -] - -[[package]] -name = "pyo3-macros" -version = "0.25.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a8725c0a622b374d6cb051d11a0983786448f7785336139c3c94f5aa6bef7e50" -dependencies = [ - "proc-macro2", - "pyo3-macros-backend", - "quote", - "syn 2.0.119", -] - -[[package]] -name = "pyo3-macros-backend" -version = "0.25.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4109984c22491085343c05b0dbc54ddc405c3cf7b4374fc533f5c3313a572ccc" -dependencies = [ - "heck", - "proc-macro2", - "pyo3-build-config", - "quote", - "syn 2.0.119", -] - -[[package]] -name = "quote" -version = "1.0.47" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" -dependencies = [ - "proc-macro2", -] - -[[package]] -name = "read-fonts" -version = "0.35.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6717cf23b488adf64b9d711329542ba34de147df262370221940dfabc2c91358" -dependencies = [ - "bytemuck", - "font-types", -] - -[[package]] -name = "roxmltree" -version = "0.20.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6c20b6793b5c2fa6553b250154b78d6d0db37e72700ae35fad9387a46f487c97" - -[[package]] -name = "rustc-hash" -version = "2.1.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d" - -[[package]] -name = "rustversion" -version = "1.0.23" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" - -[[package]] -name = "rustybuzz" -version = "0.20.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fd3c7c96f8a08ee34eff8857b11b49b07d71d1c3f4e88f8a88d4c9e9f90b1702" -dependencies = [ - "bitflags", - "bytemuck", - "core_maths", - "log", - "smallvec", - "ttf-parser", - "unicode-bidi-mirroring", - "unicode-ccc", - "unicode-properties", - "unicode-script", -] - -[[package]] -name = "shlex" -version = "2.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" - -[[package]] -name = "simd-adler32" -version = "0.3.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea" - -[[package]] -name = "skrifa" -version = "0.37.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8c31071dedf532758ecf3fed987cdb4bd9509f900e026ab684b4ecb81ea49841" -dependencies = [ - "bytemuck", - "read-fonts", -] - -[[package]] -name = "slab" -version = "0.4.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" - -[[package]] -name = "smallvec" -version = "1.16.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ba467056f1b547ed52077911161fc86985becbc60e8e1857c8a144dab0def891" - -[[package]] -name = "subsetter" -version = "0.2.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cb6895a12ac5599bb6057362f00e8a3cf1daab4df33f553a55690a44e4fed8d0" -dependencies = [ - "kurbo", - "rustc-hash", - "skrifa", - "write-fonts", -] - -[[package]] -name = "syn" -version = "2.0.119" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" -dependencies = [ - "proc-macro2", - "quote", - "unicode-ident", -] - -[[package]] -name = "syn" -version = "3.0.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8593e8e72159ed2257d083c7a454a85cbf854f37a0966d8d483aff8c8a3ebcee" -dependencies = [ - "proc-macro2", - "quote", - "unicode-ident", -] - -[[package]] -name = "target-lexicon" -version = "0.13.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "adb6935a6f5c20170eeceb1a3835a49e12e19d792f6dd344ccc76a985ca5a6ca" - -[[package]] -name = "thiserror" -version = "2.0.20" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ec86235f5fcc2a73650310756d2ac5b138a5780bbbdfae3eeccec992c435ba4f" -dependencies = [ - "thiserror-impl", -] - -[[package]] -name = "thiserror-impl" -version = "2.0.20" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bc04cd3e1236dd4a98afca4569f2deb3f120e5422a4023be2cb683f8486292af" -dependencies = [ - "proc-macro2", - "quote", - "syn 3.0.6", -] - -[[package]] -name = "ttf-parser" -version = "0.25.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d2df906b07856748fa3f6e0ad0cbaa047052d4a7dd609e231c4f72cee8c36f31" -dependencies = [ - "core_maths", -] - -[[package]] -name = "unicode-bidi" -version = "0.3.18" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5c1cb5db39152898a79168971543b1cb5020dff7fe43c8dc468b0885f5e29df5" - -[[package]] -name = "unicode-bidi-mirroring" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5dfa6e8c60bb66d49db113e0125ee8711b7647b5579dc7f5f19c42357ed039fe" - -[[package]] -name = "unicode-ccc" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ce61d488bcdc9bc8b5d1772c404828b17fc481c0a582b5581e95fb233aef503e" - -[[package]] -name = "unicode-ident" -version = "1.0.26" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d245f478577f809a851594d02313b640fb437e0bb33866753cff937863096954" - -[[package]] -name = "unicode-properties" -version = "0.1.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7df058c713841ad818f1dc5d3fd88063241cc61f49f5fbea4b951e8cf5a8d71d" - -[[package]] -name = "unicode-script" -version = "0.5.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "383ad40bb927465ec0ce7720e033cb4ca06912855fc35db31b5755d0de75b1ee" - -[[package]] -name = "unindent" -version = "0.2.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7264e107f553ccae879d21fbea1d6724ac785e8c3bfc762137959b5802826ef3" - -[[package]] -name = "wasm-bindgen" -version = "0.2.128" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "aecb87a33d3b0c5e3b7aa46336eaf486cffafbd281b195e4c8b80d50df2351bf" -dependencies = [ - "cfg-if", - "once_cell", - "rustversion", - "wasm-bindgen-macro", - "wasm-bindgen-shared", -] - -[[package]] -name = "wasm-bindgen-macro" -version = "0.2.128" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a690d511e3c1a8b3a55e33511e3c2c00c78415cd23650f32b808627f5696b9ed" -dependencies = [ - "quote", - "wasm-bindgen-macro-support", -] - -[[package]] -name = "wasm-bindgen-macro-support" -version = "0.2.128" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "411e4887f0071ef2d2164a9d5fdf2d20efbef78fccd3a78b0c10a1dc5295e48a" -dependencies = [ - "bumpalo", - "proc-macro2", - "quote", - "syn 3.0.6", - "wasm-bindgen-shared", -] - -[[package]] -name = "wasm-bindgen-shared" -version = "0.2.128" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "81941cd78d0c92026c33e5e01312845a4cb1e9af3407f9134b100dd03144103e" -dependencies = [ - "unicode-ident", -] - -[[package]] -name = "windows-core" -version = "0.62.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb" -dependencies = [ - "windows-implement", - "windows-interface", - "windows-link", - "windows-result", - "windows-strings", -] - -[[package]] -name = "windows-implement" -version = "0.60.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.119", -] - -[[package]] -name = "windows-interface" -version = "0.59.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.119", -] - -[[package]] -name = "windows-link" -version = "0.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" - -[[package]] -name = "windows-result" -version = "0.4.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5" -dependencies = [ - "windows-link", -] - -[[package]] -name = "windows-strings" -version = "0.5.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091" -dependencies = [ - "windows-link", -] - -[[package]] -name = "windows-sys" -version = "0.61.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" -dependencies = [ - "windows-link", -] - -[[package]] -name = "write-fonts" -version = "0.43.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "886614b5ce857341226aa091f3c285e450683894acaaa7887f366c361efef79d" -dependencies = [ - "font-types", - "indexmap", - "kurbo", - "log", - "read-fonts", -] - -[[package]] -name = "zip" -version = "2.4.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fabe6324e908f85a1c52063ce7aa26b68dcb7eb6dbc83a2d148403c9bc3eba50" -dependencies = [ - "arbitrary", - "crc32fast", - "crossbeam-utils", - "displaydoc", - "flate2", - "indexmap", - "memchr", - "thiserror", - "zopfli", -] - -[[package]] -name = "zlib-rs" -version = "0.6.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b268e58e7c693d7c271f93ffc4ba3b380412554231c85bf61ca7af91042a4112" - -[[package]] -name = "zopfli" -version = "0.8.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f05cd8797d63865425ff89b5c4a48804f35ba0ce8d125800027ad6017d2b5249" -dependencies = [ - "bumpalo", - "crc32fast", - "log", - "simd-adler32", -] diff --git a/minipdf-python/native/Cargo.toml b/minipdf-python/native/Cargo.toml deleted file mode 100644 index b821cbb7..00000000 --- a/minipdf-python/native/Cargo.toml +++ /dev/null @@ -1,20 +0,0 @@ -[package] -name = "minipdf-python-native" -version = "0.7.0" -edition = "2021" -license = "Apache-2.0" -repository = "https://github.com/mini-software/MiniPdf" -description = "Native Rust engine bindings for the MiniPdf Python package." -publish = false - -[lib] -name = "_native" -crate-type = ["cdylib"] - -[dependencies] -minipdf = { path = "../../minipdf-rs/crates/minipdf" } -pyo3 = { version = "0.25", features = ["abi3-py310"] } - -[profile.release] -lto = true -strip = "symbols" diff --git a/minipdf-python/native/src/lib.rs b/minipdf-python/native/src/lib.rs deleted file mode 100644 index 51571396..00000000 --- a/minipdf-python/native/src/lib.rs +++ /dev/null @@ -1,87 +0,0 @@ -//! PyO3 bindings over the Rust MiniPdf engine. -//! -//! The extension is installed as the `minipdf._native` submodule. The Python -//! package prefers this module for conversion and falls back to the pure -//! Python renderers when it is not importable. - -use std::path::Path; - -use pyo3::exceptions::PyValueError; -use pyo3::prelude::*; -use pyo3::types::PyList; - -use minipdf::ConversionOptions as CoreOptions; -use minipdf::PageSize as CorePageSize; - -fn to_py_err(error: minipdf::MiniPdfError) -> PyErr { - PyValueError::new_err(error.to_string()) -} - -fn to_options(page_size: Option<(f64, f64)>) -> PyResult { - let Some((width, height)) = page_size else { - return Ok(CoreOptions::default()); - }; - let page_size = CorePageSize::new(width as f32, height as f32).map_err(to_py_err)?; - Ok(CoreOptions { - page_size: Some(page_size), - }) -} - -fn prepare_fonts() -> PyResult<()> { - minipdf::register_system_fonts().map_err(to_py_err) -} - -#[pyfunction] -#[pyo3(signature = (data, page_size=None))] -fn convert_bytes_to_pdf(data: &[u8], page_size: Option<(f64, f64)>) -> PyResult> { - prepare_fonts()?; - minipdf::convert_bytes_to_pdf_with_options(data, &to_options(page_size)?).map_err(to_py_err) -} - -#[pyfunction] -#[pyo3(signature = (input_path, output_path, page_size=None))] -fn convert_to_pdf( - input_path: &str, - output_path: &str, - page_size: Option<(f64, f64)>, -) -> PyResult<()> { - prepare_fonts()?; - minipdf::convert_to_pdf_with_options( - Path::new(input_path), - Path::new(output_path), - &to_options(page_size)?, - ) - .map_err(to_py_err) -} - -#[pyfunction] -#[pyo3(signature = (input_path, page_size=None))] -fn convert_to_pdf_bytes(input_path: &str, page_size: Option<(f64, f64)>) -> PyResult> { - prepare_fonts()?; - minipdf::convert_to_pdf_bytes_with_options(Path::new(input_path), &to_options(page_size)?) - .map_err(to_py_err) -} - -#[pyfunction] -fn register_font(name: &str, data: &[u8]) { - minipdf::register_font(name.to_owned(), data.to_vec()); -} - -#[pyfunction] -fn registered_fonts(py: Python<'_>) -> PyResult> { - let list = PyList::empty(py); - for font in minipdf::registered_fonts() { - list.append((font.name, font.data))?; - } - Ok(list.into()) -} - -#[pymodule] -fn _native(_py: Python<'_>, module: &Bound<'_, PyModule>) -> PyResult<()> { - module.add_function(wrap_pyfunction!(convert_bytes_to_pdf, module)?)?; - module.add_function(wrap_pyfunction!(convert_to_pdf, module)?)?; - module.add_function(wrap_pyfunction!(convert_to_pdf_bytes, module)?)?; - module.add_function(wrap_pyfunction!(register_font, module)?)?; - module.add_function(wrap_pyfunction!(registered_fonts, module)?)?; - Ok(()) -} diff --git a/minipdf-python/pyproject.toml b/minipdf-python/pyproject.toml deleted file mode 100644 index 80412827..00000000 --- a/minipdf-python/pyproject.toml +++ /dev/null @@ -1,62 +0,0 @@ -[build-system] -requires = ["maturin>=1.8,<2.0"] -build-backend = "maturin" - -[project] -name = "minipdf" -version = "0.7.0" -description = "Office-to-PDF conversion engine backed by the Rust MiniPdf core" -readme = "README.md" -requires-python = ">=3.10" -license = "Apache-2.0" -license-files = ["LICENSE"] -authors = [{ name = "MiniPdf contributors" }] -classifiers = [ - "Development Status :: 2 - Pre-Alpha", - "Programming Language :: Python :: 3", - "Programming Language :: Python :: 3 :: Only", - "Programming Language :: Python :: 3.10", - "Programming Language :: Python :: 3.11", - "Programming Language :: Python :: 3.12", - "Programming Language :: Python :: 3.13", - "Programming Language :: Rust", -] - -[project.optional-dependencies] -dev = [ - "build>=1.2", - "mypy>=1.11", - "pypdf>=5", - "pytest>=8", - "ruff>=0.9", - "twine>=6", -] - -[project.scripts] -minipdf = "minipdf.cli:main" - -[project.urls] -Homepage = "https://github.com/mini-software/MiniPdf" -Repository = "https://github.com/mini-software/MiniPdf" - -[tool.maturin] -manifest-path = "native/Cargo.toml" -module-name = "minipdf._native" -python-source = "src" -features = ["pyo3/extension-module"] - -[tool.pytest.ini_options] -addopts = "-ra" -pythonpath = ["src"] -testpaths = ["tests"] - -[tool.ruff] -line-length = 100 -target-version = "py310" - -[tool.ruff.lint] -select = ["E", "F", "I", "UP", "B", "SIM"] - -[tool.mypy] -python_version = "3.10" -strict = true diff --git a/minipdf-python/src/minipdf/__init__.py b/minipdf-python/src/minipdf/__init__.py deleted file mode 100644 index 40ec87c8..00000000 --- a/minipdf-python/src/minipdf/__init__.py +++ /dev/null @@ -1,28 +0,0 @@ -from .api import ( - convert_bytes_to_pdf, - convert_to_pdf, - convert_to_pdf_bytes, - register_font, - registered_fonts, -) -from .errors import InvalidInputError, MiniPdfError, PackageError, UnsupportedFormatError -from .office import OfficeFormat, detect_office_format -from .options import ConversionOptions, PageSize - -__all__ = [ - "ConversionOptions", - "InvalidInputError", - "MiniPdfError", - "OfficeFormat", - "PackageError", - "PageSize", - "UnsupportedFormatError", - "convert_bytes_to_pdf", - "convert_to_pdf", - "convert_to_pdf_bytes", - "detect_office_format", - "register_font", - "registered_fonts", -] - -__version__ = "0.7.0" diff --git a/minipdf-python/src/minipdf/__main__.py b/minipdf-python/src/minipdf/__main__.py deleted file mode 100644 index eb53e2f3..00000000 --- a/minipdf-python/src/minipdf/__main__.py +++ /dev/null @@ -1,3 +0,0 @@ -from .cli import main - -raise SystemExit(main()) diff --git a/minipdf-python/src/minipdf/_native.pyi b/minipdf-python/src/minipdf/_native.pyi deleted file mode 100644 index f24e25a3..00000000 --- a/minipdf-python/src/minipdf/_native.pyi +++ /dev/null @@ -1,19 +0,0 @@ -# Type stub for the optional native extension `minipdf._native`, built from -# `minipdf-python/native`. At runtime the module is imported dynamically and -# is absent unless the extension has been built and installed. - -def convert_bytes_to_pdf( - data: bytes, - page_size: tuple[float, float] | None = None, -) -> bytes: ... -def convert_to_pdf( - input_path: str, - output_path: str, - page_size: tuple[float, float] | None = None, -) -> None: ... -def convert_to_pdf_bytes( - input_path: str, - page_size: tuple[float, float] | None = None, -) -> bytes: ... -def register_font(name: str, data: bytes) -> None: ... -def registered_fonts() -> list[tuple[str, bytes]]: ... diff --git a/minipdf-python/src/minipdf/api.py b/minipdf-python/src/minipdf/api.py deleted file mode 100644 index f4757502..00000000 --- a/minipdf-python/src/minipdf/api.py +++ /dev/null @@ -1,82 +0,0 @@ -from __future__ import annotations - -import importlib -import os -from pathlib import Path -from threading import RLock -from typing import Any - -from .docx import convert_docx -from .errors import MiniPdfError, UnsupportedFormatError -from .office import OfficeFormat, detect_office_format -from .options import ConversionOptions -from .pptx import convert_pptx -from .xlsx import convert_xlsx - -try: - _native: Any = importlib.import_module("minipdf._native") -except ImportError: - _native = None - -PathLike = str | os.PathLike[str] -_font_lock = RLock() -_fonts: list[tuple[str, bytes]] = [] - - -def register_font(name: str, font_data: bytes) -> None: - data = bytes(font_data) - with _font_lock: - _fonts.append((name, data)) - if _native is not None: - _native.register_font(name, data) - - -def registered_fonts() -> tuple[tuple[str, bytes], ...]: - if _native is not None: - return tuple(_native.registered_fonts()) - with _font_lock: - return tuple(_fonts) - - -def _page_size_argument(options: ConversionOptions) -> tuple[float, float] | None: - if options.page_size is None: - return None - return options.page_size.width, options.page_size.height - - -def convert_bytes_to_pdf( - data: bytes | bytearray | memoryview, - options: ConversionOptions | None = None, -) -> bytes: - source = bytes(data) - document_format = detect_office_format(source) - options = options or ConversionOptions() - if _native is not None: - if document_format is OfficeFormat.UNKNOWN: - raise UnsupportedFormatError("unsupported or unknown Office document format") - try: - return _native.convert_bytes_to_pdf(source, _page_size_argument(options)) - except Exception as error: - raise MiniPdfError(f"native conversion failed: {error}") from error - if document_format is OfficeFormat.DOCX: - return convert_docx(source, options) - if document_format is OfficeFormat.XLSX: - return convert_xlsx(source, options) - if document_format is OfficeFormat.PPTX: - return convert_pptx(source, options) - raise UnsupportedFormatError("unsupported or unknown Office document format") - - -def convert_to_pdf_bytes( - input_path: PathLike, - options: ConversionOptions | None = None, -) -> bytes: - return convert_bytes_to_pdf(Path(input_path).read_bytes(), options) - - -def convert_to_pdf( - input_path: PathLike, - output_path: PathLike, - options: ConversionOptions | None = None, -) -> None: - Path(output_path).write_bytes(convert_to_pdf_bytes(input_path, options)) diff --git a/minipdf-python/src/minipdf/cli.py b/minipdf-python/src/minipdf/cli.py deleted file mode 100644 index 65a0c12d..00000000 --- a/minipdf-python/src/minipdf/cli.py +++ /dev/null @@ -1,50 +0,0 @@ -from __future__ import annotations - -import argparse -import sys -from collections.abc import Sequence -from pathlib import Path - -from .api import convert_to_pdf -from .errors import MiniPdfError -from .options import ConversionOptions, PageSize - - -def _parser() -> argparse.ArgumentParser: - parser = argparse.ArgumentParser(prog="minipdf", description="Convert Office files to PDF.") - parser.add_argument("input", type=Path) - parser.add_argument("-o", "--output", type=Path) - parser.add_argument("--paper-size", choices=("a4", "letter")) - parser.add_argument("--page-width", type=float) - parser.add_argument("--page-height", type=float) - return parser - - -def _options(args: argparse.Namespace, parser: argparse.ArgumentParser) -> ConversionOptions: - custom_supplied = args.page_width is not None or args.page_height is not None - if args.paper_size and custom_supplied: - parser.error("use either --paper-size or --page-width/--page-height, not both") - if (args.page_width is None) != (args.page_height is None): - parser.error("--page-width and --page-height must be specified together") - if args.paper_size == "a4": - return ConversionOptions(PageSize.A4) - if args.paper_size == "letter": - return ConversionOptions(PageSize.LETTER) - if custom_supplied: - return ConversionOptions(PageSize(args.page_width, args.page_height)) - return ConversionOptions() - - -def main(argv: Sequence[str] | None = None) -> int: - arguments = list(sys.argv[1:] if argv is None else argv) - if arguments[:1] == ["convert"]: - arguments.pop(0) - parser = _parser() - args = parser.parse_args(arguments) - output = args.output or args.input.with_suffix(".pdf") - try: - convert_to_pdf(args.input, output, _options(args, parser)) - except (MiniPdfError, OSError, ValueError) as error: - parser.exit(1, f"Error: {error}\n") - print(output) - return 0 diff --git a/minipdf-python/src/minipdf/docx.py b/minipdf-python/src/minipdf/docx.py deleted file mode 100644 index 1f9f6d8d..00000000 --- a/minipdf-python/src/minipdf/docx.py +++ /dev/null @@ -1,146 +0,0 @@ -from __future__ import annotations - -import textwrap -import xml.etree.ElementTree as ET -from dataclasses import dataclass - -from .errors import PackageError -from .office import OfficePackage -from .options import ConversionOptions, PageSize -from .pdf import PdfDocument, TextStyle - -WORD_NS = "http://schemas.openxmlformats.org/wordprocessingml/2006/main" -W = f"{{{WORD_NS}}}" -DEFAULT_MARGIN = 54.0 - - -@dataclass(frozen=True, slots=True) -class Run: - text: str - style: TextStyle - - -@dataclass(frozen=True, slots=True) -class Paragraph: - runs: tuple[Run, ...] - page_break_before: bool = False - - -@dataclass(frozen=True, slots=True) -class Document: - paragraphs: tuple[Paragraph, ...] - page_size: PageSize - margins: tuple[float, float, float, float] - - -def _points(value: str | None, default: float) -> float: - if value is None: - return default - try: - return float(value) / 20.0 - except ValueError: - return default - - -def read_document(package: OfficePackage) -> Document: - document_xml = package.read("word/document.xml") - if document_xml is None: - raise PackageError("DOCX package is missing word/document.xml") - try: - root = ET.fromstring(document_xml) - except ET.ParseError as error: - raise PackageError("word/document.xml is malformed") from error - body = root.find(f"{W}body") - if body is None: - raise PackageError("word/document.xml is missing the document body") - - section = body.find(f"{W}sectPr") - size = section.find(f"{W}pgSz") if section is not None else None - margins = section.find(f"{W}pgMar") if section is not None else None - page_size = PageSize( - _points(size.get(f"{W}w") if size is not None else None, PageSize.A4.width), - _points(size.get(f"{W}h") if size is not None else None, PageSize.A4.height), - ) - page_margins = tuple( - _points(margins.get(f"{W}{name}") if margins is not None else None, DEFAULT_MARGIN) - for name in ("top", "right", "bottom", "left") - ) - - paragraphs: list[Paragraph] = [] - for paragraph_node in body.findall(f"{W}p"): - page_break = paragraph_node.find(f".//{W}pageBreakBefore") is not None - runs: list[Run] = [] - for run_node in paragraph_node.findall(f"{W}r"): - properties = run_node.find(f"{W}rPr") - size_node = properties.find(f"{W}sz") if properties is not None else None - style = TextStyle( - size=_points(size_node.get(f"{W}val") if size_node is not None else None, 11.0), - bold=properties is not None and properties.find(f"{W}b") is not None, - italic=properties is not None and properties.find(f"{W}i") is not None, - ) - chunks: list[str] = [] - for child in run_node: - if child.tag == f"{W}t": - chunks.append(child.text or "") - elif child.tag == f"{W}tab": - chunks.append("\t") - elif child.tag == f"{W}br": - break_type = child.get(f"{W}type") - if break_type == "page": - if chunks: - runs.append(Run("".join(chunks), style)) - chunks = [] - if runs: - paragraphs.append(Paragraph(tuple(runs), page_break)) - runs = [] - page_break = True - else: - chunks.append("\n") - if chunks: - runs.append(Run("".join(chunks), style)) - paragraphs.append(Paragraph(tuple(runs), page_break)) - - return Document(tuple(paragraphs), page_size, page_margins) # type: ignore[arg-type] - - -def render_document(document: Document, options: ConversionOptions) -> bytes: - page_size = options.page_size or document.page_size - top, right, bottom, left = document.margins - pdf = PdfDocument() - page = pdf.add_page(page_size.width, page_size.height) - cursor_y = page_size.height - top - available_width = page_size.width - left - right - - for paragraph in document.paragraphs: - if paragraph.page_break_before and page.operations: - page = pdf.add_page(page_size.width, page_size.height) - cursor_y = page_size.height - top - if not paragraph.runs: - cursor_y -= 16.0 - continue - for run in paragraph.runs: - average_width = max(run.style.size * 0.5, 1.0) - columns = max(1, int(available_width / average_width)) - lines = run.text.splitlines() or [""] - for source_line in lines: - wrapped = textwrap.wrap( - source_line, - width=columns, - replace_whitespace=False, - drop_whitespace=False, - break_long_words=True, - ) or [""] - for line in wrapped: - line_height = max(16.0, run.style.size * 1.2) - if cursor_y - line_height < bottom: - page = pdf.add_page(page_size.width, page_size.height) - cursor_y = page_size.height - top - cursor_y -= line_height - page.add_text(line, left, cursor_y, run.style) - cursor_y -= 5.6 - return pdf.to_bytes() - - -def convert_docx(data: bytes, options: ConversionOptions) -> bytes: - package = OfficePackage(data) - return render_document(read_document(package), options) diff --git a/minipdf-python/src/minipdf/errors.py b/minipdf-python/src/minipdf/errors.py deleted file mode 100644 index 0e4df9d9..00000000 --- a/minipdf-python/src/minipdf/errors.py +++ /dev/null @@ -1,14 +0,0 @@ -class MiniPdfError(Exception): - """Base exception for MiniPdf conversion failures.""" - - -class InvalidInputError(MiniPdfError, ValueError): - """Raised when an input or conversion option is invalid.""" - - -class UnsupportedFormatError(MiniPdfError): - """Raised when an Office package format is not supported.""" - - -class PackageError(MiniPdfError): - """Raised when an Office ZIP package is malformed or unsafe.""" diff --git a/minipdf-python/src/minipdf/office.py b/minipdf-python/src/minipdf/office.py deleted file mode 100644 index 976e00c7..00000000 --- a/minipdf-python/src/minipdf/office.py +++ /dev/null @@ -1,120 +0,0 @@ -from __future__ import annotations - -import io -import posixpath -import xml.etree.ElementTree as ET -import zipfile -from dataclasses import dataclass -from enum import Enum -from urllib.parse import unquote, urlsplit - -from .errors import PackageError - -MAX_ENTRY_SIZE = 64 * 1024 * 1024 -MAX_PACKAGE_SIZE = 256 * 1024 * 1024 - - -class OfficeFormat(Enum): - UNKNOWN = "unknown" - XLSX = "xlsx" - DOCX = "docx" - PPTX = "pptx" - - -@dataclass(frozen=True, slots=True) -class OfficeRelationship: - relationship_type: str - target: str - - -class OfficePackage: - def __init__(self, data: bytes) -> None: - try: - self._archive = zipfile.ZipFile(io.BytesIO(data)) - except (OSError, zipfile.BadZipFile) as error: - raise PackageError("input is not a valid Office ZIP package") from error - self._validate() - self._entries = { - entry.filename.replace("\\", "/"): entry for entry in self._archive.infolist() - } - - def _validate(self) -> None: - total_size = 0 - normalized_names: set[str] = set() - for entry in self._archive.infolist(): - normalized = entry.filename.replace("\\", "/") - parts = normalized.split("/") - if normalized.startswith("/") or ".." in parts: - raise PackageError(f"unsafe package path: {entry.filename}") - if normalized in normalized_names: - raise PackageError(f"duplicate package path: {entry.filename}") - normalized_names.add(normalized) - if entry.flag_bits & 0x1: - raise PackageError("encrypted Office packages are not supported") - if entry.file_size > MAX_ENTRY_SIZE: - raise PackageError(f"package entry is too large: {entry.filename}") - total_size += entry.file_size - if total_size > MAX_PACKAGE_SIZE: - raise PackageError("Office package expands beyond the safety limit") - - @property - def format(self) -> OfficeFormat: - roots = {name.split("/", 1)[0] for name in self._entries if "/" in name} - if "word" in roots: - return OfficeFormat.DOCX - if "xl" in roots: - return OfficeFormat.XLSX - if "ppt" in roots: - return OfficeFormat.PPTX - return OfficeFormat.UNKNOWN - - @property - def names(self) -> tuple[str, ...]: - return tuple(self._entries) - - def read(self, name: str) -> bytes | None: - entry = self._entries.get(name.replace("\\", "/")) - if entry is None: - return None - try: - return self._archive.read(entry) - except KeyError: - return None - except (OSError, RuntimeError, zipfile.BadZipFile) as error: - raise PackageError(f"cannot read package entry: {name}") from error - - def relationships(self, source_name: str) -> dict[str, OfficeRelationship]: - directory, filename = posixpath.split(source_name) - relationships_name = posixpath.join(directory, "_rels", f"{filename}.rels") - data = self.read(relationships_name) - if data is None: - return {} - try: - root = ET.fromstring(data) - except ET.ParseError as error: - raise PackageError(f"{relationships_name} is malformed") from error - - relationships: dict[str, OfficeRelationship] = {} - for node in root.iter(): - if node.tag.rsplit("}", 1)[-1] != "Relationship": - continue - relationship_id = node.get("Id") - relationship_type = node.get("Type") - target = node.get("Target") - if not relationship_id or not relationship_type or not target: - continue - if node.get("TargetMode", "").lower() == "external": - continue - target_path = unquote(urlsplit(target.replace("\\", "/")).path) - if target_path.startswith("/"): - resolved = posixpath.normpath(target_path.lstrip("/")) - else: - resolved = posixpath.normpath(posixpath.join(directory, target_path)) - if resolved == ".." or resolved.startswith("../"): - raise PackageError(f"unsafe relationship target: {target}") - relationships[relationship_id] = OfficeRelationship(relationship_type, resolved) - return relationships - - -def detect_office_format(data: bytes) -> OfficeFormat: - return OfficePackage(data).format diff --git a/minipdf-python/src/minipdf/options.py b/minipdf-python/src/minipdf/options.py deleted file mode 100644 index b25f575d..00000000 --- a/minipdf-python/src/minipdf/options.py +++ /dev/null @@ -1,38 +0,0 @@ -from __future__ import annotations - -import math -from dataclasses import dataclass -from typing import ClassVar - -from .errors import InvalidInputError - - -@dataclass(frozen=True, slots=True) -class PageSize: - """PDF page dimensions measured in points.""" - - width: float - height: float - - A4: ClassVar[PageSize] - LETTER: ClassVar[PageSize] - - def __post_init__(self) -> None: - if ( - not math.isfinite(self.width) - or not math.isfinite(self.height) - or self.width <= 0 - or self.height <= 0 - ): - raise InvalidInputError("page width and height must be positive finite values") - - -PageSize.A4 = PageSize(595.28, 841.89) -PageSize.LETTER = PageSize(612.0, 792.0) - - -@dataclass(frozen=True, slots=True) -class ConversionOptions: - """Options shared by all supported Office converters.""" - - page_size: PageSize | None = None diff --git a/minipdf-python/src/minipdf/pdf.py b/minipdf-python/src/minipdf/pdf.py deleted file mode 100644 index 1af5cf0f..00000000 --- a/minipdf-python/src/minipdf/pdf.py +++ /dev/null @@ -1,128 +0,0 @@ -from __future__ import annotations - -from dataclasses import dataclass, field - - -def _number(value: float) -> str: - return f"{value:.3f}".rstrip("0").rstrip(".") or "0" - - -def _pdf_text(value: str) -> bytes: - encoded = value.encode("cp1252", errors="replace") - return encoded.replace(b"\\", b"\\\\").replace(b"(", b"\\(").replace(b")", b"\\)") - - -@dataclass(frozen=True, slots=True) -class TextStyle: - size: float = 11.0 - bold: bool = False - italic: bool = False - - @property - def resource(self) -> str: - if self.bold and self.italic: - return "F4" - if self.bold: - return "F2" - if self.italic: - return "F3" - return "F1" - - -@dataclass(slots=True) -class PdfPage: - width: float - height: float - operations: list[bytes] = field(default_factory=list) - - def add_text(self, text: str, x: float, y: float, style: TextStyle) -> None: - self.operations.append( - b"BT /" - + style.resource.encode("ascii") - + b" " - + _number(style.size).encode("ascii") - + b" Tf 0 0 0 rg 1 0 0 1 " - + _number(x).encode("ascii") - + b" " - + _number(y).encode("ascii") - + b" Tm (" - + _pdf_text(text) - + b") Tj ET\n" - ) - - def content(self) -> bytes: - return b"".join(self.operations) - - -@dataclass(slots=True) -class PdfDocument: - pages: list[PdfPage] = field(default_factory=list) - - def add_page(self, width: float, height: float) -> PdfPage: - page = PdfPage(width, height) - self.pages.append(page) - return page - - def to_bytes(self) -> bytes: - if not self.pages: - self.add_page(595.28, 841.89) - - page_count = len(self.pages) - font_start = 3 + page_count * 2 - objects: list[bytes] = [ - b"<< /Type /Catalog /Pages 2 0 R >>", - b"<< /Type /Pages /Kids [" - + b" ".join(f"{3 + index * 2} 0 R".encode("ascii") for index in range(page_count)) - + f"] /Count {page_count} >>".encode("ascii"), - ] - - for index, page in enumerate(self.pages): - page_id = 3 + index * 2 - content_id = page_id + 1 - resources = ( - f"/Font << /F1 {font_start} 0 R /F2 {font_start + 1} 0 R " - f"/F3 {font_start + 2} 0 R /F4 {font_start + 3} 0 R >>" - ) - objects.append( - ( - f"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 {_number(page.width)} " - f"{_number(page.height)}] /Resources << {resources} >> " - f"/Contents {content_id} 0 R >>" - ).encode("ascii") - ) - content = page.content() - objects.append( - f"<< /Length {len(content)} >>\nstream\n".encode("ascii") + content + b"endstream" - ) - - for base_font in ( - "Helvetica", - "Helvetica-Bold", - "Helvetica-Oblique", - "Helvetica-BoldOblique", - ): - font_object = ( - f"<< /Type /Font /Subtype /Type1 /BaseFont /{base_font} " - "/Encoding /WinAnsiEncoding >>" - ) - objects.append(font_object.encode("ascii")) - - output = bytearray(b"%PDF-1.4\n%\xe2\xe3\xcf\xd3\n") - offsets = [0] - for object_id, content in enumerate(objects, start=1): - offsets.append(len(output)) - output.extend(f"{object_id} 0 obj\n".encode("ascii")) - output.extend(content) - output.extend(b"\nendobj\n") - xref_offset = len(output) - output.extend(f"xref\n0 {len(objects) + 1}\n".encode("ascii")) - output.extend(b"0000000000 65535 f \n") - for offset in offsets[1:]: - output.extend(f"{offset:010d} 00000 n \n".encode("ascii")) - output.extend( - ( - f"trailer\n<< /Size {len(objects) + 1} /Root 1 0 R >>\n" - f"startxref\n{xref_offset}\n%%EOF\n" - ).encode("ascii") - ) - return bytes(output) diff --git a/minipdf-python/src/minipdf/pptx.py b/minipdf-python/src/minipdf/pptx.py deleted file mode 100644 index edb27237..00000000 --- a/minipdf-python/src/minipdf/pptx.py +++ /dev/null @@ -1,103 +0,0 @@ -from __future__ import annotations - -import xml.etree.ElementTree as ET - -from .errors import PackageError -from .office import OfficePackage -from .options import ConversionOptions, PageSize -from .pdf import PdfDocument, TextStyle - -EMU_PER_POINT = 12700.0 -DEFAULT_SLIDE_SIZE = PageSize(720.0, 540.0) -MARGIN = 36.0 - - -def _local_name(tag: str) -> str: - return tag.rsplit("}", 1)[-1] - - -def _parse_xml(data: bytes, name: str) -> ET.Element: - try: - return ET.fromstring(data) - except ET.ParseError as error: - raise PackageError(f"{name} is malformed") from error - - -def _slide_size(root: ET.Element) -> PageSize: - size = next((node for node in root.iter() if _local_name(node.tag) == "sldSz"), None) - if size is None: - return DEFAULT_SLIDE_SIZE - try: - return PageSize( - float(size.get("cx", "")) / EMU_PER_POINT, - float(size.get("cy", "")) / EMU_PER_POINT, - ) - except ValueError: - return DEFAULT_SLIDE_SIZE - - -def _paragraph_text(paragraph: ET.Element) -> str: - chunks: list[str] = [] - for node in paragraph.iter(): - name = _local_name(node.tag) - if name == "t": - chunks.append(node.text or "") - elif name == "br": - chunks.append("\n") - return "".join(chunks) - - -def _relationship_id(node: ET.Element) -> str | None: - return next( - ( - value - for name, value in node.attrib.items() - if name.startswith("{") and _local_name(name) == "id" - ), - None, - ) - - -def convert_pptx(data: bytes, options: ConversionOptions) -> bytes: - package = OfficePackage(data) - presentation_name = "ppt/presentation.xml" - presentation_data = package.read(presentation_name) - if presentation_data is None: - raise PackageError("PPTX package is missing ppt/presentation.xml") - presentation = _parse_xml(presentation_data, presentation_name) - relationships = package.relationships(presentation_name) - slide_names: list[str] = [] - slide_list = next( - (node for node in presentation if _local_name(node.tag) == "sldIdLst"), - None, - ) - if slide_list is not None: - for node in slide_list: - if _local_name(node.tag) != "sldId": - continue - relationship_id = _relationship_id(node) - relationship = relationships.get(relationship_id or "") - if relationship is None or not relationship.relationship_type.endswith("/slide"): - raise PackageError("PPTX slide relationship is missing or invalid") - slide_names.append(relationship.target) - if not slide_names: - raise PackageError("PPTX package does not contain any slides") - - page_size = options.page_size or _slide_size(presentation) - pdf = PdfDocument() - style = TextStyle(size=18.0) - for slide_name in slide_names: - slide_data = package.read(slide_name) - if slide_data is None: - raise PackageError(f"PPTX slide part is missing: {slide_name}") - root = _parse_xml(slide_data, slide_name) - page = pdf.add_page(page_size.width, page_size.height) - cursor_y = page_size.height - MARGIN - for paragraph in (node for node in root.iter() if _local_name(node.tag) == "p"): - text = _paragraph_text(paragraph) - if text: - if cursor_y - 24.0 < MARGIN: - break - cursor_y -= 24.0 - page.add_text(text, MARGIN, cursor_y, style) - return pdf.to_bytes() diff --git a/minipdf-python/src/minipdf/xlsx.py b/minipdf-python/src/minipdf/xlsx.py deleted file mode 100644 index fe5e7b0f..00000000 --- a/minipdf-python/src/minipdf/xlsx.py +++ /dev/null @@ -1,113 +0,0 @@ -from __future__ import annotations - -import xml.etree.ElementTree as ET - -from .errors import PackageError -from .office import OfficePackage -from .options import ConversionOptions, PageSize -from .pdf import PdfDocument, TextStyle - -MARGIN = 36.0 -ROW_HEIGHT = 16.0 - - -def _local_name(tag: str) -> str: - return tag.rsplit("}", 1)[-1] - - -def _parse_xml(data: bytes, name: str) -> ET.Element: - try: - return ET.fromstring(data) - except ET.ParseError as error: - raise PackageError(f"{name} is malformed") from error - - -def _text_content(node: ET.Element) -> str: - return "".join(child.text or "" for child in node.iter() if _local_name(child.tag) == "t") - - -def _shared_strings(package: OfficePackage, part_name: str | None) -> tuple[str, ...]: - data = package.read(part_name) if part_name else None - if data is None: - return () - root = _parse_xml(data, part_name or "shared strings") - return tuple(_text_content(node) for node in root.iter() if _local_name(node.tag) == "si") - - -def _cell_text(cell: ET.Element, shared_strings: tuple[str, ...]) -> str: - cell_type = cell.get("t") - if cell_type == "inlineStr": - return _text_content(cell) - value = next((node.text or "" for node in cell if _local_name(node.tag) == "v"), "") - if cell_type == "s": - try: - return shared_strings[int(value)] - except (ValueError, IndexError): - return value - if cell_type == "b": - return "TRUE" if value == "1" else "FALSE" - return value - - -def _relationship_id(node: ET.Element) -> str | None: - return next( - ( - value - for name, value in node.attrib.items() - if name.startswith("{") and _local_name(name) == "id" - ), - None, - ) - - -def convert_xlsx(data: bytes, options: ConversionOptions) -> bytes: - package = OfficePackage(data) - workbook_name = "xl/workbook.xml" - workbook_data = package.read(workbook_name) - if workbook_data is None: - raise PackageError("XLSX package is missing xl/workbook.xml") - workbook = _parse_xml(workbook_data, workbook_name) - relationships = package.relationships(workbook_name) - sheet_names: list[str] = [] - sheets = next((node for node in workbook if _local_name(node.tag) == "sheets"), None) - if sheets is not None: - for node in sheets: - if _local_name(node.tag) != "sheet": - continue - relationship_id = _relationship_id(node) - relationship = relationships.get(relationship_id or "") - if relationship is None or not relationship.relationship_type.endswith("/worksheet"): - raise PackageError("XLSX worksheet relationship is missing or invalid") - sheet_names.append(relationship.target) - if not sheet_names: - raise PackageError("XLSX package does not contain any worksheets") - - shared_strings_name = next( - ( - relationship.target - for relationship in relationships.values() - if relationship.relationship_type.endswith("/sharedStrings") - ), - None, - ) - shared_strings = _shared_strings(package, shared_strings_name) - page_size = options.page_size or PageSize.A4 - pdf = PdfDocument() - style = TextStyle(size=10.0) - for sheet_name in sheet_names: - sheet_data = package.read(sheet_name) - if sheet_data is None: - raise PackageError(f"XLSX worksheet part is missing: {sheet_name}") - root = _parse_xml(sheet_data, sheet_name) - page = pdf.add_page(page_size.width, page_size.height) - cursor_y = page_size.height - MARGIN - for row in (node for node in root.iter() if _local_name(node.tag) == "row"): - values = [ - _cell_text(cell, shared_strings) for cell in row if _local_name(cell.tag) == "c" - ] - if cursor_y - ROW_HEIGHT < MARGIN: - page = pdf.add_page(page_size.width, page_size.height) - cursor_y = page_size.height - MARGIN - cursor_y -= ROW_HEIGHT - page.add_text(" | ".join(values), MARGIN, cursor_y, style) - return pdf.to_bytes() diff --git a/minipdf-python/tests/helpers.py b/minipdf-python/tests/helpers.py deleted file mode 100644 index 9298adb3..00000000 --- a/minipdf-python/tests/helpers.py +++ /dev/null @@ -1,133 +0,0 @@ -from __future__ import annotations - -import io -import zipfile - - -def create_docx(*, page_break: bool = False) -> bytes: - break_property = "" if page_break else "" - document = f""" - - - - Hello from Python MiniPdf - - - {break_property} - Second paragraph - - - - - - -""" - content_types = """ - - -""" - output = io.BytesIO() - with zipfile.ZipFile(output, "w", zipfile.ZIP_DEFLATED) as archive: - archive.writestr("[Content_Types].xml", content_types) - archive.writestr("word/document.xml", document) - return output.getvalue() - - -def create_xlsx() -> bytes: - spreadsheet_uri = "http://schemas.openxmlformats.org/spreadsheetml/2006/main" - relationships_uri = "http://schemas.openxmlformats.org/officeDocument/2006/relationships" - package_uri = "http://schemas.openxmlformats.org/package/2006/content-types" - worksheet_type = f"{relationships_uri}/worksheet" - shared_strings_type = f"{relationships_uri}/sharedStrings" - output = io.BytesIO() - with zipfile.ZipFile(output, "w", zipfile.ZIP_DEFLATED) as archive: - archive.writestr( - "[Content_Types].xml", - f'', - ) - archive.writestr( - "xl/workbook.xml", - f'' - '', - ) - archive.writestr( - "xl/_rels/workbook.xml.rels", - f'' - f'' - f'' - f'' - "", - ) - archive.writestr( - "xl/sharedStrings.xml", - f'' - "Hello XLSX", - ) - archive.writestr( - "xl/worksheets/sheet1.xml", - f'' - 'Second Sheet', - ) - archive.writestr( - "xl/worksheets/sheet2.xml", - f'' - '0Cell B' - "", - ) - archive.writestr( - "xl/worksheets/sheet3.xml", - f'' - 'Orphan Sheet', - ) - return output.getvalue() - - -def _slide(paragraphs: str) -> str: - presentation_uri = "http://schemas.openxmlformats.org/presentationml/2006/main" - drawing_uri = "http://schemas.openxmlformats.org/drawingml/2006/main" - return ( - f'' - '' - "" - '' - "" - '' - "" - f"{paragraphs}" - "" - ) - - -def create_pptx(*, extra_paragraphs: int = 0) -> bytes: - presentation_uri = "http://schemas.openxmlformats.org/presentationml/2006/main" - relationships_uri = "http://schemas.openxmlformats.org/officeDocument/2006/relationships" - slide_type = f"{relationships_uri}/slide" - paragraphs = "Hello PPTX" - paragraphs += "".join( - f"Extra {index}" for index in range(extra_paragraphs) - ) - output = io.BytesIO() - with zipfile.ZipFile(output, "w", zipfile.ZIP_DEFLATED) as archive: - archive.writestr( - "ppt/presentation.xml", - f'' - '' - '', - ) - archive.writestr( - "ppt/_rels/presentation.xml.rels", - f'' - f'' - f'' - "", - ) - archive.writestr( - "ppt/slides/slide1.xml", _slide("Second Slide") - ) - archive.writestr("ppt/slides/slide2.xml", _slide(paragraphs)) - archive.writestr( - "ppt/slides/slide3.xml", _slide("Orphan Slide") - ) - return output.getvalue() diff --git a/minipdf-python/tests/test_api.py b/minipdf-python/tests/test_api.py deleted file mode 100644 index 1df20dff..00000000 --- a/minipdf-python/tests/test_api.py +++ /dev/null @@ -1,109 +0,0 @@ -from __future__ import annotations - -import io -import zipfile -from pathlib import Path - -import pytest -from helpers import create_docx, create_pptx, create_xlsx -from pypdf import PdfReader - -import minipdf -from minipdf import ( - OfficeFormat, - PackageError, - UnsupportedFormatError, - convert_bytes_to_pdf, - convert_to_pdf, - convert_to_pdf_bytes, - detect_office_format, -) -from minipdf.office import OfficePackage - - -def test_runtime_version_matches_release() -> None: - assert minipdf.__version__ == "0.7.0" - - -def test_path_and_bytes_apis_produce_identical_output(tmp_path: Path) -> None: - input_path = tmp_path / "sample.docx" - output_path = tmp_path / "sample.pdf" - input_path.write_bytes(create_docx()) - - expected = convert_bytes_to_pdf(input_path.read_bytes()) - assert convert_to_pdf_bytes(input_path) == expected - convert_to_pdf(input_path, output_path) - assert output_path.read_bytes() == expected - - -def test_detects_docx_package() -> None: - assert detect_office_format(create_docx()) is OfficeFormat.DOCX - - -def test_converts_xlsx() -> None: - pdf = convert_bytes_to_pdf(create_xlsx()) - - assert pdf.startswith(b"%PDF-1.4") - reader = PdfReader(io.BytesIO(pdf)) - assert len(reader.pages) == 2 - first_sheet = reader.pages[0].extract_text() - assert "Hello XLSX" in first_sheet - assert "Cell B" in first_sheet - assert "Second Sheet" in reader.pages[1].extract_text() - assert "Orphan Sheet" not in "".join(page.extract_text() for page in reader.pages) - - -def test_converts_pptx() -> None: - pdf = convert_bytes_to_pdf(create_pptx()) - - assert pdf.startswith(b"%PDF-1.4") - reader = PdfReader(io.BytesIO(pdf)) - assert len(reader.pages) == 2 - assert "Hello PPTX" in reader.pages[0].extract_text() - assert "Second Slide" in reader.pages[1].extract_text() - assert "Orphan Slide" not in "".join(page.extract_text() for page in reader.pages) - assert float(reader.pages[0].mediabox.width) == 720.0 - assert float(reader.pages[0].mediabox.height) == 540.0 - - -def test_pptx_text_stays_inside_slide_page() -> None: - reader = PdfReader(io.BytesIO(convert_bytes_to_pdf(create_pptx(extra_paragraphs=30)))) - - assert len(reader.pages) == 2 - assert float(reader.pages[0].mediabox.width) == 720.0 - assert float(reader.pages[0].mediabox.height) == 540.0 - - -def test_reads_normalized_package_entry_names() -> None: - package_bytes = io.BytesIO() - with zipfile.ZipFile(package_bytes, "w") as archive: - archive.writestr("word\\document.xml", "") - - package = OfficePackage(package_bytes.getvalue()) - - assert package.names == ("word/document.xml",) - assert package.read("word/document.xml") == b"" - - -def test_rejects_unknown_office_package() -> None: - package = io.BytesIO() - with zipfile.ZipFile(package, "w") as archive: - archive.writestr("custom/data.xml", "") - - with pytest.raises(UnsupportedFormatError, match="unknown"): - convert_bytes_to_pdf(package.getvalue()) - - -def test_rejects_non_zip_input() -> None: - with pytest.raises(PackageError, match="valid Office ZIP"): - convert_bytes_to_pdf(b"not a zip") - - -def test_rejects_unsafe_package_paths() -> None: - package = io.BytesIO() - with zipfile.ZipFile(package, "w") as archive: - archive.writestr("word/document.xml", "") - archive.writestr("../escape.xml", "") - - with pytest.raises(PackageError, match="unsafe package path"): - detect_office_format(package.getvalue()) diff --git a/minipdf-python/tests/test_cli.py b/minipdf-python/tests/test_cli.py deleted file mode 100644 index 0508ab45..00000000 --- a/minipdf-python/tests/test_cli.py +++ /dev/null @@ -1,54 +0,0 @@ -from __future__ import annotations - -import subprocess -import sys -from pathlib import Path - -from helpers import create_docx -from pypdf import PdfReader - - -def test_cli_converts_with_default_output_name(tmp_path: Path) -> None: - input_path = tmp_path / "sample.docx" - input_path.write_bytes(create_docx()) - - result = subprocess.run( - [sys.executable, "-m", "minipdf", str(input_path)], - check=False, - capture_output=True, - text=True, - ) - - output_path = input_path.with_suffix(".pdf") - assert result.returncode == 0 - assert result.stdout.strip() == str(output_path) - assert result.stderr == "" - assert len(PdfReader(output_path).pages) == 1 - - -def test_cli_supports_convert_command_and_page_size(tmp_path: Path) -> None: - input_path = tmp_path / "sample.docx" - output_path = tmp_path / "custom.pdf" - input_path.write_bytes(create_docx()) - - result = subprocess.run( - [ - sys.executable, - "-m", - "minipdf", - "convert", - str(input_path), - "-o", - str(output_path), - "--paper-size", - "a4", - ], - check=False, - capture_output=True, - text=True, - ) - - assert result.returncode == 0 - page = PdfReader(output_path).pages[0] - assert float(page.mediabox.width) == 595.28 - assert float(page.mediabox.height) == 841.89 diff --git a/minipdf-python/tests/test_docx.py b/minipdf-python/tests/test_docx.py deleted file mode 100644 index 6f5e96fe..00000000 --- a/minipdf-python/tests/test_docx.py +++ /dev/null @@ -1,42 +0,0 @@ -from __future__ import annotations - -import io - -from helpers import create_docx -from pypdf import PdfReader - -from minipdf import ConversionOptions, PageSize, convert_bytes_to_pdf - - -def test_converts_basic_docx_to_parseable_pdf() -> None: - pdf = convert_bytes_to_pdf(create_docx()) - - assert pdf.startswith(b"%PDF-1.4") - assert pdf.endswith(b"%%EOF\n") - reader = PdfReader(io.BytesIO(pdf)) - assert len(reader.pages) == 1 - assert reader.pages[0].extract_text() == "Hello from Python MiniPdf\nSecond paragraph" - assert float(reader.pages[0].mediabox.width) == 612.0 - assert float(reader.pages[0].mediabox.height) == 792.0 - - -def test_preserves_explicit_page_breaks() -> None: - reader = PdfReader(io.BytesIO(convert_bytes_to_pdf(create_docx(page_break=True)))) - - assert len(reader.pages) == 2 - assert reader.pages[0].extract_text() == "Hello from Python MiniPdf" - assert reader.pages[1].extract_text() == "Second paragraph" - - -def test_api_page_size_overrides_document_geometry() -> None: - options = ConversionOptions(PageSize(400, 500)) - reader = PdfReader(io.BytesIO(convert_bytes_to_pdf(create_docx(), options))) - - assert float(reader.pages[0].mediabox.width) == 400.0 - assert float(reader.pages[0].mediabox.height) == 500.0 - - -def test_output_is_deterministic() -> None: - source = create_docx() - - assert convert_bytes_to_pdf(source) == convert_bytes_to_pdf(source) diff --git a/minipdf-python/tests/test_options.py b/minipdf-python/tests/test_options.py deleted file mode 100644 index 724344bf..00000000 --- a/minipdf-python/tests/test_options.py +++ /dev/null @@ -1,24 +0,0 @@ -import math - -import pytest - -from minipdf import ConversionOptions, InvalidInputError, PageSize - - -def test_exposes_standard_page_sizes() -> None: - assert PageSize(595.28, 841.89) == PageSize.A4 - assert PageSize(612.0, 792.0) == PageSize.LETTER - - -@pytest.mark.parametrize( - ("width", "height"), - [(0, 10), (-1, 10), (10, 0), (10, -1), (math.inf, 10), (10, math.nan)], -) -def test_rejects_invalid_page_dimensions(width: float, height: float) -> None: - with pytest.raises(InvalidInputError, match="positive finite"): - PageSize(width, height) - - -def test_conversion_options_default_to_document_page_size() -> None: - assert ConversionOptions().page_size is None - assert ConversionOptions(page_size=PageSize.LETTER).page_size == PageSize.LETTER diff --git a/minipdf-rs/Cargo.lock b/minipdf-rs/Cargo.lock deleted file mode 100644 index cd66c7f9..00000000 --- a/minipdf-rs/Cargo.lock +++ /dev/null @@ -1,892 +0,0 @@ -# This file is automatically @generated by Cargo. -# It is not intended for manual editing. -version = 4 - -[[package]] -name = "adler2" -version = "2.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" - -[[package]] -name = "android_system_properties" -version = "0.1.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ae221649c9976a6f6c56ae1facf410f3ddb33cc661c4b7b61020a912d4237fbc" -dependencies = [ - "libc", -] - -[[package]] -name = "anstream" -version = "1.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "824a212faf96e9acacdbd09febd34438f8f711fb84e09a8916013cd7815ca28d" -dependencies = [ - "anstyle", - "anstyle-parse", - "anstyle-query", - "anstyle-wincon", - "colorchoice", - "is_terminal_polyfill", - "utf8parse", -] - -[[package]] -name = "anstyle" -version = "1.0.14" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000" - -[[package]] -name = "anstyle-parse" -version = "1.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "52ce7f38b242319f7cabaa6813055467063ecdc9d355bbb4ce0c68908cd8130e" -dependencies = [ - "utf8parse", -] - -[[package]] -name = "anstyle-query" -version = "1.1.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc" -dependencies = [ - "windows-sys", -] - -[[package]] -name = "anstyle-wincon" -version = "3.0.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d" -dependencies = [ - "anstyle", - "once_cell_polyfill", - "windows-sys", -] - -[[package]] -name = "arbitrary" -version = "1.4.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c3d036a3c4ab069c7b410a2ce876bd74808d2d0888a82667669f8e783a898bf1" -dependencies = [ - "derive_arbitrary", -] - -[[package]] -name = "arrayvec" -version = "0.7.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d3fb67a6e08acf24fdeccbac2cb6ac4305825bd1f117462e0e6f2f193345ad56" - -[[package]] -name = "autocfg" -version = "1.5.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" - -[[package]] -name = "bitflags" -version = "2.13.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b588b76d00fde79687d7646a9b5bdf3cc0f655e0bbd080335a95d7e96f3587da" - -[[package]] -name = "bumpalo" -version = "3.20.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649" - -[[package]] -name = "bytemuck" -version = "1.25.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "95832e849adfb21180ccb6826a99da14e5d266ae5c2e668e1602cf234f153797" -dependencies = [ - "bytemuck_derive", -] - -[[package]] -name = "bytemuck_derive" -version = "1.12.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fc0e56a716f1e132ff6bf4bdac1c944a3fcdc1cae65f70a4a2a1ac3b401d2d1f" -dependencies = [ - "proc-macro2", - "quote", - "syn 3.0.3", -] - -[[package]] -name = "byteorder-lite" -version = "0.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8f1fe948ff07f4bd06c30984e69f5b4899c516a3ef74f34df92a2df2ab535495" - -[[package]] -name = "cc" -version = "1.4.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0ad534f4357a5264cce5019c989cf66a4f0dc4e0d1b1d15f8aacec0ff7360273" -dependencies = [ - "find-msvc-tools", - "shlex", -] - -[[package]] -name = "cfg-if" -version = "1.0.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801" - -[[package]] -name = "chrono" -version = "0.4.45" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1aa79e62e7697b8e29b513a68abacf485adcd1fe8284a4316c5ae868e6633327" -dependencies = [ - "iana-time-zone", - "num-traits", - "windows-link", -] - -[[package]] -name = "clap" -version = "4.6.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1ddb117e43bbf7dacf0a4190fef4d345b9bad68dfc649cb349e7d17d28428e51" -dependencies = [ - "clap_builder", - "clap_derive", -] - -[[package]] -name = "clap_builder" -version = "4.6.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "714a53001bf66416adb0e2ef5ac857140e7dc3a0c48fb28b2f10762fc4b5069f" -dependencies = [ - "anstream", - "anstyle", - "clap_lex", - "strsim", -] - -[[package]] -name = "clap_derive" -version = "4.6.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f2ce8604710f6733aa641a2b3731eaa1e8b3d9973d5e3565da11800813f997a9" -dependencies = [ - "heck", - "proc-macro2", - "quote", - "syn 2.0.118", -] - -[[package]] -name = "clap_lex" -version = "1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c8d4a3bb8b1e0c1050499d1815f5ab16d04f0959b233085fb31653fbfc9d98f9" - -[[package]] -name = "colorchoice" -version = "1.0.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570" - -[[package]] -name = "core-foundation-sys" -version = "0.8.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" - -[[package]] -name = "core_maths" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "77745e017f5edba1a9c1d854f6f3a52dac8a12dd5af5d2f54aecf61e43d80d30" -dependencies = [ - "libm", -] - -[[package]] -name = "crc32fast" -version = "1.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9481c1c90cbf2ac953f07c8d4a58aa3945c425b7185c9154d67a65e4230da511" -dependencies = [ - "cfg-if", -] - -[[package]] -name = "crossbeam-utils" -version = "0.8.21" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d0a5c400df2834b80a4c3327b3aad3a4c4cd4de0629063962b03235697506a28" - -[[package]] -name = "derive_arbitrary" -version = "1.4.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1e567bd82dcff979e4b03460c307b3cdc9e96fde3d73bed1496d2bc75d9dd62a" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.118", -] - -[[package]] -name = "displaydoc" -version = "0.2.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1ac70aa55017e108007fbaf5aa0f54b021c98f92ff8af59d42eda9da96e3dd4f" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.118", -] - -[[package]] -name = "equivalent" -version = "1.0.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f" - -[[package]] -name = "euclid" -version = "0.22.14" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f1a05365e3b1c6d1650318537c7460c6923f1abdd272ad6842baa2b509957a06" -dependencies = [ - "num-traits", -] - -[[package]] -name = "fdeflate" -version = "0.3.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1e6853b52649d4ac5c0bd02320cddc5ba956bdb407c4b75a2c6b75bf51500f8c" -dependencies = [ - "simd-adler32", -] - -[[package]] -name = "find-msvc-tools" -version = "0.1.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d45db016d36b838f563236e9193d0ee6ce38f3f68b6c94e914b4929c96bbb890" - -[[package]] -name = "flate2" -version = "1.1.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "843fba2746e448b37e26a819579957415c8cef339bf08564fe8b7ddbd959573c" -dependencies = [ - "crc32fast", - "miniz_oxide", -] - -[[package]] -name = "font-types" -version = "0.10.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "39a654f404bbcbd48ea58c617c2993ee91d1cb63727a37bf2323a4edeed1b8c5" -dependencies = [ - "bytemuck", -] - -[[package]] -name = "futures-core" -version = "0.3.34" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" - -[[package]] -name = "futures-task" -version = "0.3.34" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd" - -[[package]] -name = "futures-util" -version = "0.3.34" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" -dependencies = [ - "futures-core", - "futures-task", - "pin-project-lite", - "slab", -] - -[[package]] -name = "hashbrown" -version = "0.17.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" - -[[package]] -name = "heck" -version = "0.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" - -[[package]] -name = "iana-time-zone" -version = "0.1.65" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e31bc9ad994ba00e440a8aa5c9ef0ec67d5cb5e5cb0cc7f8b744a35b389cc470" -dependencies = [ - "android_system_properties", - "core-foundation-sys", - "iana-time-zone-haiku", - "js-sys", - "log", - "wasm-bindgen", - "windows-core", -] - -[[package]] -name = "iana-time-zone-haiku" -version = "0.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f31827a206f56af32e590ba56d5d2d085f558508192593743f16b2306495269f" -dependencies = [ - "cc", -] - -[[package]] -name = "image" -version = "0.25.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "85ab80394333c02fe689eaf900ab500fbd0c2213da414687ebf995a65d5a6104" -dependencies = [ - "bytemuck", - "byteorder-lite", - "moxcms", - "num-traits", - "png", -] - -[[package]] -name = "indexmap" -version = "2.14.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d466e9454f08e4a911e14806c24e16fba1b4c121d1ea474396f396069cf949d9" -dependencies = [ - "equivalent", - "hashbrown", -] - -[[package]] -name = "is_terminal_polyfill" -version = "1.70.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695" - -[[package]] -name = "js-sys" -version = "0.3.104" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0e0c1080212aad755ea003d18543e8768dd432c48819efd73a7bf1e39b7a5a3a" -dependencies = [ - "cfg-if", - "futures-util", - "wasm-bindgen", -] - -[[package]] -name = "kurbo" -version = "0.12.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ce9729cc38c18d86123ab736fd2e7151763ba226ac2490ec092d1dd148825e32" -dependencies = [ - "arrayvec", - "euclid", - "smallvec", -] - -[[package]] -name = "libc" -version = "0.2.189" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3eaf3ede3fee6db1a4c2ee091bf8a8b4dccdc6d17f656fb07896ee72867612f2" - -[[package]] -name = "libm" -version = "0.2.16" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981" - -[[package]] -name = "log" -version = "0.4.33" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0ceec5bc11778974d1bcb055b18002eba7f4b3518b6a0081b3af5f21666da9ad" - -[[package]] -name = "memchr" -version = "2.8.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "88904434abc2901f197fe8cc55f0445e7ded921dba5911dad2e2b39b48e663c4" - -[[package]] -name = "minipdf" -version = "0.7.0" -dependencies = [ - "chrono", - "flate2", - "image", - "roxmltree", - "rustybuzz", - "subsetter", - "thiserror", - "ttf-parser", - "unicode-bidi", - "windows-sys", - "zip", -] - -[[package]] -name = "minipdf-cli" -version = "0.7.0" -dependencies = [ - "clap", - "minipdf", - "ttf-parser", -] - -[[package]] -name = "miniz_oxide" -version = "0.8.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1fa76a2c86f704bdb222d66965fb3d63269ce38518b83cb0575fca855ebb6316" -dependencies = [ - "adler2", - "simd-adler32", -] - -[[package]] -name = "moxcms" -version = "0.8.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bb85c154ba489f01b25c0d36ae69a87e4a1c73a72631fc6c0eb6dde34a73e44b" -dependencies = [ - "num-traits", - "pxfm", -] - -[[package]] -name = "num-traits" -version = "0.2.19" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" -dependencies = [ - "autocfg", -] - -[[package]] -name = "once_cell" -version = "1.21.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" - -[[package]] -name = "once_cell_polyfill" -version = "1.70.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe" - -[[package]] -name = "pin-project-lite" -version = "0.2.17" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" - -[[package]] -name = "png" -version = "0.18.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "60769b8b31b2a9f263dae2776c37b1b28ae246943cf719eb6946a1db05128a61" -dependencies = [ - "bitflags", - "crc32fast", - "fdeflate", - "flate2", - "miniz_oxide", -] - -[[package]] -name = "proc-macro2" -version = "1.0.106" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8fd00f0bb2e90d81d1044c2b32617f68fcb9fa3bb7640c23e9c748e53fb30934" -dependencies = [ - "unicode-ident", -] - -[[package]] -name = "pxfm" -version = "0.1.30" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d55d956fa96f5ec02be2e13af0e20391a5aa83d6a074e3ad368959d0fab299ea" - -[[package]] -name = "quote" -version = "1.0.46" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dfbc457d0c7a0759a614551b11a6409e5951f6c7537be1f1b7682b9ae9230368" -dependencies = [ - "proc-macro2", -] - -[[package]] -name = "read-fonts" -version = "0.35.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6717cf23b488adf64b9d711329542ba34de147df262370221940dfabc2c91358" -dependencies = [ - "bytemuck", - "font-types", -] - -[[package]] -name = "roxmltree" -version = "0.20.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6c20b6793b5c2fa6553b250154b78d6d0db37e72700ae35fad9387a46f487c97" - -[[package]] -name = "rustc-hash" -version = "2.1.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d" - -[[package]] -name = "rustversion" -version = "1.0.23" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" - -[[package]] -name = "rustybuzz" -version = "0.20.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fd3c7c96f8a08ee34eff8857b11b49b07d71d1c3f4e88f8a88d4c9e9f90b1702" -dependencies = [ - "bitflags", - "bytemuck", - "core_maths", - "log", - "smallvec", - "ttf-parser", - "unicode-bidi-mirroring", - "unicode-ccc", - "unicode-properties", - "unicode-script", -] - -[[package]] -name = "shlex" -version = "2.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" - -[[package]] -name = "simd-adler32" -version = "0.3.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "703d5c7ef118737c72f1af64ad2f6f8c5e1921f818cdcb97b8fe6fc69bf66214" - -[[package]] -name = "skrifa" -version = "0.37.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8c31071dedf532758ecf3fed987cdb4bd9509f900e026ab684b4ecb81ea49841" -dependencies = [ - "bytemuck", - "read-fonts", -] - -[[package]] -name = "slab" -version = "0.4.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" - -[[package]] -name = "smallvec" -version = "1.15.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8ed6a63f02c8539c91a8685a86f4099661ba3da017932f6ebbea6de3f0fa7c90" - -[[package]] -name = "strsim" -version = "0.11.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" - -[[package]] -name = "subsetter" -version = "0.2.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cb6895a12ac5599bb6057362f00e8a3cf1daab4df33f553a55690a44e4fed8d0" -dependencies = [ - "kurbo", - "rustc-hash", - "skrifa", - "write-fonts", -] - -[[package]] -name = "syn" -version = "2.0.118" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1b9ae57f904213ebb649ce6895b8a66c66f0203b9319718f69a5612a065b1422" -dependencies = [ - "proc-macro2", - "quote", - "unicode-ident", -] - -[[package]] -name = "syn" -version = "3.0.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "53e9bae58849f64dfa4f5d5ae372c8341f7305f82a3868709269343628b659a3" -dependencies = [ - "proc-macro2", - "quote", - "unicode-ident", -] - -[[package]] -name = "thiserror" -version = "2.0.18" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4288b5bcbc7920c07a1149a35cf9590a2aa808e0bc1eafaade0b80947865fbc4" -dependencies = [ - "thiserror-impl", -] - -[[package]] -name = "thiserror-impl" -version = "2.0.18" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ebc4ee7f67670e9b64d05fa4253e753e016c6c95ff35b89b7941d6b856dec1d5" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.118", -] - -[[package]] -name = "ttf-parser" -version = "0.25.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d2df906b07856748fa3f6e0ad0cbaa047052d4a7dd609e231c4f72cee8c36f31" -dependencies = [ - "core_maths", -] - -[[package]] -name = "unicode-bidi" -version = "0.3.18" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5c1cb5db39152898a79168971543b1cb5020dff7fe43c8dc468b0885f5e29df5" - -[[package]] -name = "unicode-bidi-mirroring" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5dfa6e8c60bb66d49db113e0125ee8711b7647b5579dc7f5f19c42357ed039fe" - -[[package]] -name = "unicode-ccc" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ce61d488bcdc9bc8b5d1772c404828b17fc481c0a582b5581e95fb233aef503e" - -[[package]] -name = "unicode-ident" -version = "1.0.24" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75" - -[[package]] -name = "unicode-properties" -version = "0.1.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7df058c713841ad818f1dc5d3fd88063241cc61f49f5fbea4b951e8cf5a8d71d" - -[[package]] -name = "unicode-script" -version = "0.5.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "383ad40bb927465ec0ce7720e033cb4ca06912855fc35db31b5755d0de75b1ee" - -[[package]] -name = "utf8parse" -version = "0.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" - -[[package]] -name = "wasm-bindgen" -version = "0.2.127" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1b70935747edd64d89de3efa29d73789b806c15798f8e7dca4d8ac356b50ce70" -dependencies = [ - "cfg-if", - "once_cell", - "rustversion", - "wasm-bindgen-macro", - "wasm-bindgen-shared", -] - -[[package]] -name = "wasm-bindgen-macro" -version = "0.2.127" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "77775f8f3f7217702089053b94958f8f54061a3f663417df76e19cbdcca29bc1" -dependencies = [ - "quote", - "wasm-bindgen-macro-support", -] - -[[package]] -name = "wasm-bindgen-macro-support" -version = "0.2.127" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e11d33f857dc2fb11b8bc75aee111aa9cbeb12cd9f25efd3d4c2a3dd4e235284" -dependencies = [ - "bumpalo", - "proc-macro2", - "quote", - "syn 2.0.118", - "wasm-bindgen-shared", -] - -[[package]] -name = "wasm-bindgen-shared" -version = "0.2.127" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7ef64dbcc55df09c7e5a46182d181c2cfa3e925f3da937ea764728b4bbb9dcbf" -dependencies = [ - "unicode-ident", -] - -[[package]] -name = "windows-core" -version = "0.62.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb" -dependencies = [ - "windows-implement", - "windows-interface", - "windows-link", - "windows-result", - "windows-strings", -] - -[[package]] -name = "windows-implement" -version = "0.60.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.118", -] - -[[package]] -name = "windows-interface" -version = "0.59.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.118", -] - -[[package]] -name = "windows-link" -version = "0.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" - -[[package]] -name = "windows-result" -version = "0.4.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5" -dependencies = [ - "windows-link", -] - -[[package]] -name = "windows-strings" -version = "0.5.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091" -dependencies = [ - "windows-link", -] - -[[package]] -name = "windows-sys" -version = "0.61.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" -dependencies = [ - "windows-link", -] - -[[package]] -name = "write-fonts" -version = "0.43.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "886614b5ce857341226aa091f3c285e450683894acaaa7887f366c361efef79d" -dependencies = [ - "font-types", - "indexmap", - "kurbo", - "log", - "read-fonts", -] - -[[package]] -name = "zip" -version = "2.4.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fabe6324e908f85a1c52063ce7aa26b68dcb7eb6dbc83a2d148403c9bc3eba50" -dependencies = [ - "arbitrary", - "crc32fast", - "crossbeam-utils", - "displaydoc", - "flate2", - "indexmap", - "memchr", - "thiserror", - "zopfli", -] - -[[package]] -name = "zopfli" -version = "0.8.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f05cd8797d63865425ff89b5c4a48804f35ba0ce8d125800027ad6017d2b5249" -dependencies = [ - "bumpalo", - "crc32fast", - "log", - "simd-adler32", -] diff --git a/minipdf-rs/Cargo.toml b/minipdf-rs/Cargo.toml deleted file mode 100644 index bfbd51fb..00000000 --- a/minipdf-rs/Cargo.toml +++ /dev/null @@ -1,29 +0,0 @@ -[workspace] -members = [ - "crates/minipdf", - "crates/minipdf-cli", -] -resolver = "2" - -[workspace.package] -version = "0.7.0" -edition = "2021" -license = "Apache-2.0" -repository = "https://github.com/mini-software/MiniPdf" -homepage = "https://github.com/mini-software/MiniPdf" -documentation = "https://docs.rs/minipdf" -rust-version = "1.82" - -[workspace.dependencies] -chrono = { version = "0.4", default-features = false, features = ["clock"] } -clap = { version = "4.5", features = ["derive"] } -flate2 = "1" -image = { version = "0.25", default-features = false, features = ["png"] } -roxmltree = "0.20" -rustybuzz = "0.20" -subsetter = "=0.2.3" -ttf-parser = "0.25" -thiserror = "2" -unicode-bidi = "0.3" -windows-sys = "0.61" -zip = { version = "2.2", default-features = false, features = ["deflate"] } \ No newline at end of file diff --git a/minipdf-rs/README.md b/minipdf-rs/README.md deleted file mode 100644 index 09913fee..00000000 --- a/minipdf-rs/README.md +++ /dev/null @@ -1,192 +0,0 @@ -# MiniPdf for Rust - -[![crates.io](https://img.shields.io/crates/v/minipdf.svg)](https://crates.io/crates/minipdf) -[![docs.rs](https://img.shields.io/docsrs/minipdf)](https://docs.rs/minipdf) -[![License](https://img.shields.io/badge/license-Apache%202.0-blue.svg)](../LICENSE) - -The experimental native Rust implementation of MiniPdf. It provides the -reusable `minipdf` crate and the `minipdf-cli` package, whose installed binary is -named `minipdf`. - -[Project portal](../README.md) · -[crates.io](https://crates.io/crates/minipdf) · -[API documentation](https://docs.rs/minipdf) · -[.NET implementation](../documents/README.nuget.md) - -> The Rust implementation is under active development and is not yet -> feature-equivalent with MiniPdf for .NET. It currently converts XLSX, DOCX, -> and PPTX files. Use the .NET implementation for broader production compatibility. - -## Requirements - -- Rust 1.82 or later -- No Microsoft Office, LibreOffice, Adobe Acrobat, or .NET runtime at runtime - -## Library - -Add the crate: - -```bash -cargo add minipdf -``` - -Convert a file to a PDF on disk: - -```rust -fn main() -> minipdf::Result<()> { - minipdf::convert_to_pdf("report.docx", "report.pdf")?; - Ok(()) -} -``` - -Return PDF bytes instead: - -```rust -let pdf = minipdf::convert_to_pdf_bytes("data.xlsx")?; -``` - -Override the output page size with a preset or custom dimensions: - -```rust -let options = minipdf::ConversionOptions { - page_size: Some(minipdf::PageSize::A4), -}; -minipdf::convert_to_pdf_with_options("data.xlsx", "data.pdf", &options)?; - -let custom = minipdf::ConversionOptions { - page_size: Some(minipdf::PageSize::new(400.0, 500.0)?), -}; -minipdf::convert_to_pdf_with_options("report.docx", "report.pdf", &custom)?; -``` - -Custom dimensions use PDF points, where 72 points equal one inch. XLSX -conversion uses an explicit API override first, then the worksheet `pageSetup` -paper size and orientation. DOCX conversion uses the section page size and -margins unless the API overrides the page size. PPTX conversion uses the -presentation slide size unless the API overrides it. A document without -recognized page geometry uses its format default. - -For a host with limited system fonts, register font bytes before conversion: - -```rust -let font = std::fs::read("fonts/NotoSansSC-Regular.ttf")?; -minipdf::register_font("NotoSansSC", font); -minipdf::convert_to_pdf("report.docx", "report.pdf")?; -``` - -The public API also supports in-memory Office package bytes through -`convert_bytes_to_pdf` and package inspection through `detect_office_format`. - -## Command Line - -Install the CLI from crates.io: - -```bash -cargo install minipdf-cli -``` - -Convert with an automatically selected output name: - -```bash -minipdf report.docx -``` - -Specify an output path or font directory: - -```bash -minipdf data.xlsx -o data.pdf -minipdf report.docx --fonts ./fonts -minipdf slides.pptx -o slides.pdf -minipdf convert report.docx -o report.pdf -``` - -Select A4 or Letter paper, or provide custom dimensions in PDF points: - -```bash -minipdf data.xlsx --paper-size a4 -minipdf data.xlsx --paper-size letter -minipdf data.xlsx --page-width 400 --page-height 500 -``` - -`--paper-size` cannot be combined with `--page-width` and `--page-height`. -Custom width and height must be provided together. - -## Current Scope - -| Capability | Rust status | -|---|---| -| XLSX to PDF | Supported; rendering coverage is expanding | -| DOCX to PDF | Supported; rendering coverage is expanding | -| PPTX to PDF | Supported; rendering coverage is expanding | -| PDF output | PDF 1.4 | -| Fonts | Built-in Helvetica and registered/system fallback fonts | -| Page size | Office page/slide geometry, A4/Letter presets, or custom point dimensions | -| Interfaces | Rust crate and native CLI | - -The converter preserves sparse worksheet row positions, paginates wide sheets -horizontally, and supports basic spreadsheet styling, drawing images, document -text, explicit DOCX page breaks, basic DOCX tables, and Unicode fallback fonts. -PPTX support includes themes and placeholders, basic shapes and connectors, -text, raster and SVG images, tables, and SmartArt drawing fallbacks. Complex -shape geometry, transforms, animations, and Office-specific layout can still -differ from the source application. - -## Development - -The Rust implementation is an independent Cargo workspace: - -```text -minipdf-rs/ -|-- Cargo.toml -`-- crates/ - |-- minipdf/ # Library API and conversion engine - `-- minipdf-cli/ # CLI binary named minipdf -``` - -Run the standard checks from this directory: - -```powershell -cargo fmt --check -cargo clippy --workspace --all-targets -- -D warnings -cargo test --workspace -cargo run -p minipdf-cli -- path\to\input.docx -``` - -## Visual Benchmarks - -Run shared fixtures against Microsoft 365 and LibreOffice from the repository root: - -```powershell -.\scripts\Run-Rust-Benchmark.ps1 -Suite classic -Format xlsx -.\scripts\Run-Rust-Benchmark.ps1 -Suite classic -Format docx -.\scripts\Run-Rust-Benchmark.ps1 -Suite issue -Format xlsx -.\scripts\Run-Rust-Benchmark.ps1 -Suite issue -Format docx -.\scripts\Run-Rust-Benchmark-Matrix.ps1 -MaxComparePages 1 -``` - -The benchmark reuses the repository fixtures, references, and PDF comparison -pipeline without executing the C# xUnit tests. Each run writes coverage data, -Markdown and JSON reports, side-by-side images, and heatmaps under -`artifacts/rust-benchmark//`. - -- [Classic XLSX visual comparison](https://mini-software.github.io/minipdf-web-page/?language=rust&suite=classic&format=xlsx) -- [Classic DOCX visual comparison](https://mini-software.github.io/minipdf-web-page/?language=rust&suite=classic&format=docx) - -Microsoft 365 is the primary reference used for text, visual, page-count, and -overall scores. LibreOffice is generated on every run as an auxiliary reference -and is included in the visual report without affecting those scores. Both -references are required, the default minimum score is `0.95`, and -`-SkipCandidate` reuses an existing Rust candidate PDF. - -The matrix is generated at `artifacts/rust-benchmark/benchmark_matrix.md` and -links to the fixture coverage and comparison reports from each run. - -## Publishing - -Both packages are published to crates.io. Repository releases tagged -`rust-v` publish `minipdf` first and then `minipdf-cli` through GitHub -Actions. - -## License - -[Apache License 2.0](../LICENSE). \ No newline at end of file diff --git a/minipdf-rs/crates/minipdf-cli/Cargo.toml b/minipdf-rs/crates/minipdf-cli/Cargo.toml deleted file mode 100644 index 5cb580c6..00000000 --- a/minipdf-rs/crates/minipdf-cli/Cargo.toml +++ /dev/null @@ -1,22 +0,0 @@ -[package] -name = "minipdf-cli" -version.workspace = true -edition.workspace = true -license.workspace = true -repository.workspace = true -homepage.workspace = true -rust-version.workspace = true -description = "Experimental Rust CLI for MiniPdf Office-to-PDF conversion." -readme = "../../README.md" -keywords = ["pdf", "xlsx", "docx", "pptx", "cli"] -categories = ["command-line-utilities"] -exclude = ["target/"] - -[[bin]] -name = "minipdf" -path = "src/main.rs" - -[dependencies] -clap.workspace = true -minipdf = { version = "0.7.0", path = "../minipdf" } -ttf-parser.workspace = true \ No newline at end of file diff --git a/minipdf-rs/crates/minipdf-cli/src/main.rs b/minipdf-rs/crates/minipdf-cli/src/main.rs deleted file mode 100644 index 497406b9..00000000 --- a/minipdf-rs/crates/minipdf-cli/src/main.rs +++ /dev/null @@ -1,239 +0,0 @@ -use std::fs; -use std::path::{Path, PathBuf}; - -use clap::{Args, Parser, Subcommand, ValueEnum}; - -#[derive(Debug, Parser)] -#[command(name = "minipdf")] -#[command(version)] -#[command(about = "Convert Office files to PDF with the experimental Rust MiniPdf engine.")] -struct Cli { - #[command(subcommand)] - command: Option, - - #[arg(value_name = "INPUT")] - input: Option, - - #[arg(short, long, value_name = "OUTPUT")] - output: Option, - - #[arg(long, value_name = "DIR")] - fonts: Option, - - #[command(flatten)] - page: PageArgs, -} - -#[derive(Debug, Subcommand)] -enum Commands { - Convert(ConvertArgs), -} - -#[derive(Debug, Parser)] -struct ConvertArgs { - #[arg(value_name = "INPUT")] - input: PathBuf, - - #[arg(short, long, value_name = "OUTPUT")] - output: Option, - - #[arg(long, value_name = "DIR")] - fonts: Option, - - #[command(flatten)] - page: PageArgs, -} - -#[derive(Debug, Args, Default)] -struct PageArgs { - #[arg(long, value_enum, value_name = "SIZE")] - paper_size: Option, - - #[arg(long, value_name = "POINTS", requires = "page_height")] - page_width: Option, - - #[arg(long, value_name = "POINTS", requires = "page_width")] - page_height: Option, -} - -#[derive(Debug, Clone, Copy, ValueEnum)] -enum PaperSizeArg { - A4, - Letter, -} - -fn main() { - let cli = Cli::parse(); - let result = match cli.command { - Some(Commands::Convert(args)) => { - run_convert(args.input, args.output, args.fonts, args.page) - } - None => { - let Some(input) = cli.input else { - eprintln!("Error: input file is required. Use --help for usage."); - std::process::exit(1); - }; - run_convert(input, cli.output, cli.fonts, cli.page) - } - }; - - if let Err(err) = result { - eprintln!("Error: {err}"); - std::process::exit(1); - } -} - -fn run_convert( - input: PathBuf, - output: Option, - fonts: Option, - page: PageArgs, -) -> minipdf::Result<()> { - if !input.exists() { - return Err(minipdf::MiniPdfError::InvalidInput(format!( - "file not found: {}", - input.display() - ))); - } - - let ext = input - .extension() - .and_then(|ext| ext.to_str()) - .map(|ext| ext.to_ascii_lowercase()) - .unwrap_or_default(); - if ext != "xlsx" && ext != "docx" && ext != "pptx" { - return Err(minipdf::MiniPdfError::InvalidInput(format!( - "unsupported file type '.{ext}'. Supported: .xlsx, .docx, .pptx" - ))); - } - - if let Some(font_dir) = fonts { - register_fonts_from_dir(&font_dir)?; - } else { - register_system_fallback_fonts()?; - } - - let options = conversion_options(page)?; - let output = output.unwrap_or_else(|| input.with_extension("pdf")); - minipdf::convert_to_pdf_with_options(&input, &output, &options)?; - println!("{}", output.display()); - Ok(()) -} - -fn conversion_options(page: PageArgs) -> minipdf::Result { - if page.paper_size.is_some() && page.page_width.is_some() { - return Err(minipdf::MiniPdfError::InvalidInput( - "use either --paper-size or --page-width/--page-height, not both".to_owned(), - )); - } - let page_size = match (page.paper_size, page.page_width, page.page_height) { - (Some(PaperSizeArg::A4), None, None) => Some(minipdf::PageSize::A4), - (Some(PaperSizeArg::Letter), None, None) => Some(minipdf::PageSize::LETTER), - (None, Some(width), Some(height)) => Some(minipdf::PageSize::new(width, height)?), - (None, None, None) => None, - _ => { - return Err(minipdf::MiniPdfError::InvalidInput( - "--page-width and --page-height must be specified together".to_owned(), - )); - } - }; - Ok(minipdf::ConversionOptions { page_size }) -} - -fn register_fonts_from_dir(font_dir: &Path) -> minipdf::Result<()> { - if !font_dir.is_dir() { - return Err(minipdf::MiniPdfError::InvalidInput(format!( - "font directory not found: {}", - font_dir.display() - ))); - } - - for entry in fs::read_dir(font_dir)? { - let entry = entry?; - let path = entry.path(); - let ext = path - .extension() - .and_then(|ext| ext.to_str()) - .map(|ext| ext.to_ascii_lowercase()); - if matches!(ext.as_deref(), Some("ttf" | "ttc" | "otf")) { - let data = fs::read(&path)?; - let name = font_alias_from_data(&data).unwrap_or_else(|| { - path.file_stem() - .and_then(|name| name.to_str()) - .unwrap_or("font") - .to_owned() - }); - minipdf::register_font(name, data); - } - } - - Ok(()) -} - -fn register_system_fallback_fonts() -> minipdf::Result<()> { - minipdf::register_system_fonts() -} - -fn font_alias_from_data(data: &[u8]) -> Option { - let face = ttf_parser::Face::parse(data, 0).ok()?; - let name = |id| { - face.names() - .into_iter() - .find(|name| name.name_id == id && name.is_unicode()) - .and_then(|name| name.to_string()) - }; - let family = name(ttf_parser::name_id::TYPOGRAPHIC_FAMILY) - .or_else(|| name(ttf_parser::name_id::FAMILY))?; - let subfamily = name(ttf_parser::name_id::TYPOGRAPHIC_SUBFAMILY) - .or_else(|| name(ttf_parser::name_id::SUBFAMILY)) - .unwrap_or_default(); - Some(build_font_alias( - &family, - &subfamily, - face.is_bold(), - face.is_italic(), - )) -} - -fn build_font_alias(family: &str, subfamily: &str, bold: bool, italic: bool) -> String { - let mut alias = normalize_font_alias(family); - if subfamily.to_ascii_lowercase().contains("display") && !alias.contains("display") { - alias.push_str("display"); - } - if bold && italic { - alias.push('z'); - } else if bold { - alias.push('b'); - } else if italic { - alias.push('i'); - } - alias -} - -fn normalize_font_alias(name: &str) -> String { - name.chars() - .filter(|character| character.is_ascii_alphanumeric()) - .flat_map(char::to_lowercase) - .collect() -} - -#[cfg(test)] -mod tests { - use super::build_font_alias; - - #[test] - fn builds_stable_cloud_font_aliases() { - assert_eq!( - build_font_alias("Grandview", "Regular", false, false), - "grandview" - ); - assert_eq!( - build_font_alias("Grandview", "Bold", true, false), - "grandviewb" - ); - assert_eq!( - build_font_alias("Grandview", "Display", false, false), - "grandviewdisplay" - ); - } -} diff --git a/minipdf-rs/crates/minipdf/Cargo.toml b/minipdf-rs/crates/minipdf/Cargo.toml deleted file mode 100644 index cc827453..00000000 --- a/minipdf-rs/crates/minipdf/Cargo.toml +++ /dev/null @@ -1,29 +0,0 @@ -[package] -name = "minipdf" -version.workspace = true -edition.workspace = true -license.workspace = true -repository.workspace = true -homepage.workspace = true -documentation.workspace = true -rust-version.workspace = true -description = "Experimental Rust implementation of MiniPdf Office-to-PDF conversion." -readme = "../../README.md" -keywords = ["pdf", "xlsx", "docx", "pptx", "converter"] -categories = ["encoding", "parser-implementations"] -exclude = ["target/"] - -[dependencies] -chrono.workspace = true -flate2.workspace = true -image.workspace = true -roxmltree.workspace = true -rustybuzz.workspace = true -subsetter.workspace = true -ttf-parser.workspace = true -thiserror.workspace = true -unicode-bidi.workspace = true -zip.workspace = true - -[target.'cfg(windows)'.dependencies] -windows-sys = { workspace = true, features = ["Win32_Graphics_Gdi"] } \ No newline at end of file diff --git a/minipdf-rs/crates/minipdf/src/docx.rs b/minipdf-rs/crates/minipdf/src/docx.rs deleted file mode 100644 index 5a8aa2fe..00000000 --- a/minipdf-rs/crates/minipdf/src/docx.rs +++ /dev/null @@ -1,2598 +0,0 @@ -use std::collections::HashMap; -use std::io::{Cursor, Read}; - -use zip::ZipArchive; - -use crate::pdf::{styled_text_width_with_font, PdfColor, PdfDocument}; -use crate::{read_zip_text, ConversionOptions, PageSize, Result}; - -const PAGE_WIDTH: f32 = 595.28; -const PAGE_HEIGHT: f32 = 841.89; -const MARGIN: f32 = 54.0; -const BODY_FONT_SIZE: f32 = 11.0; -const TABLE_CELL_PADDING_HORIZONTAL: f32 = 5.4; -const TABLE_BORDER_WIDTH: f32 = 0.5; -const VML_INLINE_IMAGE_TOP_LEADING: f32 = 2.0; - -#[derive(Debug, PartialEq)] -struct DocxDocument { - blocks: Vec, - page_size: PageSize, - margins: DocxMargins, - grid_line_pitch: f32, - compatibility_mode: u8, -} - -#[derive(Debug, Clone, Copy, PartialEq)] -struct DocxMargins { - top: f32, - right: f32, - bottom: f32, - left: f32, -} - -#[derive(Debug, PartialEq)] -enum DocxBlock { - Paragraph(DocxParagraph), - Table(DocxTable), - Image(DocxImage), - PageBreak, -} - -#[derive(Debug, Clone, PartialEq)] -struct DocxParagraph { - runs: Vec, - floating_images: Vec, - style_id: Option, - contextual_spacing: bool, - alignment: TextAlignment, - indent_left: f32, - indent_right: f32, - spacing_before: f32, - spacing_after: f32, - line_spacing: f32, - line_spacing_explicit: bool, - fill: Option, - bottom_border: Option, -} - -#[derive(Debug, Clone, PartialEq)] -struct DocxFloatingImage { - image: DocxImage, - offset_x: f32, - offset_y: f32, - inset_left: f32, - inset_top: f32, - line_top_leading: f32, -} - -#[derive(Debug, Clone, PartialEq)] -struct DocxRun { - text: String, - font_size: f32, - font_name: Option, - bold: bool, - italic: bool, - underline: bool, - color: PdfColor, - highlight: Option, -} - -#[derive(Debug, Clone, Copy, PartialEq)] -struct DocxBorder { - color: PdfColor, - width: f32, - space: f32, - is_double: bool, - pattern: BorderPattern, -} - -#[derive(Debug, Clone, Copy, PartialEq)] -enum BorderPattern { - Solid, - DotDash, - Dotted, - Dashed, -} - -#[derive(Debug, Clone, Default)] -struct DocxStyles { - paragraph_defaults: ParagraphProperties, - run_defaults: RunProperties, - styles: HashMap, - theme_fonts: DocxThemeFonts, -} - -#[derive(Debug, Clone, Default)] -struct DocxStyle { - based_on: Option, - paragraph: ParagraphProperties, - run: RunProperties, -} - -#[derive(Debug, Clone, Default)] -struct ParagraphProperties { - contextual_spacing: Option, - alignment: Option, - indent_left: Option, - indent_right: Option, - spacing_before: Option, - spacing_after: Option, - line_spacing: Option, - fill: Option, - bottom_border: Option, -} - -#[derive(Debug, Clone, Default)] -struct RunProperties { - font_size: Option, - font_name: Option, - font_theme: Option, - bold: Option, - italic: Option, - underline: Option, - color: Option, - highlight: Option, -} - -#[derive(Debug, Clone, Copy, PartialEq)] -enum ThemeFontReference { - MajorEastAsia, - MinorEastAsia, -} - -#[derive(Debug, Clone, Default)] -struct DocxThemeFonts { - major_east_asia: Option, - minor_east_asia: Option, -} - -#[derive(Debug, Clone, PartialEq)] -struct DocxImage { - data: DocxImageData, - width: f32, - height: f32, - alignment: TextAlignment, -} - -#[derive(Debug, Clone, PartialEq)] -enum DocxImageData { - Jpeg { - data: Vec, - width: u16, - height: u16, - }, - Rgba { - data: Vec, - width: u16, - height: u16, - }, -} - -#[derive(Debug, PartialEq)] -struct DocxTable { - column_widths: Vec, - rows: Vec, - alignment: TextAlignment, - cell_margin_left: f32, - cell_margin_right: f32, - cell_margin_top: f32, - cell_margin_bottom: f32, - legacy_cjk_metrics: bool, -} - -#[derive(Debug, PartialEq)] -struct DocxTableRow { - cells: Vec, - height: Option, -} - -#[derive(Debug, PartialEq)] -struct DocxTableCell { - runs: Vec, - images: Vec, - width: Option, - spacing_before: f32, - spacing_after: f32, - line_spacing: f32, - fill: Option, - alignment: TextAlignment, - vertical_alignment: VerticalAlignment, - grid_span: usize, - vertical_merge: VerticalMerge, - borders: DocxCellBorders, -} - -#[derive(Debug, Clone, Copy, Default, PartialEq)] -struct DocxCellBorders { - top: Option, - right: Option, - bottom: Option, - left: Option, -} - -#[derive(Debug, Clone, Copy, PartialEq)] -enum TextAlignment { - Left, - Center, - Right, -} - -#[derive(Debug, Clone, Copy, PartialEq)] -enum VerticalAlignment { - Top, - Center, - Bottom, -} - -#[derive(Debug, Clone, Copy, PartialEq)] -enum VerticalMerge { - None, - Restart, - Continue, -} - -pub(crate) fn convert_docx_bytes(input: &[u8], options: &ConversionOptions) -> Result> { - let document = read_docx_document(input)?; - let mut doc = PdfDocument::new(); - render_docx(&mut doc, &document, options); - Ok(doc.to_bytes()) -} - -fn read_docx_document(input: &[u8]) -> Result { - let cursor = Cursor::new(input); - let mut archive = ZipArchive::new(cursor)?; - let Some(document_xml) = read_zip_text(&mut archive, "word/document.xml")? else { - return Ok(empty_docx_document()); - }; - let styles = read_styles(&mut archive)?; - let relationships = read_document_relationships(&mut archive)?; - let compatibility_mode = read_compatibility_mode(&mut archive)?; - - let xml = roxmltree::Document::parse(&document_xml)?; - let Some(body) = xml.descendants().find(|node| node.has_tag_name("body")) else { - return Ok(empty_docx_document()); - }; - let (page_size, margins, grid_line_pitch) = read_page_layout(body); - let mut blocks = Vec::new(); - - for node in body.children().filter(|node| node.is_element()) { - if node.has_tag_name("p") { - read_paragraph(node, &mut blocks, &styles, &relationships, &mut archive)?; - } else if node.has_tag_name("tbl") { - blocks.push(DocxBlock::Table(read_table( - node, - &styles, - &relationships, - &mut archive, - compatibility_mode <= 12, - )?)); - } - } - - if blocks.is_empty() { - blocks.push(DocxBlock::Paragraph(plain_paragraph( - "Empty DOCX document".to_owned(), - ))); - } - - Ok(DocxDocument { - blocks, - page_size, - margins, - grid_line_pitch, - compatibility_mode, - }) -} - -fn read_compatibility_mode(archive: &mut ZipArchive>) -> Result { - let Some(settings_xml) = read_zip_text(archive, "word/settings.xml")? else { - return Ok(15); - }; - let xml = roxmltree::Document::parse(&settings_xml)?; - Ok(xml - .descendants() - .find(|node| { - node.has_tag_name("compatSetting") - && attribute_by_local_name(*node, "name") == Some("compatibilityMode") - }) - .and_then(|node| attribute_by_local_name(node, "val")) - .and_then(|value| value.parse().ok()) - .unwrap_or(15)) -} - -fn empty_docx_document() -> DocxDocument { - DocxDocument { - blocks: vec![DocxBlock::Paragraph(plain_paragraph( - "Empty DOCX document".to_owned(), - ))], - page_size: PageSize { - width: PAGE_WIDTH, - height: PAGE_HEIGHT, - }, - margins: DocxMargins { - top: MARGIN, - right: MARGIN, - bottom: MARGIN, - left: MARGIN, - }, - grid_line_pitch: 0.0, - compatibility_mode: 15, - } -} - -fn plain_paragraph(text: String) -> DocxParagraph { - DocxParagraph { - runs: vec![DocxRun { - text, - font_size: BODY_FONT_SIZE, - font_name: None, - bold: false, - italic: false, - underline: false, - color: PdfColor::BLACK, - highlight: None, - }], - floating_images: Vec::new(), - style_id: None, - contextual_spacing: false, - alignment: TextAlignment::Left, - indent_left: 0.0, - indent_right: 0.0, - spacing_before: 0.0, - spacing_after: 0.0, - line_spacing: 1.15, - line_spacing_explicit: false, - fill: None, - bottom_border: None, - } -} - -fn read_page_layout(body: roxmltree::Node<'_, '_>) -> (PageSize, DocxMargins, f32) { - let section = body.children().find(|node| node.has_tag_name("sectPr")); - let page_size_node = section.and_then(|node| child(node, "pgSz")); - let margin_node = section.and_then(|node| child(node, "pgMar")); - let page_size = PageSize { - width: twips_attribute(page_size_node, "w").unwrap_or(PAGE_WIDTH), - height: twips_attribute(page_size_node, "h").unwrap_or(PAGE_HEIGHT), - }; - let margins = DocxMargins { - top: twips_attribute(margin_node, "top").unwrap_or(MARGIN), - right: twips_attribute(margin_node, "right").unwrap_or(MARGIN), - bottom: twips_attribute(margin_node, "bottom").unwrap_or(MARGIN), - left: twips_attribute(margin_node, "left").unwrap_or(MARGIN), - }; - let grid_line_pitch = section - .and_then(|node| child(node, "docGrid")) - .filter(|node| { - matches!( - attribute_by_local_name(*node, "type"), - Some("lines" | "linesAndChars" | "snapToChars") - ) - }) - .and_then(|node| twips_attribute(Some(node), "linePitch")) - .unwrap_or(0.0); - (page_size, margins, grid_line_pitch) -} - -fn read_styles(archive: &mut ZipArchive>) -> Result { - let theme_fonts = read_theme_fonts(archive)?; - let Some(styles_xml) = read_zip_text(archive, "word/styles.xml")? else { - return Ok(DocxStyles { - theme_fonts, - ..DocxStyles::default() - }); - }; - let xml = roxmltree::Document::parse(&styles_xml)?; - let defaults = xml - .descendants() - .find(|node| node.has_tag_name("docDefaults")); - let paragraph_defaults = defaults - .and_then(|node| node.descendants().find(|child| child.has_tag_name("pPr"))) - .map(read_paragraph_properties) - .unwrap_or_default(); - let run_defaults = defaults - .and_then(|node| node.descendants().find(|child| child.has_tag_name("rPr"))) - .map(read_run_properties) - .unwrap_or_default(); - let styles = xml - .descendants() - .filter(|node| node.has_tag_name("style")) - .filter_map(|node| { - let id = attribute_by_local_name(node, "styleId")?; - Some(( - id.to_owned(), - DocxStyle { - based_on: child(node, "basedOn") - .and_then(|value| attribute_by_local_name(value, "val")) - .map(str::to_owned), - paragraph: child(node, "pPr") - .map(read_paragraph_properties) - .unwrap_or_default(), - run: child(node, "rPr") - .map(read_run_properties) - .unwrap_or_default(), - }, - )) - }) - .collect(); - Ok(DocxStyles { - paragraph_defaults, - run_defaults, - styles, - theme_fonts, - }) -} - -fn read_theme_fonts(archive: &mut ZipArchive>) -> Result { - let Some(theme_xml) = read_zip_text(archive, "word/theme/theme1.xml")? else { - return Ok(DocxThemeFonts::default()); - }; - let xml = roxmltree::Document::parse(&theme_xml)?; - let font_scheme = xml - .descendants() - .find(|node| node.has_tag_name("fontScheme")); - Ok(DocxThemeFonts { - major_east_asia: font_scheme - .and_then(|node| child(node, "majorFont")) - .and_then(theme_east_asia_font), - minor_east_asia: font_scheme - .and_then(|node| child(node, "minorFont")) - .and_then(theme_east_asia_font), - }) -} - -fn theme_east_asia_font(group: roxmltree::Node<'_, '_>) -> Option { - child(group, "ea") - .and_then(|node| attribute_by_local_name(node, "typeface")) - .filter(|name| !name.is_empty()) - .or_else(|| { - group - .children() - .find(|node| { - node.has_tag_name("font") - && attribute_by_local_name(*node, "script") == Some("Hans") - }) - .and_then(|node| attribute_by_local_name(node, "typeface")) - }) - .map(str::to_owned) -} - -fn read_paragraph_properties(properties: roxmltree::Node<'_, '_>) -> ParagraphProperties { - let spacing = child(properties, "spacing"); - let indentation = child(properties, "ind"); - ParagraphProperties { - contextual_spacing: child(properties, "contextualSpacing").map(property_enabled), - alignment: child(properties, "jc") - .and_then(|node| attribute_by_local_name(node, "val")) - .map(parse_alignment), - indent_left: indentation - .and_then(|node| numeric_attribute(node, "left")) - .map(|twips| twips / 20.0), - indent_right: indentation - .and_then(|node| numeric_attribute(node, "right")) - .map(|twips| twips / 20.0), - spacing_before: spacing - .and_then(|node| numeric_attribute(node, "before")) - .map(|twips| twips / 20.0), - spacing_after: spacing - .and_then(|node| numeric_attribute(node, "after")) - .map(|twips| twips / 20.0), - line_spacing: spacing - .and_then(|node| numeric_attribute(node, "line")) - .map(|line| line / 240.0), - fill: child(properties, "shd") - .and_then(|node| attribute_by_local_name(node, "fill")) - .and_then(parse_hex_color), - bottom_border: child(properties, "pBdr") - .and_then(|node| child(node, "bottom")) - .and_then(read_border), - } -} - -fn read_run_properties(properties: roxmltree::Node<'_, '_>) -> RunProperties { - let fonts = child(properties, "rFonts"); - RunProperties { - font_size: child(properties, "sz") - .and_then(|node| numeric_attribute(node, "val")) - .map(|half_points| half_points / 2.0), - font_name: fonts - .and_then(|node| { - attribute_by_local_name(node, "eastAsia") - .or_else(|| attribute_by_local_name(node, "ascii")) - .or_else(|| attribute_by_local_name(node, "hAnsi")) - }) - .map(str::to_owned), - font_theme: fonts - .and_then(|node| { - attribute_by_local_name(node, "eastAsiaTheme") - .or_else(|| attribute_by_local_name(node, "asciiTheme")) - .or_else(|| attribute_by_local_name(node, "hAnsiTheme")) - }) - .and_then(|value| match value { - "majorEastAsia" => Some(ThemeFontReference::MajorEastAsia), - "minorEastAsia" => Some(ThemeFontReference::MinorEastAsia), - _ => None, - }), - bold: child(properties, "b").map(property_enabled), - italic: child(properties, "i").map(property_enabled), - underline: child(properties, "u").map(property_enabled), - color: child(properties, "color") - .and_then(|node| attribute_by_local_name(node, "val")) - .and_then(parse_hex_color), - highlight: child(properties, "highlight") - .and_then(|node| attribute_by_local_name(node, "val")) - .and_then(parse_highlight_color), - } -} - -fn parse_highlight_color(value: &str) -> Option { - match value { - "yellow" => Some(PdfColor::new(1.0, 1.0, 0.0)), - "green" => Some(PdfColor::new(0.0, 1.0, 0.0)), - "cyan" => Some(PdfColor::new(0.0, 1.0, 1.0)), - "magenta" => Some(PdfColor::new(1.0, 0.0, 1.0)), - "blue" => Some(PdfColor::new(0.0, 0.0, 1.0)), - "red" => Some(PdfColor::new(1.0, 0.0, 0.0)), - "darkBlue" => Some(PdfColor::new(0.0, 0.0, 0.5)), - "darkCyan" => Some(PdfColor::new(0.0, 0.5, 0.5)), - "darkGreen" => Some(PdfColor::new(0.0, 0.5, 0.0)), - "darkMagenta" => Some(PdfColor::new(0.5, 0.0, 0.5)), - "darkRed" => Some(PdfColor::new(0.5, 0.0, 0.0)), - "darkYellow" => Some(PdfColor::new(0.5, 0.5, 0.0)), - "darkGray" => Some(PdfColor::new(0.5, 0.5, 0.5)), - "lightGray" => Some(PdfColor::new(0.75, 0.75, 0.75)), - "black" => Some(PdfColor::BLACK), - _ => None, - } -} - -fn read_border(border: roxmltree::Node<'_, '_>) -> Option { - let style = attribute_by_local_name(border, "val")?; - if matches!(style, "nil" | "none") { - return None; - } - Some(DocxBorder { - color: attribute_by_local_name(border, "color") - .and_then(parse_hex_color) - .unwrap_or(PdfColor::BLACK), - width: numeric_attribute(border, "sz").unwrap_or(4.0) / 8.0, - space: numeric_attribute(border, "space").unwrap_or(0.0), - is_double: style == "double", - pattern: match style { - "dotDash" | "dashDotStroked" => BorderPattern::DotDash, - "dotted" => BorderPattern::Dotted, - "dashed" | "dashSmallGap" => BorderPattern::Dashed, - _ => BorderPattern::Solid, - }, - }) -} - -fn default_table_border() -> DocxBorder { - DocxBorder { - color: PdfColor::BLACK, - width: TABLE_BORDER_WIDTH, - space: 0.0, - is_double: false, - pattern: BorderPattern::Solid, - } -} - -fn parse_alignment(value: &str) -> TextAlignment { - match value { - "center" => TextAlignment::Center, - "right" | "end" => TextAlignment::Right, - _ => TextAlignment::Left, - } -} - -fn property_enabled(node: roxmltree::Node<'_, '_>) -> bool { - !matches!( - attribute_by_local_name(node, "val"), - Some("0" | "false" | "off" | "none") - ) -} - -fn merge_paragraph_properties(target: &mut ParagraphProperties, source: &ParagraphProperties) { - if source.contextual_spacing.is_some() { - target.contextual_spacing = source.contextual_spacing; - } - if source.alignment.is_some() { - target.alignment = source.alignment; - } - if source.indent_left.is_some() { - target.indent_left = source.indent_left; - } - if source.indent_right.is_some() { - target.indent_right = source.indent_right; - } - if source.spacing_before.is_some() { - target.spacing_before = source.spacing_before; - } - if source.spacing_after.is_some() { - target.spacing_after = source.spacing_after; - } - if source.line_spacing.is_some() { - target.line_spacing = source.line_spacing; - } - if source.fill.is_some() { - target.fill = source.fill; - } - if source.bottom_border.is_some() { - target.bottom_border = source.bottom_border; - } -} - -fn merge_run_properties(target: &mut RunProperties, source: &RunProperties) { - if source.font_size.is_some() { - target.font_size = source.font_size; - } - if source.font_name.is_some() { - target.font_name.clone_from(&source.font_name); - target.font_theme = None; - } - if source.font_theme.is_some() { - target.font_theme = source.font_theme; - target.font_name = None; - } - if source.bold.is_some() { - target.bold = source.bold; - } - if source.italic.is_some() { - target.italic = source.italic; - } - if source.underline.is_some() { - target.underline = source.underline; - } - if source.color.is_some() { - target.color = source.color; - } - if source.highlight.is_some() { - target.highlight = source.highlight; - } -} - -fn merge_style_chain( - styles: &DocxStyles, - style_id: &str, - paragraph: &mut ParagraphProperties, - run: &mut RunProperties, - depth: usize, -) { - if depth > 16 { - return; - } - let Some(style) = styles.styles.get(style_id) else { - return; - }; - if let Some(parent) = &style.based_on { - merge_style_chain(styles, parent, paragraph, run, depth + 1); - } - merge_paragraph_properties(paragraph, &style.paragraph); - merge_run_properties(run, &style.run); -} - -fn read_paragraph( - paragraph: roxmltree::Node<'_, '_>, - blocks: &mut Vec, - styles: &DocxStyles, - relationships: &HashMap, - archive: &mut ZipArchive>, -) -> Result<()> { - if child(paragraph, "pPr") - .and_then(|properties| child(properties, "pageBreakBefore")) - .is_some_and(property_enabled) - { - blocks.push(DocxBlock::PageBreak); - } - - let direct_properties = child(paragraph, "pPr") - .map(read_paragraph_properties) - .unwrap_or_default(); - let style_id = child(paragraph, "pPr") - .and_then(|node| child(node, "pStyle")) - .and_then(|node| attribute_by_local_name(node, "val")); - let mut paragraph_properties = styles.paragraph_defaults.clone(); - let mut base_run_properties = styles.run_defaults.clone(); - if let Some(style_id) = style_id { - merge_style_chain( - styles, - style_id, - &mut paragraph_properties, - &mut base_run_properties, - 0, - ); - } - merge_paragraph_properties(&mut paragraph_properties, &direct_properties); - if let Some(properties) = child(paragraph, "pPr").and_then(|node| child(node, "rPr")) { - merge_run_properties(&mut base_run_properties, &read_run_properties(properties)); - } - - let floating_images = read_vml_floating_images(paragraph, relationships, archive)?; - - let mut runs = Vec::new(); - let mut emitted_non_text = false; - for run_node in paragraph - .descendants() - .filter(|node| node.has_tag_name("r")) - { - if run_node - .ancestors() - .any(|node| node.has_tag_name("txbxContent")) - || run_node - .descendants() - .any(|node| node.has_tag_name("txbxContent")) - { - continue; - } - if let Some(drawing) = run_node - .descendants() - .find(|node| node.has_tag_name("drawing")) - { - push_paragraph_runs(blocks, &mut runs, style_id, ¶graph_properties); - if let Some(image) = read_image(drawing, paragraph, relationships, archive)? { - blocks.push(DocxBlock::Image(image)); - emitted_non_text = true; - } - continue; - } - - let mut run_properties = base_run_properties.clone(); - if let Some(properties) = child(run_node, "rPr") { - merge_run_properties(&mut run_properties, &read_run_properties(properties)); - } - let mut text = String::new(); - for node in run_node.descendants() { - if node.has_tag_name("t") { - if let Some(value) = node.text() { - text.push_str(value); - } - } else if node.has_tag_name("tab") { - text.push('\t'); - } else if node.has_tag_name("br") { - if attribute_by_local_name(node, "type") == Some("page") { - if !text.is_empty() { - runs.push(create_run( - std::mem::take(&mut text), - &run_properties, - &styles.theme_fonts, - )); - } - push_paragraph_runs(blocks, &mut runs, style_id, ¶graph_properties); - blocks.push(DocxBlock::PageBreak); - emitted_non_text = true; - } else { - text.push('\n'); - } - } - } - if !text.is_empty() { - runs.push(create_run(text, &run_properties, &styles.theme_fonts)); - } - } - if !runs.is_empty() || !emitted_non_text { - let mut output = - create_paragraph(std::mem::take(&mut runs), style_id, ¶graph_properties); - output.floating_images = floating_images; - blocks.push(DocxBlock::Paragraph(output)); - } - Ok(()) -} - -fn read_vml_floating_images( - paragraph: roxmltree::Node<'_, '_>, - relationships: &HashMap, - archive: &mut ZipArchive>, -) -> Result> { - let mut images = Vec::new(); - for shape in paragraph - .descendants() - .filter(|node| node.has_tag_name("shape")) - { - let Some(style) = shape.attribute("style") else { - continue; - }; - if !vml_style_value(style, "position") - .is_some_and(|value| value.eq_ignore_ascii_case("absolute")) - { - continue; - } - let Some(textbox) = shape - .descendants() - .find(|node| node.has_tag_name("txbxContent")) - else { - continue; - }; - let offset_x = vml_style_point(style, "margin-left").unwrap_or(0.0); - let offset_y = vml_style_point(style, "margin-top").unwrap_or(0.0); - let (inset_left, inset_top) = vml_textbox_insets(shape); - for drawing in textbox - .descendants() - .filter(|node| node.has_tag_name("drawing")) - { - let image_paragraph = drawing - .ancestors() - .find(|node| node.has_tag_name("p")) - .unwrap_or(paragraph); - if let Some(image) = read_image(drawing, image_paragraph, relationships, archive)? { - images.push(DocxFloatingImage { - image, - offset_x, - offset_y, - inset_left, - inset_top, - line_top_leading: VML_INLINE_IMAGE_TOP_LEADING, - }); - } - } - } - Ok(images) -} - -fn vml_style_value<'a>(style: &'a str, name: &str) -> Option<&'a str> { - style.split(';').find_map(|declaration| { - let (property, value) = declaration.split_once(':')?; - property - .trim() - .eq_ignore_ascii_case(name) - .then(|| value.trim()) - }) -} - -fn vml_style_point(style: &str, name: &str) -> Option { - parse_vml_length(vml_style_value(style, name)?) -} - -fn parse_vml_length(value: &str) -> Option { - let value = value.trim(); - if let Some(points) = value.strip_suffix("pt") { - points.trim().parse().ok() - } else if let Some(inches) = value.strip_suffix("in") { - inches - .trim() - .parse::() - .ok() - .map(|length| length * 72.0) - } else if let Some(pixels) = value.strip_suffix("px") { - pixels - .trim() - .parse::() - .ok() - .map(|length| length * 0.75) - } else { - value.parse().ok() - } -} - -fn vml_textbox_insets(shape: roxmltree::Node<'_, '_>) -> (f32, f32) { - let inset = shape - .descendants() - .find(|node| node.has_tag_name("textbox")) - .and_then(|node| node.attribute("inset")); - let Some(inset) = inset else { - return (7.2, 3.6); - }; - let values: Vec<_> = inset - .split(',') - .filter_map(|value| parse_vml_length(value.trim())) - .collect(); - ( - values.first().copied().unwrap_or(7.2), - values.get(1).copied().unwrap_or(3.6), - ) -} - -fn create_run(text: String, properties: &RunProperties, theme_fonts: &DocxThemeFonts) -> DocxRun { - DocxRun { - text, - font_size: properties.font_size.unwrap_or(BODY_FONT_SIZE), - font_name: properties - .font_name - .clone() - .or_else(|| match properties.font_theme { - Some(ThemeFontReference::MajorEastAsia) => theme_fonts.major_east_asia.clone(), - Some(ThemeFontReference::MinorEastAsia) => theme_fonts.minor_east_asia.clone(), - None => None, - }), - bold: properties.bold.unwrap_or(false), - italic: properties.italic.unwrap_or(false), - underline: properties.underline.unwrap_or(false), - color: properties.color.unwrap_or(PdfColor::BLACK), - highlight: properties.highlight, - } -} - -fn create_paragraph( - runs: Vec, - style_id: Option<&str>, - properties: &ParagraphProperties, -) -> DocxParagraph { - let spacing_after = if runs.is_empty() { - 0.0 - } else { - properties.spacing_after.unwrap_or(0.0) - }; - DocxParagraph { - runs, - floating_images: Vec::new(), - style_id: style_id.map(str::to_owned), - contextual_spacing: properties.contextual_spacing.unwrap_or(false), - alignment: properties.alignment.unwrap_or(TextAlignment::Left), - indent_left: properties.indent_left.unwrap_or(0.0), - indent_right: properties.indent_right.unwrap_or(0.0), - spacing_before: properties.spacing_before.unwrap_or(0.0), - spacing_after, - line_spacing: properties.line_spacing.unwrap_or(1.15), - line_spacing_explicit: properties.line_spacing.is_some(), - fill: properties.fill, - bottom_border: properties.bottom_border, - } -} - -fn push_paragraph_runs( - blocks: &mut Vec, - runs: &mut Vec, - style_id: Option<&str>, - properties: &ParagraphProperties, -) { - if !runs.is_empty() { - blocks.push(DocxBlock::Paragraph(create_paragraph( - std::mem::take(runs), - style_id, - properties, - ))); - } -} - -fn read_document_relationships( - archive: &mut ZipArchive>, -) -> Result> { - let Some(relationships_xml) = read_zip_text(archive, "word/_rels/document.xml.rels")? else { - return Ok(HashMap::new()); - }; - let xml = roxmltree::Document::parse(&relationships_xml)?; - Ok(xml - .descendants() - .filter(|node| node.has_tag_name("Relationship")) - .filter_map(|node| { - Some(( - node.attribute("Id")?.to_owned(), - node.attribute("Target")?.to_owned(), - )) - }) - .collect()) -} - -fn read_image( - drawing: roxmltree::Node<'_, '_>, - paragraph: roxmltree::Node<'_, '_>, - relationships: &HashMap, - archive: &mut ZipArchive>, -) -> Result> { - let Some(container) = drawing - .descendants() - .find(|node| node.has_tag_name("inline")) - else { - return Ok(None); - }; - let Some(relationship_id) = container - .descendants() - .find(|node| node.has_tag_name("blip")) - .and_then(|node| attribute_by_local_name(node, "embed")) - else { - return Ok(None); - }; - let Some(target) = relationships.get(relationship_id) else { - return Ok(None); - }; - let image_path = resolve_part_target("word/document.xml", target); - let Ok(mut entry) = archive.by_name(&image_path) else { - return Ok(None); - }; - let mut bytes = Vec::with_capacity(entry.size() as usize); - entry.read_to_end(&mut bytes)?; - drop(entry); - - let (data, pixel_width, pixel_height) = if let Some((width, height)) = jpeg_dimensions(&bytes) { - ( - DocxImageData::Jpeg { - data: bytes, - width, - height, - }, - width, - height, - ) - } else { - let Ok(decoded) = image::load_from_memory(&bytes) else { - return Ok(None); - }; - let width = u16::try_from(decoded.width()).unwrap_or(u16::MAX); - let height = u16::try_from(decoded.height()).unwrap_or(u16::MAX); - ( - DocxImageData::Rgba { - data: decoded.into_rgba8().into_raw(), - width, - height, - }, - width, - height, - ) - }; - let extent = child(container, "extent"); - let width = extent - .and_then(|node| numeric_attribute(node, "cx")) - .map(|emu| emu / 12_700.0) - .unwrap_or(pixel_width as f32 * 0.75); - let height = extent - .and_then(|node| numeric_attribute(node, "cy")) - .map(|emu| emu / 12_700.0) - .unwrap_or(pixel_height as f32 * 0.75); - - Ok(Some(DocxImage { - data, - width, - height, - alignment: paragraph_alignment(paragraph), - })) -} - -fn resolve_part_target(source_part: &str, target: &str) -> String { - let combined = if target.starts_with('/') { - target.trim_start_matches('/').to_owned() - } else { - let parent = source_part - .rsplit_once('/') - .map(|(path, _)| path) - .unwrap_or(""); - format!("{parent}/{target}") - }; - let normalized = combined.replace('\\', "/"); - let mut segments = Vec::new(); - for segment in normalized.split('/') { - match segment { - "" | "." => {} - ".." => { - segments.pop(); - } - _ => segments.push(segment), - } - } - segments.join("/") -} - -fn jpeg_dimensions(data: &[u8]) -> Option<(u16, u16)> { - if !data.starts_with(&[0xff, 0xd8]) { - return None; - } - let mut index = 2; - while index + 3 < data.len() { - while index < data.len() && data[index] != 0xff { - index += 1; - } - while index < data.len() && data[index] == 0xff { - index += 1; - } - if index >= data.len() { - break; - } - let marker = data[index]; - index += 1; - if matches!(marker, 0xd8 | 0xd9) { - continue; - } - if index + 1 >= data.len() { - break; - } - let segment_length = u16::from_be_bytes([data[index], data[index + 1]]) as usize; - if segment_length < 2 || index + segment_length > data.len() { - break; - } - if matches!(marker, 0xc0..=0xc3 | 0xc5..=0xc7 | 0xc9..=0xcb | 0xcd..=0xcf) - && segment_length >= 7 - { - let height = u16::from_be_bytes([data[index + 3], data[index + 4]]); - let width = u16::from_be_bytes([data[index + 5], data[index + 6]]); - return Some((width, height)); - } - index += segment_length; - } - None -} - -fn read_table( - table: roxmltree::Node<'_, '_>, - styles: &DocxStyles, - relationships: &HashMap, - archive: &mut ZipArchive>, - legacy_cjk_metrics: bool, -) -> Result { - let properties = child(table, "tblPr"); - let cell_margins = properties.and_then(|node| child(node, "tblCellMar")); - let style_id = properties - .and_then(|node| child(node, "tblStyle")) - .and_then(|node| attribute_by_local_name(node, "val")); - let style_has_grid = style_id == Some("af2"); - let use_style_borders = style_has_grid - && properties - .and_then(|node| child(node, "tblBorders")) - .is_none(); - let column_widths = child(table, "tblGrid") - .map(|grid| { - grid.children() - .filter(|node| node.has_tag_name("gridCol")) - .filter_map(|node| twips_attribute(Some(node), "w")) - .collect() - }) - .unwrap_or_default(); - let mut rows = Vec::new(); - for row in table.children().filter(|node| node.has_tag_name("tr")) { - let height = child(row, "trPr") - .and_then(|node| child(node, "trHeight")) - .and_then(|node| twips_attribute(Some(node), "val")); - let mut cells = Vec::new(); - for cell in row.children().filter(|node| node.has_tag_name("tc")) { - cells.push(read_table_cell( - cell, - styles, - relationships, - archive, - use_style_borders, - )?); - } - rows.push(DocxTableRow { cells, height }); - } - Ok(DocxTable { - column_widths, - rows, - alignment: properties - .and_then(|node| child(node, "jc")) - .and_then(|node| attribute_by_local_name(node, "val")) - .map(parse_alignment) - .unwrap_or(TextAlignment::Left), - cell_margin_left: table_margin(cell_margins, "left", TABLE_CELL_PADDING_HORIZONTAL), - cell_margin_right: table_margin(cell_margins, "right", TABLE_CELL_PADDING_HORIZONTAL), - cell_margin_top: table_margin(cell_margins, "top", 0.0), - cell_margin_bottom: table_margin(cell_margins, "bottom", 0.0), - legacy_cjk_metrics, - }) -} - -fn table_margin(margins: Option>, side: &str, default: f32) -> f32 { - margins - .and_then(|node| child(node, side)) - .and_then(|node| twips_attribute(Some(node), "w")) - .unwrap_or(default) -} - -fn read_table_cell( - cell: roxmltree::Node<'_, '_>, - styles: &DocxStyles, - relationships: &HashMap, - archive: &mut ZipArchive>, - use_style_borders: bool, -) -> Result { - let properties = child(cell, "tcPr"); - let paragraphs: Vec<_> = cell - .children() - .filter(|node| node.has_tag_name("p")) - .collect(); - let mut runs: Vec = Vec::new(); - for paragraph in ¶graphs { - let paragraph_runs = read_table_cell_runs(*paragraph, styles); - if paragraph_runs.is_empty() { - continue; - } - if let Some(previous) = runs.last_mut() { - previous.text.push('\n'); - } - runs.extend(paragraph_runs); - } - let first_paragraph = paragraphs.first().copied(); - let first_paragraph_properties = first_paragraph - .and_then(|paragraph| child(paragraph, "pPr")) - .map(read_paragraph_properties) - .unwrap_or_default(); - let mut images = Vec::new(); - for paragraph in ¶graphs { - for drawing in paragraph - .descendants() - .filter(|node| node.has_tag_name("drawing")) - { - if let Some(image) = read_image(drawing, *paragraph, relationships, archive)? { - images.push(image); - } - } - } - - Ok(DocxTableCell { - runs, - images, - width: properties - .and_then(|node| child(node, "tcW")) - .and_then(|node| twips_attribute(Some(node), "w")), - spacing_before: first_paragraph_properties.spacing_before.unwrap_or(0.0), - spacing_after: first_paragraph_properties.spacing_after.unwrap_or(0.0), - line_spacing: first_paragraph_properties.line_spacing.unwrap_or(1.0), - fill: properties - .and_then(|node| child(node, "shd")) - .and_then(|node| attribute_by_local_name(node, "fill")) - .and_then(parse_hex_color), - alignment: first_paragraph - .and_then(|node| node.descendants().find(|child| child.has_tag_name("jc"))) - .and_then(|node| attribute_by_local_name(node, "val")) - .map(|value| match value { - "center" => TextAlignment::Center, - "right" | "end" => TextAlignment::Right, - _ => TextAlignment::Left, - }) - .unwrap_or(TextAlignment::Left), - vertical_alignment: properties - .and_then(|node| child(node, "vAlign")) - .and_then(|node| attribute_by_local_name(node, "val")) - .map(|value| match value { - "center" => VerticalAlignment::Center, - "bottom" => VerticalAlignment::Bottom, - _ => VerticalAlignment::Top, - }) - .unwrap_or(VerticalAlignment::Top), - grid_span: properties - .and_then(|node| child(node, "gridSpan")) - .and_then(|node| numeric_attribute(node, "val")) - .map(|value| value.max(1.0) as usize) - .unwrap_or(1), - vertical_merge: properties - .and_then(|node| child(node, "vMerge")) - .map(|node| match attribute_by_local_name(node, "val") { - Some("restart") => VerticalMerge::Restart, - _ => VerticalMerge::Continue, - }) - .unwrap_or(VerticalMerge::None), - borders: DocxCellBorders { - top: read_cell_border(properties, "top", use_style_borders), - right: read_cell_border(properties, "right", use_style_borders), - bottom: read_cell_border(properties, "bottom", use_style_borders), - left: read_cell_border(properties, "left", use_style_borders), - }, - }) -} - -fn read_table_cell_runs(paragraph: roxmltree::Node<'_, '_>, styles: &DocxStyles) -> Vec { - let style_id = child(paragraph, "pPr") - .and_then(|node| child(node, "pStyle")) - .and_then(|node| attribute_by_local_name(node, "val")); - let mut paragraph_properties = styles.paragraph_defaults.clone(); - let mut base_run_properties = styles.run_defaults.clone(); - if let Some(style_id) = style_id { - merge_style_chain( - styles, - style_id, - &mut paragraph_properties, - &mut base_run_properties, - 0, - ); - } - if let Some(properties) = child(paragraph, "pPr").and_then(|node| child(node, "rPr")) { - merge_run_properties(&mut base_run_properties, &read_run_properties(properties)); - } - - paragraph - .descendants() - .filter(|node| node.has_tag_name("r")) - .filter_map(|run_node| { - let mut properties = base_run_properties.clone(); - if let Some(direct) = child(run_node, "rPr") { - merge_run_properties(&mut properties, &read_run_properties(direct)); - } - let text = paragraph_text(run_node); - (!text.is_empty()).then(|| create_run(text, &properties, &styles.theme_fonts)) - }) - .collect() -} - -fn read_cell_border( - properties: Option>, - side: &str, - use_style_border: bool, -) -> Option { - let border = properties - .and_then(|node| child(node, "tcBorders")) - .and_then(|node| child(node, side)); - match border { - Some(border) => read_border(border), - None if use_style_border => Some(default_table_border()), - None => None, - } -} - -fn paragraph_text(paragraph: roxmltree::Node<'_, '_>) -> String { - let mut text = String::new(); - for node in paragraph.descendants() { - if node.has_tag_name("t") { - if let Some(value) = node.text() { - text.push_str(value); - } - } else if node.has_tag_name("tab") { - text.push('\t'); - } else if node.has_tag_name("br") { - text.push('\n'); - } - } - text -} - -fn paragraph_alignment(paragraph: roxmltree::Node<'_, '_>) -> TextAlignment { - paragraph - .descendants() - .find(|node| node.has_tag_name("jc")) - .and_then(|node| attribute_by_local_name(node, "val")) - .map(|value| match value { - "center" => TextAlignment::Center, - "right" | "end" => TextAlignment::Right, - _ => TextAlignment::Left, - }) - .unwrap_or(TextAlignment::Left) -} - -fn child<'a, 'input>( - node: roxmltree::Node<'a, 'input>, - local_name: &str, -) -> Option> { - node.children().find(|child| child.has_tag_name(local_name)) -} - -fn twips_attribute(node: Option>, name: &str) -> Option { - node.and_then(|node| numeric_attribute(node, name)) - .map(|twips| twips / 20.0) -} - -fn numeric_attribute(node: roxmltree::Node<'_, '_>, name: &str) -> Option { - attribute_by_local_name(node, name)?.parse().ok() -} - -fn parse_hex_color(value: &str) -> Option { - if value.len() != 6 || value.eq_ignore_ascii_case("auto") { - return None; - } - let red = u8::from_str_radix(&value[0..2], 16).ok()?; - let green = u8::from_str_radix(&value[2..4], 16).ok()?; - let blue = u8::from_str_radix(&value[4..6], 16).ok()?; - Some(PdfColor::new( - red as f32 / 255.0, - green as f32 / 255.0, - blue as f32 / 255.0, - )) -} - -fn attribute_by_local_name<'a, 'input>( - node: roxmltree::Node<'a, 'input>, - local_name: &str, -) -> Option<&'a str> { - node.attributes() - .find(|attribute| attribute.name() == local_name) - .map(|attribute| attribute.value()) -} - -fn render_docx(doc: &mut PdfDocument, document: &DocxDocument, options: &ConversionOptions) { - let mut page_index = doc.pages().len(); - let page_size = options.page_size.unwrap_or(document.page_size); - let margins = document.margins; - doc.add_page(page_size.width, page_size.height); - let mut y = page_size.height - margins.top - BODY_FONT_SIZE; - let max_width = page_size.width - margins.left - margins.right; - - for (block_index, block) in document.blocks.iter().enumerate() { - match block { - DocxBlock::PageBreak => { - page_index = doc.pages().len(); - doc.add_page(page_size.width, page_size.height); - y = page_size.height - margins.top - BODY_FONT_SIZE; - } - DocxBlock::Paragraph(paragraph) => { - if block_index + 1 == document.blocks.len() - && paragraph.runs.is_empty() - && paragraph.fill.is_none() - && paragraph.bottom_border.is_none() - { - continue; - } - let previous_paragraph = - block_index - .checked_sub(1) - .and_then(|index| match document.blocks.get(index) { - Some(DocxBlock::Paragraph(previous)) => Some(previous), - _ => None, - }); - let previous_spacing_after = previous_paragraph.map_or(0.0, |previous| { - if previous.contextual_spacing && previous.style_id == paragraph.style_id { - 0.0 - } else { - previous.spacing_after - } - }); - let spacing_before = if document.compatibility_mode <= 12 { - paragraph.spacing_before - } else if previous_paragraph.is_some() { - (paragraph.spacing_before - previous_spacing_after).max(0.0) - } else { - paragraph.spacing_before - }; - let spacing_after = if paragraph.contextual_spacing - && matches!( - document.blocks.get(block_index + 1), - Some(DocxBlock::Paragraph(next)) if next.style_id == paragraph.style_id - ) { - 0.0 - } else { - paragraph.spacing_after - }; - let previous_grid_ascent = previous_paragraph - .map(|previous| paragraph_line_metrics(previous, document.grid_line_pitch).2); - render_paragraph( - doc, - paragraph, - ( - spacing_before, - spacing_after, - document.grid_line_pitch, - previous_grid_ascent, - ), - page_size, - margins, - &mut page_index, - &mut y, - ); - } - DocxBlock::Table(table) => render_table( - doc, - table, - page_size, - margins, - max_width, - &mut page_index, - &mut y, - ), - DocxBlock::Image(image) => render_image( - doc, - image, - page_size, - margins, - max_width, - &mut page_index, - &mut y, - ), - } - } -} - -fn render_paragraph( - doc: &mut PdfDocument, - paragraph: &DocxParagraph, - layout: (f32, f32, f32, Option), - page_size: PageSize, - margins: DocxMargins, - page_index: &mut usize, - y: &mut f32, -) { - let (spacing_before, spacing_after, grid_line_pitch, previous_grid_ascent) = layout; - let (_, line_height, baseline_offset) = paragraph_line_metrics(paragraph, grid_line_pitch); - let available_width = (page_size.width - - margins.left - - margins.right - - paragraph.indent_left - - paragraph.indent_right) - .max(1.0); - let lines = wrap_paragraph_runs(¶graph.runs, available_width); - let line_count = lines.len().max(1); - let content_height = line_count as f32 * line_height; - let total_height = spacing_before + content_height + spacing_after; - let mut top = *y + BODY_FONT_SIZE; - if top - total_height < margins.bottom { - *page_index = doc.pages().len(); - doc.add_page(page_size.width, page_size.height); - top = page_size.height - margins.top; - } - top -= spacing_before; - if grid_line_pitch > 0.0 { - if let Some(previous_ascent) = previous_grid_ascent.filter(|ascent| *ascent > 0.0) { - top -= baseline_offset - previous_ascent; - } - } - let left = margins.left + paragraph.indent_left; - let bottom = top - content_height; - if let Some(fill) = paragraph.fill { - doc.page_mut(*page_index) - .expect("page index is valid") - .add_rect(left, bottom, available_width, content_height, fill); - } - - for (line_index, line) in lines.iter().enumerate() { - let line_width: f32 = line.iter().map(|run| run_width(run, &run.text)).sum(); - let mut x = match paragraph.alignment { - TextAlignment::Left => left, - TextAlignment::Center => left + (available_width - line_width) / 2.0, - TextAlignment::Right => left + available_width - line_width, - }; - let baseline = top - baseline_offset - line_index as f32 * line_height; - for run in line { - let width = run_width(run, &run.text); - let page = doc.page_mut(*page_index).expect("page index is valid"); - page.add_styled_text_with_font( - &run.text, - x, - baseline, - run.font_size, - run.color, - run.bold, - run.italic, - run.font_name.as_deref(), - ); - if run.underline && !run.text.trim().is_empty() { - page.add_line(x, baseline - 1.5, x + width, baseline - 1.5, run.color, 0.5); - } - x += width; - } - } - - for floating in ¶graph.floating_images { - let image_id = register_image(doc, &floating.image); - doc.page_mut(*page_index) - .expect("page index is valid") - .add_image( - image_id, - margins.left + floating.offset_x + floating.inset_left, - top - floating.offset_y - - floating.inset_top - - floating.line_top_leading - - floating.image.height, - floating.image.width, - floating.image.height, - ); - } - - if let Some(border) = paragraph.bottom_border { - let border_y = bottom - border.space; - let page = doc.page_mut(*page_index).expect("page index is valid"); - draw_border( - page, - (left, border_y), - (left + available_width, border_y), - border, - ); - if border.is_double { - draw_border( - page, - (left, border_y - border.width * 2.0), - (left + available_width, border_y - border.width * 2.0), - border, - ); - } - } - *y = top - content_height - spacing_after - BODY_FONT_SIZE; -} - -fn paragraph_line_metrics(paragraph: &DocxParagraph, grid_line_pitch: f32) -> (f32, f32, f32) { - let font_size = paragraph - .runs - .iter() - .map(|run| run.font_size) - .fold(BODY_FONT_SIZE, f32::max); - let mut line_height = font_size * 1.18 * paragraph.line_spacing; - if grid_line_pitch <= 0.0 { - return (font_size, line_height, font_size); - } - - if paragraph.line_spacing_explicit { - line_height = line_height.max(grid_line_pitch * paragraph.line_spacing); - let text_length: usize = paragraph - .runs - .iter() - .map(|run| run.text.chars().count()) - .sum(); - let is_centered_cjk_heading = paragraph.alignment == TextAlignment::Center - && font_size >= 14.0 - && text_length <= 12 - && paragraph - .runs - .iter() - .any(|run| run.text.chars().any(is_cjk_character)); - if is_centered_cjk_heading { - line_height = - line_height.max((font_size * 1.29 / grid_line_pitch).ceil() * grid_line_pitch); - } - } else if font_size <= grid_line_pitch { - line_height = grid_line_pitch; - } else { - line_height = line_height.max(grid_line_pitch); - } - - let font_name = paragraph - .runs - .iter() - .find_map(|run| run.font_name.as_deref()); - let baseline_offset = if font_name.is_some_and(is_tall_cjk_font_name) { - (line_height - font_size) / 2.0 + font_size * 0.86 - } else { - (line_height + font_size) / 2.0 - }; - (font_size, line_height, baseline_offset) -} - -fn is_cjk_character(ch: char) -> bool { - matches!(ch as u32, 0x2e80..=0x9fff | 0xf900..=0xfaff) -} - -fn is_tall_cjk_font_name(font_name: &str) -> bool { - let normalized = font_name.trim().to_ascii_lowercase(); - [ - "kaiti", - "simsun", - "simhei", - "nsimsun", - "fangsong", - "dengxian", - "microsoft yahei", - ] - .iter() - .any(|name| normalized.contains(name)) - || ["宋体", "黑体", "楷体", "仿宋", "等线", "微软雅黑"] - .iter() - .any(|name| font_name.contains(name)) -} - -fn wrap_paragraph_runs(runs: &[DocxRun], max_width: f32) -> Vec> { - let mut lines = vec![Vec::new()]; - let mut line_width = 0.0; - for run in runs { - let mut segment = String::new(); - for ch in run.text.chars() { - if ch == '\n' { - push_run_segment(lines.last_mut().expect("line exists"), run, &mut segment); - lines.push(Vec::new()); - line_width = 0.0; - continue; - } - let char_width = run_width(run, &ch.to_string()); - if line_width + char_width > max_width && line_width > 0.0 { - push_run_segment(lines.last_mut().expect("line exists"), run, &mut segment); - lines.push(Vec::new()); - line_width = 0.0; - } - segment.push(ch); - line_width += char_width; - } - push_run_segment(lines.last_mut().expect("line exists"), run, &mut segment); - } - lines -} - -fn push_run_segment(line: &mut Vec, run: &DocxRun, segment: &mut String) { - if segment.is_empty() { - return; - } - let mut output = run.clone(); - output.text = std::mem::take(segment); - line.push(output); -} - -fn run_width(run: &DocxRun, text: &str) -> f32 { - styled_text_width_with_font( - text, - run.font_size, - run.bold, - run.italic, - run.font_name.as_deref(), - ) -} - -fn render_image( - doc: &mut PdfDocument, - image: &DocxImage, - page_size: PageSize, - margins: DocxMargins, - max_width: f32, - page_index: &mut usize, - y: &mut f32, -) { - let mut width = image.width; - let mut height = image.height; - if width > max_width { - let scale = max_width / width; - width *= scale; - height *= scale; - } - let mut top = *y + BODY_FONT_SIZE; - if top - height < margins.bottom { - *page_index = doc.pages().len(); - doc.add_page(page_size.width, page_size.height); - top = page_size.height - margins.top; - } - let x = match image.alignment { - TextAlignment::Left => margins.left, - TextAlignment::Center => margins.left + (max_width - width) / 2.0, - TextAlignment::Right => page_size.width - margins.right - width, - }; - let image_id = match &image.data { - DocxImageData::Jpeg { - data, - width, - height, - } => doc.add_jpeg_image(data.clone(), *width, *height), - DocxImageData::Rgba { - data, - width, - height, - } => doc.add_rgba_image(data.clone(), *width, *height), - }; - doc.page_mut(*page_index) - .expect("page index is valid") - .add_image(image_id, x, top - height, width, height); - *y = top - height - BODY_FONT_SIZE; -} - -fn render_table( - doc: &mut PdfDocument, - table: &DocxTable, - page_size: PageSize, - margins: DocxMargins, - max_width: f32, - page_index: &mut usize, - y: &mut f32, -) { - let max_columns = table - .rows - .iter() - .map(|row| row.cells.iter().map(|cell| cell.grid_span).sum()) - .max() - .unwrap_or(0); - if max_columns == 0 { - return; - } - let mut widths = if table.column_widths.len() >= max_columns { - table.column_widths[..max_columns].to_vec() - } else { - let inferred_widths: Vec<_> = (0..max_columns) - .map(|index| { - table - .rows - .iter() - .find_map(|row| row.cells.get(index).and_then(|cell| cell.width)) - }) - .collect(); - if inferred_widths.iter().all(Option::is_some) { - inferred_widths.into_iter().flatten().collect() - } else { - vec![max_width / max_columns as f32; max_columns] - } - }; - let width_sum: f32 = widths.iter().sum(); - if width_sum > max_width && width_sum > 0.0 { - let scale = max_width / width_sum; - for width in &mut widths { - *width *= scale; - } - } - - let table_width: f32 = widths.iter().sum(); - let table_left = match table.alignment { - TextAlignment::Left => margins.left, - TextAlignment::Center => margins.left + (max_width - table_width) / 2.0, - TextAlignment::Right => page_size.width - margins.right - table_width, - }; - - let mut row_heights: Vec = table - .rows - .iter() - .map(|row| { - let mut grid_index = 0; - let content_height = row - .cells - .iter() - .map(|cell| { - let width = spanned_width(&widths, grid_index, cell.grid_span); - grid_index += cell.grid_span; - if cell.vertical_merge != VerticalMerge::None { - return 0.0; - } - table_cell_content_height(table, cell, width) - }) - .fold(0.0_f32, f32::max) - .max(BODY_FONT_SIZE); - row.height - .map_or(content_height, |height| height.max(content_height)) - }) - .collect(); - - for (row_index, row) in table.rows.iter().enumerate() { - let mut grid_index = 0; - for cell in &row.cells { - if cell.vertical_merge == VerticalMerge::Restart { - let mut end_row = row_index; - for next_row in (row_index + 1)..table.rows.len() { - let Some(next_cell) = cell_at_grid(&table.rows[next_row], grid_index) else { - break; - }; - if next_cell.vertical_merge != VerticalMerge::Continue { - break; - } - end_row = next_row; - } - let width = spanned_width(&widths, grid_index, cell.grid_span); - let required_height = table_cell_content_height(table, cell, width); - let current_height: f32 = row_heights[row_index..=end_row].iter().sum(); - if required_height > current_height { - row_heights[end_row] += required_height - current_height; - } - } - grid_index += cell.grid_span; - } - } - - let mut row_top = *y + BODY_FONT_SIZE; - for (row_index, row) in table.rows.iter().enumerate() { - let row_height = row_heights[row_index]; - - if row_top - row_height < margins.bottom { - *page_index = doc.pages().len(); - doc.add_page(page_size.width, page_size.height); - row_top = page_size.height - margins.top; - } - - let mut grid_index = 0; - for cell in &row.cells { - let x = table_left + widths.iter().take(grid_index).sum::(); - let width = spanned_width(&widths, grid_index, cell.grid_span); - if cell.vertical_merge == VerticalMerge::Continue { - grid_index += cell.grid_span; - continue; - } - let cell_height = if cell.vertical_merge == VerticalMerge::Restart { - merged_cell_height(table, &row_heights, row_index, grid_index) - } else { - row_height - }; - let bottom = row_top - cell_height; - let page = doc.page_mut(*page_index).expect("page index is valid"); - if let Some(fill) = cell.fill { - page.add_rect(x, bottom, width, cell_height, fill); - } - let wrapped_lines = wrap_table_cell_runs( - &cell.runs, - (width - table.cell_margin_left - table.cell_margin_right).max(1.0), - ); - let line_height = table_cell_line_height(table, cell); - let text_height = wrapped_lines.len() as f32 * line_height; - let font_size = table_cell_font_size(cell); - let image_height: f32 = cell - .images - .iter() - .map(|image| { - image_render_size( - image, - (width - table.cell_margin_left - table.cell_margin_right).max(1.0), - ) - .1 - }) - .sum(); - let content_height = - cell.spacing_before + text_height + image_height + cell.spacing_after; - let content_top = match cell.vertical_alignment { - VerticalAlignment::Top => row_top - table.cell_margin_top, - VerticalAlignment::Center => bottom + (cell_height + content_height) / 2.0, - VerticalAlignment::Bottom => bottom + table.cell_margin_bottom + content_height, - }; - let mut text_y = content_top - cell.spacing_before - font_size; - for line in &wrapped_lines { - let text_width: f32 = line.iter().map(|run| run_width(run, &run.text)).sum(); - let text_x = match cell.alignment { - TextAlignment::Left => x + table.cell_margin_left, - TextAlignment::Center => x + (width - text_width) / 2.0, - TextAlignment::Right => x + width - table.cell_margin_right - text_width, - }; - let mut run_x = text_x.max(x + TABLE_BORDER_WIDTH); - for run in line { - let width = run_width(run, &run.text); - if let Some(highlight) = run.highlight { - page.add_rect( - run_x - 0.7, - text_y - run.font_size * 0.24, - width + 1.4, - run.font_size * 1.18, - highlight, - ); - } - page.add_styled_text_with_font( - &run.text, - run_x, - text_y, - run.font_size, - run.color, - run.bold, - run.italic, - run.font_name.as_deref(), - ); - run_x += width; - } - text_y -= line_height; - } - let mut image_top = content_top - cell.spacing_before - text_height; - for image in &cell.images { - let (image_width, image_height) = image_render_size( - image, - (width - table.cell_margin_left - table.cell_margin_right).max(1.0), - ); - let image_x = match image.alignment { - TextAlignment::Left => x + table.cell_margin_left, - TextAlignment::Center => x + (width - image_width) / 2.0, - TextAlignment::Right => x + width - table.cell_margin_right - image_width, - }; - let image_id = register_image(doc, image); - doc.page_mut(*page_index) - .expect("page index is valid") - .add_image( - image_id, - image_x, - image_top - image_height, - image_width, - image_height, - ); - image_top -= image_height; - } - let page = doc.page_mut(*page_index).expect("page index is valid"); - if let Some(border) = cell.borders.top { - draw_border(page, (x, row_top), (x + width, row_top), border); - } - if let Some(border) = cell.borders.bottom { - draw_border(page, (x, bottom), (x + width, bottom), border); - } - if let Some(border) = cell.borders.left { - draw_border(page, (x, bottom), (x, row_top), border); - } - if let Some(border) = cell.borders.right { - draw_border(page, (x + width, bottom), (x + width, row_top), border); - } - grid_index += cell.grid_span; - } - row_top -= row_height; - } - *y = row_top - BODY_FONT_SIZE; -} - -fn draw_border( - page: &mut crate::pdf::PdfPage, - start: (f32, f32), - end: (f32, f32), - border: DocxBorder, -) { - let pattern: &[f32] = match border.pattern { - BorderPattern::Solid => &[], - BorderPattern::DotDash => &[1.0, 1.0, 3.0, 1.0], - BorderPattern::Dotted => &[0.8, 1.2], - BorderPattern::Dashed => &[3.0, 2.0], - }; - page.add_line_with_dash_pattern(start, end, border.color, border.width, pattern); -} - -fn spanned_width(widths: &[f32], grid_index: usize, grid_span: usize) -> f32 { - widths.iter().skip(grid_index).take(grid_span).sum() -} - -fn merged_cell_height( - table: &DocxTable, - row_heights: &[f32], - start_row: usize, - grid_index: usize, -) -> f32 { - let mut height = row_heights[start_row]; - for (row_index, row) in table.rows.iter().enumerate().skip(start_row + 1) { - let Some(cell) = cell_at_grid(row, grid_index) else { - break; - }; - if cell.vertical_merge != VerticalMerge::Continue { - break; - } - height += row_heights[row_index]; - } - height -} - -fn cell_at_grid(row: &DocxTableRow, target_grid_index: usize) -> Option<&DocxTableCell> { - let mut grid_index = 0; - for cell in &row.cells { - if grid_index == target_grid_index { - return Some(cell); - } - grid_index += cell.grid_span; - } - None -} - -fn table_cell_content_height(table: &DocxTable, cell: &DocxTableCell, width: f32) -> f32 { - let content_width = (width - table.cell_margin_left - table.cell_margin_right).max(1.0); - let lines = wrap_table_cell_runs(&cell.runs, content_width); - let text_height = cell.spacing_before - + lines.len() as f32 * table_cell_line_height(table, cell) - + cell.spacing_after; - let image_height: f32 = cell - .images - .iter() - .map(|image| image_render_size(image, content_width).1) - .sum(); - text_height + image_height + table.cell_margin_top + table.cell_margin_bottom -} - -fn table_cell_line_height(table: &DocxTable, cell: &DocxTableCell) -> f32 { - let metrics_factor = if table.legacy_cjk_metrics - && cell - .runs - .iter() - .filter_map(|run| run.font_name.as_deref()) - .any(is_tall_cjk_font_name) - { - 1.35 - } else { - 1.18 - }; - table_cell_font_size(cell) * metrics_factor * cell.line_spacing -} - -fn table_cell_font_size(cell: &DocxTableCell) -> f32 { - cell.runs - .iter() - .map(|run| run.font_size) - .reduce(f32::max) - .unwrap_or(BODY_FONT_SIZE) -} - -fn image_render_size(image: &DocxImage, max_width: f32) -> (f32, f32) { - if image.width <= max_width { - return (image.width, image.height); - } - let scale = max_width / image.width; - (image.width * scale, image.height * scale) -} - -fn register_image(doc: &mut PdfDocument, image: &DocxImage) -> usize { - match &image.data { - DocxImageData::Jpeg { - data, - width, - height, - } => doc.add_jpeg_image(data.clone(), *width, *height), - DocxImageData::Rgba { - data, - width, - height, - } => doc.add_rgba_image(data.clone(), *width, *height), - } -} - -fn wrap_table_cell_runs(runs: &[DocxRun], max_width: f32) -> Vec> { - let Some(first_run) = runs.first() else { - return Vec::new(); - }; - let mut measurement_run = first_run.clone(); - measurement_run.font_name = runs.iter().find_map(|run| run.font_name.clone()); - let (text, styled_characters) = normalize_table_cell_runs(runs); - let wrapped_text = wrap_styled_text_with_font( - &text, - max_width, - measurement_run.font_size, - measurement_run.bold, - measurement_run.italic, - measurement_run.font_name.as_deref(), - ); - let mut characters = styled_characters.into_iter(); - wrapped_text - .into_iter() - .map(|line| { - let mut output = Vec::new(); - for _ in line.chars() { - if let Some(character) = characters.next() { - push_styled_character(&mut output, character); - } - } - output - }) - .collect() -} - -fn normalize_table_cell_runs(runs: &[DocxRun]) -> (String, Vec) { - let mut text = String::new(); - let mut characters = Vec::new(); - let mut pending_space = false; - let mut line_has_text = false; - for run in runs { - for character in run.text.replace('\t', " ").chars() { - if character == '\n' { - text.push('\n'); - pending_space = false; - line_has_text = false; - } else if character.is_whitespace() { - pending_space = line_has_text; - } else { - if pending_space { - let mut space = run.clone(); - space.text = " ".to_owned(); - text.push(' '); - characters.push(space); - } - let mut styled_character = run.clone(); - styled_character.text = character.to_string(); - text.push(character); - characters.push(styled_character); - pending_space = false; - line_has_text = true; - } - } - } - (text, characters) -} - -fn push_styled_character(line: &mut Vec, character: DocxRun) { - if let Some(last) = line.last_mut() { - if same_run_style(last, &character) { - last.text.push_str(&character.text); - return; - } - } - line.push(character); -} - -fn same_run_style(left: &DocxRun, right: &DocxRun) -> bool { - left.font_size == right.font_size - && left.font_name == right.font_name - && left.bold == right.bold - && left.italic == right.italic - && left.underline == right.underline - && left.color == right.color - && left.highlight == right.highlight -} - -fn wrap_styled_text_with_font( - text: &str, - max_width: f32, - font_size: f32, - bold: bool, - italic: bool, - font_name: Option<&str>, -) -> Vec { - let text = text.replace('\t', " "); - let mut lines = Vec::new(); - - for forced_line in text.lines() { - let mut current = String::new(); - for word in forced_line.split_whitespace() { - let candidate = if current.is_empty() { - word.to_owned() - } else { - format!("{current} {word}") - }; - - if styled_text_width_with_font(&candidate, font_size, bold, italic, font_name) - <= max_width - { - current = candidate; - } else if word.chars().next().is_some_and(is_forbidden_line_start) - && !current.is_empty() - { - let trailing = current.pop().expect("preceding character exists"); - if !current.is_empty() { - lines.push(std::mem::take(&mut current)); - } - current.push(trailing); - current.push_str(word); - } else { - if !current.is_empty() { - lines.push(current); - } - current = append_wrapped_word( - &mut lines, word, max_width, font_size, bold, italic, font_name, - ); - } - } - - if current.is_empty() { - lines.push(String::new()); - } else { - lines.push(current); - } - } - - lines -} - -fn append_wrapped_word( - lines: &mut Vec, - word: &str, - max_width: f32, - font_size: f32, - bold: bool, - italic: bool, - font_name: Option<&str>, -) -> String { - if styled_text_width_with_font(word, font_size, bold, italic, font_name) <= max_width { - return word.to_owned(); - } - - let mut chunks = split_word_to_width(word, max_width, font_size, bold, italic, font_name); - let current = chunks.pop().unwrap_or_default(); - for chunk in chunks { - lines.push(chunk); - } - current -} - -fn split_word_to_width( - word: &str, - max_width: f32, - font_size: f32, - bold: bool, - italic: bool, - font_name: Option<&str>, -) -> Vec { - let mut chunks = Vec::new(); - let mut current = String::new(); - - for ch in word.chars() { - let mut candidate = current.clone(); - candidate.push(ch); - if !current.is_empty() - && styled_text_width_with_font(&candidate, font_size, bold, italic, font_name) - > max_width - { - if is_forbidden_line_start(ch) { - let trailing = current.pop().expect("preceding character exists"); - if !current.is_empty() { - chunks.push(std::mem::take(&mut current)); - } - current.push(trailing); - } else if current.chars().last().is_some_and(is_forbidden_line_end) { - let opening = current.pop().expect("line-ending character exists"); - if !current.is_empty() { - chunks.push(std::mem::take(&mut current)); - } - current.push(opening); - } else { - chunks.push(std::mem::take(&mut current)); - } - } - current.push(ch); - } - - if !current.is_empty() { - chunks.push(current); - } - - chunks -} - -fn is_forbidden_line_end(ch: char) -> bool { - matches!( - ch, - '(' | '[' | '{' | '(' | '[' | '{' | '《' | '〈' | '「' | '『' - ) -} - -fn is_forbidden_line_start(ch: char) -> bool { - matches!( - ch, - ')' | ']' | '}' | ')' | ']' | '}' | '》' | '〉' | '」' | '』' - ) -} - -#[cfg(test)] -mod tests { - use std::io::{Cursor, Write}; - - use zip::write::SimpleFileOptions; - - use super::{ - convert_docx_bytes, plain_paragraph, read_docx_document, wrap_styled_text_with_font, - DocxBlock, DocxImageData, - }; - use crate::ConversionOptions; - - fn create_docx(document_xml: &str) -> Vec { - let mut output = Cursor::new(Vec::new()); - { - let mut archive = zip::ZipWriter::new(&mut output); - archive - .start_file("word/document.xml", SimpleFileOptions::default()) - .unwrap(); - archive.write_all(document_xml.as_bytes()).unwrap(); - archive.finish().unwrap(); - } - output.into_inner() - } - - fn create_docx_with_settings(document_xml: &str, settings_xml: &str) -> Vec { - let mut output = Cursor::new(Vec::new()); - { - let mut archive = zip::ZipWriter::new(&mut output); - for (path, data) in [ - ("word/document.xml", document_xml.as_bytes()), - ("word/settings.xml", settings_xml.as_bytes()), - ] { - archive - .start_file(path, SimpleFileOptions::default()) - .unwrap(); - archive.write_all(data).unwrap(); - } - archive.finish().unwrap(); - } - output.into_inner() - } - - fn create_docx_with_image(document_xml: &str, relationships_xml: &str) -> Vec { - let image = image::RgbaImage::from_pixel(2, 1, image::Rgba([0, 0, 255, 255])); - let mut png = Cursor::new(Vec::new()); - image::DynamicImage::ImageRgba8(image) - .write_to(&mut png, image::ImageFormat::Png) - .unwrap(); - - let mut output = Cursor::new(Vec::new()); - { - let mut archive = zip::ZipWriter::new(&mut output); - for (path, data) in [ - ("word/document.xml", document_xml.as_bytes()), - ("word/_rels/document.xml.rels", relationships_xml.as_bytes()), - ("word/media/image1.png", png.get_ref()), - ] { - archive - .start_file(path, SimpleFileOptions::default()) - .unwrap(); - archive.write_all(data).unwrap(); - } - archive.finish().unwrap(); - } - output.into_inner() - } - - #[test] - fn wraps_unspaced_text_without_truncating() { - let text = "abcdefghijklmnopqrstuvwxyz"; - let lines = wrap_styled_text_with_font(text, 40.0, 12.0, false, false, None); - - assert!(lines.len() > 1); - assert_eq!(lines.concat(), text); - assert!(lines.iter().all(|line| { - crate::pdf::styled_text_width_with_font(line, 12.0, false, false, None) <= 40.0 - })); - } - - #[test] - fn keeps_cjk_opening_punctuation_off_line_end() { - let text = "机房(扶梯上机舱 )"; - let max_width = - crate::pdf::styled_text_width_with_font("机房(", 8.0, true, false, Some("宋体")); - - let lines = wrap_styled_text_with_font(text, max_width, 8.0, true, false, Some("宋体")); - - assert_eq!(lines, vec!["机房", "(扶梯", "上机", "舱)"]); - assert!(lines.iter().all(|line| !line.ends_with('('))); - } - - #[test] - fn preserves_explicit_page_breaks() { - let input = create_docx( - r#"FirstSecondThird"#, - ); - - let document = read_docx_document(&input).unwrap(); - - assert_eq!( - document.blocks, - vec![ - DocxBlock::Paragraph(plain_paragraph("First".to_owned())), - DocxBlock::PageBreak, - DocxBlock::Paragraph(plain_paragraph("Second".to_owned())), - DocxBlock::PageBreak, - DocxBlock::Paragraph(plain_paragraph("Third".to_owned())), - ] - ); - let pdf = convert_docx_bytes(&input, &ConversionOptions::default()).unwrap(); - assert_eq!( - pdf.windows(b"/Type /Page /Parent".len()) - .filter(|chunk| *chunk == b"/Type /Page /Parent") - .count(), - 3 - ); - } - - #[test] - fn ignores_disabled_page_break_before() { - let input = create_docx( - r#"FirstSecondThirdFourth"#, - ); - - let document = read_docx_document(&input).unwrap(); - - assert_eq!( - document.blocks, - vec![ - DocxBlock::Paragraph(plain_paragraph("First".to_owned())), - DocxBlock::Paragraph(plain_paragraph("Second".to_owned())), - DocxBlock::Paragraph(plain_paragraph("Third".to_owned())), - DocxBlock::PageBreak, - DocxBlock::Paragraph(plain_paragraph("Fourth".to_owned())), - ] - ); - let pdf = convert_docx_bytes(&input, &ConversionOptions::default()).unwrap(); - assert_eq!( - pdf.windows(b"/Type /Page /Parent".len()) - .filter(|chunk| *chunk == b"/Type /Page /Parent") - .count(), - 2 - ); - } - - #[test] - fn ignores_page_break_before_in_change_history() { - let input = create_docx( - r#"FirstSecond"#, - ); - - let document = read_docx_document(&input).unwrap(); - - assert_eq!( - document.blocks, - vec![ - DocxBlock::Paragraph(plain_paragraph("First".to_owned())), - DocxBlock::Paragraph(plain_paragraph("Second".to_owned())), - ] - ); - } - - #[test] - fn reads_and_renders_basic_table() { - let input = create_docx( - r#"HeaderValue"#, - ); - - let document = read_docx_document(&input).unwrap(); - - assert_eq!(document.page_size, crate::PageSize::LETTER); - assert_eq!(document.margins.left, 90.0); - let DocxBlock::Table(table) = &document.blocks[0] else { - panic!("expected table block"); - }; - assert_eq!(table.column_widths, vec![100.0, 150.0]); - assert_eq!(table.alignment, super::TextAlignment::Left); - assert_eq!(table.rows[0].cells.len(), 2); - assert_eq!(table.rows[0].cells[0].runs[0].font_size, 8.0); - assert!(table.rows[0].cells[0].runs[0].bold); - assert_eq!(table.rows[0].cells[0].runs[0].text, "Header"); - assert!(table.rows[0].cells[0].fill.is_some()); - - let pdf = convert_docx_bytes(&input, &ConversionOptions::default()).unwrap(); - assert_eq!( - pdf.windows(b"/Type /Page /Parent".len()) - .filter(|chunk| *chunk == b"/Type /Page /Parent") - .count(), - 1 - ); - } - - #[test] - fn reads_table_spans_merges_and_declared_height() { - let input = create_docx( - r#"ABC"#, - ); - - let document = read_docx_document(&input).unwrap(); - let DocxBlock::Table(table) = &document.blocks[0] else { - panic!("expected table block"); - }; - - assert_eq!(table.alignment, super::TextAlignment::Center); - assert_eq!(table.rows[0].height, Some(12.0)); - assert_eq!(table.rows[0].cells[1].grid_span, 2); - assert_eq!( - table.rows[0].cells[0].vertical_merge, - super::VerticalMerge::Restart - ); - assert_eq!( - table.rows[1].cells[0].vertical_merge, - super::VerticalMerge::Continue - ); - assert_eq!( - table.rows[0].cells[0].vertical_alignment, - super::VerticalAlignment::Center - ); - } - - #[test] - fn reads_table_font_highlight_margins_and_borders() { - let input = create_docx( - r#"□高亮"#, - ); - - let document = read_docx_document(&input).unwrap(); - let DocxBlock::Table(table) = &document.blocks[0] else { - panic!("expected table block"); - }; - let cell = &table.rows[0].cells[0]; - - assert_eq!(table.cell_margin_left, 0.0); - assert_eq!(table.cell_margin_right, 0.0); - assert_eq!(cell.spacing_before, 9.0); - assert_eq!(cell.spacing_after, 6.0); - assert_eq!(cell.line_spacing, 1.15); - assert_eq!(cell.runs.len(), 2); - assert_eq!(cell.runs[0].font_name, None); - assert_eq!(cell.runs[1].font_name.as_deref(), Some("宋体")); - assert_eq!(cell.runs[1].font_size, 9.0); - assert_eq!( - cell.runs[1].highlight, - Some(crate::PdfColor::new(1.0, 1.0, 0.0)) - ); - assert_eq!( - cell.borders.top.map(|border| border.pattern), - Some(super::BorderPattern::DotDash) - ); - assert_eq!(cell.borders.right, None); - } - - #[test] - fn reads_word_2007_compatibility_mode() { - let input = create_docx_with_settings( - r#"Legacy"#, - r#""#, - ); - - let document = read_docx_document(&input).unwrap(); - - assert_eq!(document.compatibility_mode, 12); - } - - #[test] - fn reads_and_renders_inline_png() { - let input = create_docx_with_image( - r#""#, - r#""#, - ); - - let document = read_docx_document(&input).unwrap(); - - let DocxBlock::Image(image) = &document.blocks[0] else { - panic!("expected image block"); - }; - assert_eq!((image.width, image.height), (72.0, 36.0)); - let DocxImageData::Rgba { - data, - width, - height, - } = &image.data - else { - panic!("expected RGBA image"); - }; - assert_eq!((*width, *height, data.len()), (2, 1, 8)); - - let pdf = convert_docx_bytes(&input, &ConversionOptions::default()).unwrap(); - assert!(pdf - .windows(b"/Subtype /Image".len()) - .any(|chunk| chunk == b"/Subtype /Image")); - } - - #[test] - fn anchors_vml_textbox_image_once() { - let input = create_docx_with_image( - r#"Title"#, - r#""#, - ); - - let document = read_docx_document(&input).unwrap(); - - assert_eq!(document.blocks.len(), 1); - let DocxBlock::Paragraph(paragraph) = &document.blocks[0] else { - panic!("expected paragraph block"); - }; - assert_eq!(paragraph.runs.len(), 1); - assert_eq!(paragraph.runs[0].text, "Title"); - assert_eq!(paragraph.floating_images.len(), 1); - assert_eq!(paragraph.floating_images[0].offset_x, 393.95); - assert_eq!(paragraph.floating_images[0].offset_y, -1.9); - assert_eq!(paragraph.floating_images[0].line_top_leading, 2.0); - } -} diff --git a/minipdf-rs/crates/minipdf/src/fonts.rs b/minipdf-rs/crates/minipdf/src/fonts.rs deleted file mode 100644 index c5043516..00000000 --- a/minipdf-rs/crates/minipdf/src/fonts.rs +++ /dev/null @@ -1,260 +0,0 @@ -use std::fs; -use std::path::PathBuf; -use std::sync::{Mutex, OnceLock}; - -use crate::Result; - -static SYSTEM_FONTS_REGISTERED: OnceLock> = OnceLock::new(); - -pub fn register_system_fonts() -> Result<()> { - let state = SYSTEM_FONTS_REGISTERED.get_or_init(|| Mutex::new(false)); - let mut registered = state - .lock() - .expect("system font registration lock poisoned"); - if *registered { - return Ok(()); - } - - for path in system_fallback_font_paths() - .into_iter() - .filter(|path| path.is_file()) - { - let name = path - .file_stem() - .and_then(|name| name.to_str()) - .unwrap_or("font") - .to_owned(); - crate::register_font(name, fs::read(path)?); - } - register_office_cloud_fonts()?; - *registered = true; - Ok(()) -} - -#[cfg(target_os = "windows")] -fn register_office_cloud_fonts() -> Result<()> { - let Some(local_app_data) = std::env::var_os("LOCALAPPDATA") else { - return Ok(()); - }; - let cache_root = PathBuf::from(local_app_data) - .join("Microsoft") - .join("FontCache"); - let Ok(cache_versions) = fs::read_dir(cache_root) else { - return Ok(()); - }; - for cloud_root in cache_versions - .filter_map(std::result::Result::ok) - .map(|entry| entry.path().join("CloudFonts")) - .filter(|path| path.is_dir()) - { - for family in ["Grandview", "Grandview Display", "STKaiti"] { - let directory = cloud_root.join(family); - let Ok(entries) = fs::read_dir(directory) else { - continue; - }; - for entry in entries.filter_map(std::result::Result::ok) { - let path = entry.path(); - if path.extension().and_then(|ext| ext.to_str()) != Some("ttf") { - continue; - } - let Ok(data) = fs::read(path) else { - continue; - }; - if let Some(name) = font_alias_from_data(&data) { - crate::register_font(name, data); - } - } - } - } - Ok(()) -} - -#[cfg(not(target_os = "windows"))] -fn register_office_cloud_fonts() -> Result<()> { - Ok(()) -} - -#[cfg(target_os = "windows")] -fn font_alias_from_data(data: &[u8]) -> Option { - let face = ttf_parser::Face::parse(data, 0).ok()?; - let name = |id| { - face.names() - .into_iter() - .find(|name| name.name_id == id && name.is_unicode()) - .and_then(|name| name.to_string()) - }; - let family = name(ttf_parser::name_id::TYPOGRAPHIC_FAMILY) - .or_else(|| name(ttf_parser::name_id::FAMILY))?; - let subfamily = name(ttf_parser::name_id::TYPOGRAPHIC_SUBFAMILY) - .or_else(|| name(ttf_parser::name_id::SUBFAMILY)) - .unwrap_or_default(); - Some(build_font_alias( - &family, - &subfamily, - face.is_bold(), - face.is_italic(), - )) -} - -#[cfg(target_os = "windows")] -fn build_font_alias(family: &str, subfamily: &str, bold: bool, italic: bool) -> String { - let mut alias = normalize_font_alias(family); - if subfamily.to_ascii_lowercase().contains("display") && !alias.contains("display") { - alias.push_str("display"); - } - if bold && italic { - alias.push('z'); - } else if bold { - alias.push('b'); - } else if italic { - alias.push('i'); - } - alias -} - -#[cfg(target_os = "windows")] -fn normalize_font_alias(name: &str) -> String { - name.chars() - .filter(|character| character.is_ascii_alphanumeric()) - .flat_map(char::to_lowercase) - .collect() -} - -fn system_fallback_font_paths() -> Vec { - #[cfg(target_os = "windows")] - { - let directory = std::env::var_os("WINDIR") - .map(PathBuf::from) - .unwrap_or_else(|| PathBuf::from(r"C:\Windows")) - .join("Fonts"); - return [ - "arial.ttf", - "arialbd.ttf", - "ariali.ttf", - "arialbi.ttf", - "calibri.ttf", - "calibrib.ttf", - "calibrii.ttf", - "calibriz.ttf", - "pala.ttf", - "palab.ttf", - "palai.ttf", - "palabi.ttf", - "corbel.ttf", - "corbelb.ttf", - "corbeli.ttf", - "corbelz.ttf", - "GARA.TTF", - "GARABD.TTF", - "GARAIT.TTF", - "TCM_____.TTF", - "TCB_____.TTF", - "TCMI____.TTF", - "TCBI____.TTF", - "verdana.ttf", - "verdanab.ttf", - "verdanai.ttf", - "verdanaz.ttf", - "NotoSans-Regular.ttf", - "NotoSansArmenian-Regular.ttf", - "NotoSansArmenian-Bold.ttf", - "NotoSansGeorgian-Regular.ttf", - "NotoSansGeorgian-Bold.ttf", - "ebrima.ttf", - "ebrimabd.ttf", - "YuGothR.ttc", - "NotoSansSC-VF.ttf", - "simkai.ttf", - "simsun.ttc", - "simhei.ttf", - "malgunsl.ttf", - "malgun.ttf", - "micross.ttf", - "LeelawUI.ttf", - "Nirmala.ttf", - "seguisym.ttf", - "seguiemj.ttf", - ] - .into_iter() - .map(|name| directory.join(name)) - .collect(); - } - - #[cfg(target_os = "linux")] - { - return [ - "/usr/share/fonts/truetype/noto/NotoSans-Regular.ttf", - "/usr/share/fonts/opentype/noto/NotoSansCJK-Regular.ttc", - "/usr/share/fonts/truetype/noto/NotoSansThai-Regular.ttf", - "/usr/share/fonts/truetype/noto/NotoSansDevanagari-Regular.ttf", - "/usr/share/fonts/truetype/noto/NotoColorEmoji.ttf", - "/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf", - ] - .into_iter() - .map(PathBuf::from) - .collect(); - } - - #[cfg(target_os = "macos")] - { - return [ - "/System/Library/Fonts/Supplemental/Arial Unicode.ttf", - "/System/Library/Fonts/AppleSDGothicNeo.ttc", - "/System/Library/Fonts/ヒラギノ角ゴシック W3.ttc", - "/System/Library/Fonts/Kohinoor.ttc", - "/System/Library/Fonts/Apple Color Emoji.ttc", - ] - .into_iter() - .map(PathBuf::from) - .collect(); - } - - #[allow(unreachable_code)] - Vec::new() -} - -#[cfg(test)] -mod tests { - #[cfg(target_os = "windows")] - use super::build_font_alias; - - #[cfg(target_os = "windows")] - use super::system_fallback_font_paths; - - #[cfg(target_os = "windows")] - #[test] - fn builds_stable_cloud_font_aliases() { - assert_eq!( - build_font_alias("Grandview", "Regular", false, false), - "grandview" - ); - assert_eq!( - build_font_alias("Grandview", "Bold", true, false), - "grandviewb" - ); - assert_eq!( - build_font_alias("Grandview", "Display", false, false), - "grandviewdisplay" - ); - } - - #[cfg(target_os = "windows")] - #[test] - fn registers_windows_latin_and_cjk_fallbacks() { - let names = system_fallback_font_paths() - .into_iter() - .filter_map(|path| path.file_name().map(|name| name.to_owned())) - .collect::>(); - - for name in [ - "arial.ttf", - "arialbd.ttf", - "ariali.ttf", - "arialbi.ttf", - "simkai.ttf", - "simsun.ttc", - ] { - assert!(names.iter().any(|candidate| candidate == name)); - } - } -} diff --git a/minipdf-rs/crates/minipdf/src/lib.rs b/minipdf-rs/crates/minipdf/src/lib.rs deleted file mode 100644 index bf440161..00000000 --- a/minipdf-rs/crates/minipdf/src/lib.rs +++ /dev/null @@ -1,232 +0,0 @@ -mod docx; -mod fonts; -mod office; -mod pdf; -mod pptx; -mod xlsx; - -use std::fs; -use std::io::{Cursor, Read, Seek}; -use std::path::Path; -use std::sync::{Mutex, OnceLock}; - -pub use fonts::register_system_fonts; -pub use office::OfficeFormat; -pub use pdf::{PdfColor, PdfDocument}; -use zip::ZipArchive; - -#[derive(Debug, thiserror::Error)] -pub enum MiniPdfError { - #[error("I/O error: {0}")] - Io(#[from] std::io::Error), - #[error("ZIP package error: {0}")] - Zip(#[from] zip::result::ZipError), - #[error("XML parse error: {0}")] - Xml(#[from] roxmltree::Error), - #[error("unsupported or unknown Office document format")] - UnsupportedFormat, - #[error("invalid input: {0}")] - InvalidInput(String), -} - -pub type Result = std::result::Result; - -#[derive(Debug, Clone, Copy, PartialEq)] -pub struct PageSize { - pub width: f32, - pub height: f32, -} - -impl PageSize { - pub const A4: Self = Self { - width: 595.28, - height: 841.89, - }; - pub const LETTER: Self = Self { - width: 612.0, - height: 792.0, - }; - - pub fn new(width: f32, height: f32) -> Result { - if !width.is_finite() || !height.is_finite() || width <= 0.0 || height <= 0.0 { - return Err(MiniPdfError::InvalidInput( - "page width and height must be positive finite values".to_owned(), - )); - } - Ok(Self { width, height }) - } -} - -#[derive(Debug, Clone, Copy, Default)] -pub struct ConversionOptions { - pub page_size: Option, -} - -#[derive(Debug, Clone)] -pub struct RegisteredFont { - pub name: String, - pub data: Vec, -} - -static REGISTERED_FONTS: OnceLock>> = OnceLock::new(); - -pub fn register_font(name: impl Into, font_data: impl Into>) { - let fonts = REGISTERED_FONTS.get_or_init(|| Mutex::new(Vec::new())); - let mut fonts = fonts.lock().expect("font registry lock poisoned"); - fonts.push(RegisteredFont { - name: name.into(), - data: font_data.into(), - }); - pdf::clear_font_support_cache(); -} - -pub fn registered_fonts() -> Vec { - let Some(fonts) = REGISTERED_FONTS.get() else { - return Vec::new(); - }; - fonts.lock().expect("font registry lock poisoned").clone() -} - -pub(crate) fn with_registered_fonts(callback: impl FnOnce(&[RegisteredFont]) -> T) -> T { - let Some(fonts) = REGISTERED_FONTS.get() else { - return callback(&[]); - }; - let fonts = fonts.lock().expect("font registry lock poisoned"); - callback(&fonts) -} - -pub fn convert_to_pdf(input_path: impl AsRef, output_path: impl AsRef) -> Result<()> { - convert_to_pdf_with_options(input_path, output_path, &ConversionOptions::default()) -} - -pub fn convert_to_pdf_with_options( - input_path: impl AsRef, - output_path: impl AsRef, - options: &ConversionOptions, -) -> Result<()> { - let pdf = convert_to_pdf_bytes_with_options(input_path, options)?; - fs::write(output_path, pdf)?; - Ok(()) -} - -pub fn convert_to_pdf_bytes(input_path: impl AsRef) -> Result> { - convert_to_pdf_bytes_with_options(input_path, &ConversionOptions::default()) -} - -pub fn convert_to_pdf_bytes_with_options( - input_path: impl AsRef, - options: &ConversionOptions, -) -> Result> { - let input_path = input_path.as_ref(); - let bytes = fs::read(input_path)?; - match input_path - .extension() - .and_then(|ext| ext.to_str()) - .map(|ext| ext.to_ascii_lowercase()) - { - Some(ext) if ext == "docx" => docx::convert_docx_bytes(&bytes, options), - Some(ext) if ext == "xlsx" => xlsx::convert_xlsx_bytes(&bytes, options), - Some(ext) if ext == "pptx" => pptx::convert_pptx_bytes(&bytes, options), - _ => convert_bytes_to_pdf_with_options(&bytes, options), - } -} - -pub fn convert_bytes_to_pdf(input: &[u8]) -> Result> { - convert_bytes_to_pdf_with_options(input, &ConversionOptions::default()) -} - -pub fn convert_bytes_to_pdf_with_options( - input: &[u8], - options: &ConversionOptions, -) -> Result> { - match detect_office_format(input)? { - OfficeFormat::Docx => docx::convert_docx_bytes(input, options), - OfficeFormat::Xlsx => xlsx::convert_xlsx_bytes(input, options), - OfficeFormat::Pptx => pptx::convert_pptx_bytes(input, options), - OfficeFormat::Unknown => Err(MiniPdfError::UnsupportedFormat), - } -} - -pub fn detect_office_format(input: &[u8]) -> Result { - let cursor = Cursor::new(input); - office::detect_office_format(cursor) -} - -fn read_zip_text( - archive: &mut ZipArchive, - path: &str, -) -> Result> { - let Ok(mut file) = archive.by_name(path) else { - return Ok(None); - }; - let mut text = String::new(); - file.read_to_string(&mut text)?; - Ok(Some(text)) -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn writes_basic_pdf_document() { - let mut doc = PdfDocument::new(); - let page = doc.add_page(595.28, 841.89); - page.add_text( - "Hello from Rust MiniPdf", - 72.0, - 760.0, - 14.0, - PdfColor::BLACK, - false, - ); - - let pdf = doc.to_bytes(); - assert!(pdf.starts_with(b"%PDF-1.4")); - assert!(pdf.ends_with(b"%%EOF\n")); - } - - #[test] - fn declares_pdf_stream_lengths_exactly() { - let mut doc = PdfDocument::new(); - let page = doc.add_page(595.28, 841.89); - page.add_text("Hello", 72.0, 760.0, 14.0, PdfColor::BLACK, false); - - let pdf = doc.to_bytes(); - let mut offset = 0; - let mut checked_streams = 0; - - while let Some(relative_length_pos) = find_bytes(&pdf[offset..], b"/Length ") { - let length_start = offset + relative_length_pos + b"/Length ".len(); - let length_end = length_start - + pdf[length_start..] - .iter() - .position(|byte| !byte.is_ascii_digit()) - .expect("stream length is terminated"); - let declared_length = std::str::from_utf8(&pdf[length_start..length_end]) - .expect("stream length is ASCII") - .parse::() - .expect("stream length is numeric"); - - let stream_marker_pos = length_end - + find_bytes(&pdf[length_end..], b"stream\n") - .expect("stream marker follows length"); - let stream_start = stream_marker_pos + b"stream\n".len(); - let stream_end = stream_start - + find_bytes(&pdf[stream_start..], b"\nendstream") - .expect("endstream marker follows stream data"); - - assert_eq!(declared_length, stream_end - stream_start); - checked_streams += 1; - offset = stream_end + b"\nendstream".len(); - } - - assert!(checked_streams > 0); - } - - fn find_bytes(haystack: &[u8], needle: &[u8]) -> Option { - haystack - .windows(needle.len()) - .position(|window| window == needle) - } -} diff --git a/minipdf-rs/crates/minipdf/src/office.rs b/minipdf-rs/crates/minipdf/src/office.rs deleted file mode 100644 index 676cf77d..00000000 --- a/minipdf-rs/crates/minipdf/src/office.rs +++ /dev/null @@ -1,31 +0,0 @@ -use std::io::{Read, Seek}; - -use zip::ZipArchive; - -use crate::Result; - -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum OfficeFormat { - Unknown, - Xlsx, - Docx, - Pptx, -} - -pub(crate) fn detect_office_format(reader: R) -> Result { - let mut archive = ZipArchive::new(reader)?; - for index in 0..archive.len() { - let file = archive.by_index(index)?; - let name = file.name().replace('\\', "/"); - if name.starts_with("word/") { - return Ok(OfficeFormat::Docx); - } - if name.starts_with("xl/") { - return Ok(OfficeFormat::Xlsx); - } - if name.starts_with("ppt/") { - return Ok(OfficeFormat::Pptx); - } - } - Ok(OfficeFormat::Unknown) -} diff --git a/minipdf-rs/crates/minipdf/src/pdf.rs b/minipdf-rs/crates/minipdf/src/pdf.rs deleted file mode 100644 index 27a7ab4c..00000000 --- a/minipdf-rs/crates/minipdf/src/pdf.rs +++ /dev/null @@ -1,1558 +0,0 @@ -use std::collections::{BTreeMap, HashMap}; -use std::io::Write; -use std::sync::{Mutex, OnceLock}; - -use flate2::{write::ZlibEncoder, Compression}; - -use crate::RegisteredFont; - -#[derive(Debug, Default)] -struct FontSupportCache { - support_by_character: HashMap>>, - selections: HashMap>, -} - -#[derive(Debug, Clone, PartialEq, Eq, Hash)] -struct FontSelectionKey { - font_count: usize, - ch: char, - bold: bool, - italic: bool, - preferred_font: Option, -} - -impl FontSelectionKey { - fn new( - font_count: usize, - ch: char, - bold: bool, - italic: bool, - preferred_font: Option<&str>, - ) -> Self { - Self { - font_count, - ch, - bold, - italic, - preferred_font: preferred_font.map(|name| name.trim().to_ascii_lowercase()), - } - } -} - -impl FontSupportCache { - fn get_or_probe(&mut self, font_index: usize, ch: char, probe: impl FnOnce() -> bool) -> bool { - let support = self.support_by_character.entry(ch).or_default(); - if support.len() <= font_index { - support.resize(font_index + 1, None); - } - if let Some(supported) = support[font_index] { - return supported; - } - let supported = probe(); - support[font_index] = Some(supported); - supported - } - - fn select_font( - &mut self, - fonts: &[RegisteredFont], - ch: char, - bold: bool, - italic: bool, - preferred_font: Option<&str>, - ) -> Option { - let key = FontSelectionKey::new(fonts.len(), ch, bold, italic, preferred_font); - if let Some(selection) = self.selections.get(&key) { - return *selection; - } - let mut selected = None; - for (index, font) in fonts.iter().enumerate() { - if !self.get_or_probe(index, ch, || probe_font_support(font, ch)) { - continue; - } - let preference = font_preference(&font.name, ch, bold, italic, preferred_font); - if selected.is_none_or(|(best, _)| preference < best) { - selected = Some((preference, index)); - } - } - let selection = selected.map(|(_, index)| index); - self.selections.insert(key, selection); - selection - } - - fn clear(&mut self) { - *self = Self::default(); - } -} - -static FONT_SUPPORT_CACHE: OnceLock> = OnceLock::new(); - -pub(crate) fn clear_font_support_cache() { - if let Some(cache) = FONT_SUPPORT_CACHE.get() { - let mut cache = cache.lock().expect("font support cache lock poisoned"); - cache.clear(); - } -} - -#[derive(Debug, Clone, Copy, PartialEq)] -pub struct PdfColor { - pub r: f32, - pub g: f32, - pub b: f32, -} - -impl PdfColor { - pub const BLACK: Self = Self::new(0.0, 0.0, 0.0); - pub const WHITE: Self = Self::new(1.0, 1.0, 1.0); - pub const LIGHT_GRAY: Self = Self::new(0.92, 0.92, 0.92); - pub const TABLE_HEADER: Self = Self::new(0.86, 0.91, 0.96); - - pub const fn new(r: f32, g: f32, b: f32) -> Self { - Self { r, g, b } - } -} - -#[derive(Debug, Clone, Copy)] -pub struct PdfTextStyle { - pub color: PdfColor, - pub bold: bool, - pub italic: bool, - pub preferred_font: Option<&'static str>, -} - -#[derive(Debug, Clone)] -pub(crate) enum PdfPathCommand { - MoveTo(f32, f32), - LineTo(f32, f32), - CurveTo(f32, f32, f32, f32, f32, f32), - Close, -} - -#[derive(Debug, Clone)] -enum PdfOp { - Text { - text: String, - x: f32, - y: f32, - font_size: f32, - color: PdfColor, - bold: bool, - italic: bool, - preferred_font: Option, - }, - Rect { - x: f32, - y: f32, - width: f32, - height: f32, - color: PdfColor, - }, - Ellipse { - x: f32, - y: f32, - width: f32, - height: f32, - color: PdfColor, - }, - Path { - commands: Vec, - color: PdfColor, - }, - Line { - x1: f32, - y1: f32, - x2: f32, - y2: f32, - color: PdfColor, - width: f32, - dash_pattern: Vec, - }, - Image { - image_id: usize, - x: f32, - y: f32, - width: f32, - height: f32, - }, - PushClip { - x: f32, - y: f32, - width: f32, - height: f32, - }, - PopClip, -} - -#[derive(Debug, Clone)] -enum PdfImageData { - Jpeg(Vec), - Rgba { rgb: Vec, alpha: Vec }, -} - -#[derive(Debug, Clone)] -struct PdfImage { - data: PdfImageData, - width: u16, - height: u16, -} - -#[derive(Debug, Clone)] -pub struct PdfPage { - pub width: f32, - pub height: f32, - ops: Vec, -} - -impl PdfPage { - fn new(width: f32, height: f32) -> Self { - Self { - width, - height, - ops: Vec::new(), - } - } - - pub fn add_text( - &mut self, - text: impl Into, - x: f32, - y: f32, - font_size: f32, - color: PdfColor, - bold: bool, - ) { - self.add_styled_text( - text, - x, - y, - font_size, - PdfTextStyle { - color, - bold, - italic: false, - preferred_font: None, - }, - ); - } - - pub fn add_styled_text( - &mut self, - text: impl Into, - x: f32, - y: f32, - font_size: f32, - style: PdfTextStyle, - ) { - self.add_styled_text_with_font( - text, - x, - y, - font_size, - style.color, - style.bold, - style.italic, - style.preferred_font, - ); - } - - #[allow(clippy::too_many_arguments)] - pub(crate) fn add_styled_text_with_font( - &mut self, - text: impl Into, - x: f32, - y: f32, - font_size: f32, - color: PdfColor, - bold: bool, - italic: bool, - preferred_font: Option<&str>, - ) { - self.ops.push(PdfOp::Text { - text: text.into(), - x, - y, - font_size, - color, - bold, - italic, - preferred_font: preferred_font.map(str::to_owned), - }); - } - - pub fn add_rect(&mut self, x: f32, y: f32, width: f32, height: f32, color: PdfColor) { - self.ops.push(PdfOp::Rect { - x, - y, - width, - height, - color, - }); - } - - pub(crate) fn add_ellipse(&mut self, x: f32, y: f32, width: f32, height: f32, color: PdfColor) { - self.ops.push(PdfOp::Ellipse { - x, - y, - width, - height, - color, - }); - } - - pub(crate) fn add_path(&mut self, commands: Vec, color: PdfColor) { - if !commands.is_empty() { - self.ops.push(PdfOp::Path { commands, color }); - } - } - - pub fn add_line(&mut self, x1: f32, y1: f32, x2: f32, y2: f32, color: PdfColor, width: f32) { - self.ops.push(PdfOp::Line { - x1, - y1, - x2, - y2, - color, - width, - dash_pattern: Vec::new(), - }); - } - - pub fn add_dashed_line( - &mut self, - x1: f32, - y1: f32, - x2: f32, - y2: f32, - color: PdfColor, - width: f32, - ) { - self.ops.push(PdfOp::Line { - x1, - y1, - x2, - y2, - color, - width, - dash_pattern: vec![0.8, 1.2], - }); - } - - pub(crate) fn add_line_with_dash_pattern( - &mut self, - start: (f32, f32), - end: (f32, f32), - color: PdfColor, - width: f32, - dash_pattern: &[f32], - ) { - self.ops.push(PdfOp::Line { - x1: start.0, - y1: start.1, - x2: end.0, - y2: end.1, - color, - width, - dash_pattern: dash_pattern.to_vec(), - }); - } - - pub fn add_image(&mut self, image_id: usize, x: f32, y: f32, width: f32, height: f32) { - self.ops.push(PdfOp::Image { - image_id, - x, - y, - width, - height, - }); - } - - pub fn push_clip(&mut self, x: f32, y: f32, width: f32, height: f32) { - self.ops.push(PdfOp::PushClip { - x, - y, - width, - height, - }); - } - - pub fn pop_clip(&mut self) { - self.ops.push(PdfOp::PopClip); - } - - pub(crate) fn translate_y(&mut self, offset: f32) { - for operation in &mut self.ops { - match operation { - PdfOp::Text { y, .. } - | PdfOp::Rect { y, .. } - | PdfOp::Ellipse { y, .. } - | PdfOp::Image { y, .. } - | PdfOp::PushClip { y, .. } => *y += offset, - PdfOp::Line { y1, y2, .. } => { - *y1 += offset; - *y2 += offset; - } - PdfOp::Path { commands, .. } => { - for command in commands { - match command { - PdfPathCommand::MoveTo(_, y) | PdfPathCommand::LineTo(_, y) => { - *y += offset; - } - PdfPathCommand::CurveTo(_, y1, _, y2, _, y3) => { - *y1 += offset; - *y2 += offset; - *y3 += offset; - } - PdfPathCommand::Close => {} - } - } - } - PdfOp::PopClip => {} - } - } - } -} - -#[derive(Debug, Clone)] -pub struct PdfDocument { - pages: Vec, - images: Vec, - fonts: Vec, -} - -#[derive(Debug)] -struct EmbeddedFont { - registered_index: usize, - resource_name: String, - object_id: usize, - glyphs: BTreeMap, - cid_by_glyph: BTreeMap, -} - -impl PdfDocument { - pub fn new() -> Self { - Self { - pages: Vec::new(), - images: Vec::new(), - fonts: crate::registered_fonts(), - } - } - - pub fn add_jpeg_image(&mut self, data: Vec, width: u16, height: u16) -> usize { - let image_id = self.images.len(); - self.images.push(PdfImage { - data: PdfImageData::Jpeg(data), - width, - height, - }); - image_id - } - - pub fn add_rgba_image(&mut self, data: Vec, width: u16, height: u16) -> usize { - let mut rgb = Vec::with_capacity(data.len() / 4 * 3); - let mut alpha = Vec::with_capacity(data.len() / 4); - for pixel in data.chunks_exact(4) { - rgb.extend_from_slice(&pixel[..3]); - alpha.push(pixel[3]); - } - let image_id = self.images.len(); - self.images.push(PdfImage { - data: PdfImageData::Rgba { rgb, alpha }, - width, - height, - }); - image_id - } - - pub fn add_page(&mut self, width: f32, height: f32) -> &mut PdfPage { - self.pages.push(PdfPage::new(width, height)); - self.pages.last_mut().expect("page was just pushed") - } - - pub fn pages(&self) -> &[PdfPage] { - &self.pages - } - - pub fn page_mut(&mut self, index: usize) -> Option<&mut PdfPage> { - self.pages.get_mut(index) - } - - pub fn to_bytes(&self) -> Vec { - let mut objects: Vec> = Vec::new(); - let page_count = self.pages.len(); - - objects.push(b"<< /Type /Catalog /Pages 2 0 R >>".to_vec()); - objects.push(Vec::new()); - objects.push(b"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>".to_vec()); - objects.push(b"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica-Bold >>".to_vec()); - objects.push(b"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica-Oblique >>".to_vec()); - objects - .push(b"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica-BoldOblique >>".to_vec()); - - let mut embedded_fonts = prepare_embedded_fonts(&self.pages, &self.fonts); - for font in &mut embedded_fonts { - font.object_id = append_embedded_font_objects(&mut objects, font, &self.fonts); - } - - let mut image_ids = Vec::with_capacity(self.images.len()); - for image in &self.images { - let (data, filter, soft_mask) = match &image.data { - PdfImageData::Jpeg(data) => (data.clone(), "/DCTDecode", None), - PdfImageData::Rgba { rgb, alpha } => { - let alpha = zlib_compress(alpha); - let mut mask_object = format!( - "<< /Type /XObject /Subtype /Image /Width {} /Height {} /ColorSpace /DeviceGray /BitsPerComponent 8 /Filter /FlateDecode /Length {} >>\nstream\n", - image.width, - image.height, - alpha.len() - ) - .into_bytes(); - mask_object.extend_from_slice(&alpha); - mask_object.extend_from_slice(b"\nendstream"); - let mask_id = push_object(&mut objects, mask_object); - (zlib_compress(rgb), "/FlateDecode", Some(mask_id)) - } - }; - let soft_mask = soft_mask.map_or_else(String::new, |id| format!(" /SMask {id} 0 R")); - let mut image_object = format!( - "<< /Type /XObject /Subtype /Image /Width {} /Height {} /ColorSpace /DeviceRGB /BitsPerComponent 8 /Filter {}{} /Length {} >>\nstream\n", - image.width, - image.height, - filter, - soft_mask, - data.len() - ) - .into_bytes(); - image_object.extend_from_slice(&data); - image_object.extend_from_slice(b"\nendstream"); - image_ids.push(push_object(&mut objects, image_object)); - } - - let mut page_ids = Vec::with_capacity(page_count); - for page in &self.pages { - let mut content = write_content_stream(page, &self.fonts, &embedded_fonts); - if content.ends_with(b"\n") { - content.pop(); - } - - let mut content_object = Vec::new(); - content_object - .extend_from_slice(format!("<< /Length {} >>\nstream\n", content.len()).as_bytes()); - content_object.extend_from_slice(&content); - content_object.extend_from_slice(b"\nendstream"); - let content_id = push_object(&mut objects, content_object); - - let xobjects = image_ids - .iter() - .enumerate() - .map(|(index, object_id)| format!("/Im{} {} 0 R", index + 1, object_id)) - .collect::>() - .join(" "); - let embedded_resources = embedded_fonts - .iter() - .map(|font| format!("/{} {} 0 R", font.resource_name, font.object_id)) - .collect::>() - .join(" "); - let page_object = format!( - "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 {:.2} {:.2}] /Resources << /Font << /F1 3 0 R /F2 4 0 R /F3 5 0 R /F4 6 0 R {} >> /XObject << {} >> >> /Contents {} 0 R >>", - page.width, page.height, embedded_resources, xobjects, content_id - ); - page_ids.push(push_object(&mut objects, page_object.into_bytes())); - } - - let kids = page_ids - .iter() - .map(|id| format!("{id} 0 R")) - .collect::>() - .join(" "); - objects[1] = format!("<< /Type /Pages /Kids [{kids}] /Count {page_count} >>").into_bytes(); - - write_objects(objects) - } -} - -impl Default for PdfDocument { - fn default() -> Self { - Self::new() - } -} - -fn push_object(objects: &mut Vec>, object: Vec) -> usize { - objects.push(object); - objects.len() -} - -fn zlib_compress(data: &[u8]) -> Vec { - let mut encoder = ZlibEncoder::new(Vec::new(), Compression::default()); - encoder - .write_all(data) - .expect("writing to memory cannot fail"); - encoder - .finish() - .expect("finishing memory stream cannot fail") -} - -fn prepare_embedded_fonts(pages: &[PdfPage], fonts: &[RegisteredFont]) -> Vec { - let mut used_glyphs: BTreeMap> = BTreeMap::new(); - for page in pages { - for op in &page.ops { - let PdfOp::Text { - text, - bold, - italic, - preferred_font, - .. - } = op - else { - continue; - }; - for run in split_font_runs(text, fonts, *bold, *italic, preferred_font.as_deref()) { - let Some(font_index) = run.font_index else { - continue; - }; - let Some(shaped) = shape_text(&run.text, &fonts[font_index].data) else { - continue; - }; - let glyphs = used_glyphs.entry(font_index).or_default(); - for (glyph_index, glyph) in shaped.glyphs.iter().enumerate() { - glyphs.entry(glyph.id).or_insert_with(|| { - text_for_cluster(&run.text, &shaped.glyphs, glyph_index) - }); - } - } - } - } - - used_glyphs - .into_iter() - .enumerate() - .map( - |(resource_index, (registered_index, glyphs))| EmbeddedFont { - registered_index, - resource_name: format!("FU{}", resource_index + 1), - object_id: 0, - cid_by_glyph: BTreeMap::new(), - glyphs, - }, - ) - .collect() -} - -fn append_embedded_font_objects( - objects: &mut Vec>, - font: &mut EmbeddedFont, - registered_fonts: &[RegisteredFont], -) -> usize { - let registered = ®istered_fonts[font.registered_index]; - let face = ttf_parser::Face::parse(®istered.data, 0) - .expect("font was validated while preparing PDF resources"); - let pdf_name = format!("MPFont{}", font.registered_index + 1); - let mut remapper = subsetter::GlyphRemapper::new(); - for glyph_id in font.glyphs.keys() { - remapper.remap(*glyph_id); - } - font.cid_by_glyph = font - .glyphs - .keys() - .map(|glyph_id| { - ( - *glyph_id, - remapper.get(*glyph_id).expect("glyph was remapped"), - ) - }) - .collect(); - let font_data = subsetter::subset(®istered.data, 0, &remapper) - .expect("font was validated while preparing PDF resources"); - - let mut font_file = format!( - "<< /Length {} /Length1 {} >>\nstream\n", - font_data.len(), - font_data.len() - ) - .into_bytes(); - font_file.extend_from_slice(&font_data); - font_file.extend_from_slice(b"\nendstream"); - let font_file_id = push_object(objects, font_file); - - let bbox = face.global_bounding_box(); - let descriptor = format!( - "<< /Type /FontDescriptor /FontName /{pdf_name} /Flags 32 /FontBBox [{} {} {} {}] /ItalicAngle 0 /Ascent {} /Descent {} /CapHeight {} /StemV 80 /FontFile2 {} 0 R >>", - bbox.x_min, - bbox.y_min, - bbox.x_max, - bbox.y_max, - face.ascender(), - face.descender(), - face.capital_height().unwrap_or_else(|| face.ascender()), - font_file_id - ); - let descriptor_id = push_object(objects, descriptor.into_bytes()); - - let units_per_em = u32::from(face.units_per_em()); - let widths = font - .glyphs - .keys() - .map(|glyph_id| { - let advance = u32::from( - face.glyph_hor_advance(ttf_parser::GlyphId(*glyph_id)) - .unwrap_or(face.units_per_em()), - ); - format!( - "{} [{}]", - remapper.get(*glyph_id).expect("glyph was remapped"), - advance * 1000 / units_per_em - ) - }) - .collect::>() - .join(" "); - let cid_font = format!( - "<< /Type /Font /Subtype /CIDFontType2 /BaseFont /{pdf_name} /CIDSystemInfo << /Registry (Adobe) /Ordering (Identity) /Supplement 0 >> /FontDescriptor {} 0 R /DW 1000 /W [{}] /CIDToGIDMap /Identity >>", - descriptor_id, widths - ); - let cid_font_id = push_object(objects, cid_font.into_bytes()); - - let to_unicode = build_to_unicode_cmap(&font.glyphs, &remapper); - let mut to_unicode_object = - format!("<< /Length {} >>\nstream\n", to_unicode.len()).into_bytes(); - to_unicode_object.extend_from_slice(to_unicode.as_bytes()); - to_unicode_object.extend_from_slice(b"\nendstream"); - let to_unicode_id = push_object(objects, to_unicode_object); - - let type0_font = format!( - "<< /Type /Font /Subtype /Type0 /BaseFont /{pdf_name} /Encoding /Identity-H /DescendantFonts [{} 0 R] /ToUnicode {} 0 R >>", - cid_font_id, to_unicode_id - ); - push_object(objects, type0_font.into_bytes()) -} - -fn build_to_unicode_cmap( - glyphs: &BTreeMap, - remapper: &subsetter::GlyphRemapper, -) -> String { - let mut cmap = String::from( - "/CIDInit /ProcSet findresource begin\n12 dict begin\nbegincmap\n/CIDSystemInfo << /Registry (Adobe) /Ordering (UCS) /Supplement 0 >> def\n/CMapName /Adobe-Identity-UCS def\n/CMapType 2 def\n1 begincodespacerange\n<0000> \nendcodespacerange\n", - ); - for chunk in glyphs.iter().collect::>().chunks(100) { - cmap.push_str(&format!("{} beginbfchar\n", chunk.len())); - for (glyph_id, text) in chunk { - let cid = remapper.get(**glyph_id).expect("glyph was remapped"); - cmap.push_str(&format!("<{cid:04X}> <{}>\n", utf16be_hex(text, false))); - } - cmap.push_str("endbfchar\n"); - } - cmap.push_str("endcmap\nCMapName currentdict /CMap defineresource pop\nend\nend"); - cmap -} - -#[derive(Debug)] -struct FontRun { - text: String, - font_index: Option, -} - -#[derive(Debug)] -struct ShapedGlyph { - id: u16, - cluster: usize, - x_advance: i32, - y_advance: i32, - x_offset: i32, - y_offset: i32, -} - -#[derive(Debug)] -struct ShapedText { - glyphs: Vec, - units_per_em: i32, -} - -fn split_font_runs( - text: &str, - fonts: &[RegisteredFont], - bold: bool, - italic: bool, - preferred_font: Option<&str>, -) -> Vec { - let mut runs: Vec = Vec::new(); - for ch in text.chars() { - let font_index = if ch.is_whitespace() || ch.is_ascii_punctuation() || ch == '\u{fe0f}' { - runs.last() - .and_then(|run| run.font_index) - .filter(|index| font_supports(*index, &fonts[*index], ch)) - .or_else(|| select_font(fonts, ch, bold, italic, preferred_font)) - } else { - select_font(fonts, ch, bold, italic, preferred_font) - }; - - if let Some(run) = runs.last_mut().filter(|run| run.font_index == font_index) { - run.text.push(ch); - } else { - runs.push(FontRun { - text: ch.to_string(), - font_index, - }); - } - } - runs -} - -fn select_font( - fonts: &[RegisteredFont], - ch: char, - bold: bool, - italic: bool, - preferred_font: Option<&str>, -) -> Option { - let cache = FONT_SUPPORT_CACHE.get_or_init(|| Mutex::new(FontSupportCache::default())); - cache - .lock() - .expect("font support cache lock poisoned") - .select_font(fonts, ch, bold, italic, preferred_font) -} - -fn font_preference( - name: &str, - ch: char, - bold: bool, - italic: bool, - preferred_font: Option<&str>, -) -> u8 { - let name = name.to_ascii_lowercase(); - if let Some(preferred) = preferred_font { - let preferred = match preferred.trim() { - "宋体" | "新宋体" => "simsun".to_owned(), - "黑体" => "simhei".to_owned(), - preferred => preferred.to_ascii_lowercase(), - }; - let preferred_variant = match (preferred.as_str(), bold, italic) { - ("arial", true, true) => "arialbi", - ("arial", true, false) => "arialbd", - ("arial", false, true) => "ariali", - ("corbel", true, true) => "corbelz", - ("corbel", true, false) => "corbelb", - ("corbel", false, true) => "corbeli", - ("gara", true, false) => "garabd", - ("gara", false, true) => "garait", - ("bookos", true, true) => "bookosbi", - ("bookos", true, false) => "bookosb", - ("bookos", false, true) => "bookosi", - ("verdana", true, true) => "verdanaz", - ("verdana", true, false) => "verdanab", - ("verdana", false, true) => "verdanai", - ("grandview", true, true) => "grandviewz", - ("grandview", true, false) => "grandviewb", - ("grandview", false, true) => "grandviewi", - ("tcm_____", true, true) => "tcbi____", - ("tcm_____", true, false) => "tcb_____", - ("tcm_____", false, true) => "tcmi____", - _ => preferred.as_str(), - }; - if name == preferred_variant { - return 0; - } - if name.starts_with(&preferred) { - return 1; - } - if preferred == "stkaiti" && name.starts_with("simkai") { - return 2; - } - } - let codepoint = ch as u32; - let preferred = if matches!(codepoint, 0x0530..=0x058f) { - "notosansarmenian" - } else if matches!(codepoint, 0x10a0..=0x10ff | 0x1c90..=0x1cbf) { - "notosansgeorgian" - } else if matches!(codepoint, 0x1200..=0x137f | 0x1380..=0x139f | 0x2d80..=0x2ddf) { - "ebrima" - } else if matches!(codepoint, 0x1100..=0x11ff | 0x3130..=0x318f | 0xac00..=0xd7af) { - "malgunsl" - } else if matches!(codepoint, 0x0e00..=0x0e7f) { - "micross" - } else if matches!(codepoint, 0x0900..=0x097f) { - "nirmala" - } else if matches!(codepoint, 0x2e80..=0x9fff | 0xf900..=0xfaff) - || matches!(codepoint, 0x2190..=0x2bff) - { - if bold { - "simhei" - } else { - "notosanssc" - } - } else if codepoint >= 0x1f000 { - "seguiemj" - } else if bold && italic { - "calibriz" - } else if bold { - "calibrib" - } else if italic { - "calibrii" - } else { - "calibri" - }; - - let fallback_score = if name == preferred { - 0 - } else if name.starts_with(preferred) { - 1 - } else if name == "calibri" { - 2 - } else { - 10 - }; - fallback_score + if preferred_font.is_some() { 2 } else { 0 } -} - -fn font_supports(font_index: usize, font: &RegisteredFont, ch: char) -> bool { - let cache = FONT_SUPPORT_CACHE.get_or_init(|| Mutex::new(FontSupportCache::default())); - cache - .lock() - .expect("font support cache lock poisoned") - .get_or_probe(font_index, ch, || probe_font_support(font, ch)) -} - -fn probe_font_support(font: &RegisteredFont, ch: char) -> bool { - if !is_embeddable_truetype(&font.data) { - return false; - } - let Ok(face) = ttf_parser::Face::parse(&font.data, 0) else { - return false; - }; - font_has_subsettable_outlines(face.raw_face()) && face.glyph_index(ch).is_some() -} - -fn is_embeddable_truetype(data: &[u8]) -> bool { - data.starts_with(b"\0\x01\0\0") || data.starts_with(b"true") || data.starts_with(b"ttcf") -} - -fn font_has_subsettable_outlines(face: &ttf_parser::RawFace<'_>) -> bool { - face.table(ttf_parser::Tag::from_bytes(b"glyf")).is_some() - || face.table(ttf_parser::Tag::from_bytes(b"CFF ")).is_some() -} - -fn shape_text(text: &str, font_data: &[u8]) -> Option { - let face = rustybuzz::Face::from_slice(font_data, 0)?; - let units_per_em = face.units_per_em(); - let mut buffer = rustybuzz::UnicodeBuffer::new(); - buffer.push_str(text); - buffer.guess_segment_properties(); - let output = rustybuzz::shape(&face, &[], buffer); - let glyphs = output - .glyph_infos() - .iter() - .zip(output.glyph_positions()) - .filter_map(|(info, position)| { - Some(ShapedGlyph { - id: u16::try_from(info.glyph_id).ok()?, - cluster: usize::try_from(info.cluster).ok()?, - x_advance: position.x_advance, - y_advance: position.y_advance, - x_offset: position.x_offset, - y_offset: position.y_offset, - }) - }) - .collect(); - Some(ShapedText { - glyphs, - units_per_em, - }) -} - -pub(crate) fn styled_text_width_with_font( - text: &str, - font_size: f32, - bold: bool, - italic: bool, - preferred_font: Option<&str>, -) -> f32 { - crate::with_registered_fonts(|fonts| { - split_font_runs(text, fonts, bold, italic, preferred_font) - .into_iter() - .map(|run| { - let Some(font_index) = run.font_index else { - return base14_text_width(&run.text, font_size, bold); - }; - let Some(shaped) = shape_text(&run.text, &fonts[font_index].data) else { - return base14_text_width(&run.text, font_size, bold); - }; - let scale = font_size / shaped.units_per_em as f32; - shaped - .glyphs - .iter() - .map(|glyph| glyph.x_advance as f32 * scale) - .sum::() - }) - .sum() - }) -} - -fn base14_text_width(text: &str, font_size: f32, bold: bool) -> f32 { - text.chars() - .map(|ch| helvetica_glyph_width(ch, bold)) - .sum::() as f32 - * font_size - / 1000.0 -} - -pub(crate) fn helvetica_glyph_width(ch: char, bold: bool) -> u32 { - const REGULAR: [u16; 95] = [ - 278, 278, 355, 556, 556, 889, 667, 191, 333, 333, 389, 584, 278, 333, 278, 278, 556, 556, - 556, 556, 556, 556, 556, 556, 556, 556, 278, 278, 584, 584, 584, 556, 1015, 667, 667, 722, - 722, 667, 611, 778, 722, 278, 500, 667, 556, 833, 722, 778, 667, 778, 722, 667, 611, 722, - 667, 944, 667, 667, 611, 278, 278, 278, 469, 556, 333, 556, 556, 500, 556, 556, 278, 556, - 556, 222, 222, 500, 222, 833, 556, 556, 556, 556, 333, 500, 278, 556, 500, 722, 500, 500, - 500, 334, 260, 334, 584, - ]; - const BOLD: [u16; 95] = [ - 278, 333, 474, 556, 556, 889, 722, 238, 333, 333, 389, 584, 278, 333, 278, 278, 556, 556, - 556, 556, 556, 556, 556, 556, 556, 556, 333, 333, 584, 584, 584, 611, 975, 722, 722, 722, - 722, 667, 611, 778, 722, 278, 556, 722, 611, 833, 722, 778, 667, 778, 722, 667, 611, 722, - 667, 944, 722, 667, 611, 333, 278, 333, 584, 556, 333, 556, 611, 556, 611, 556, 333, 611, - 611, 278, 278, 556, 278, 889, 611, 611, 611, 611, 389, 556, 333, 611, 556, 778, 556, 556, - 500, 389, 280, 389, 584, - ]; - let codepoint = ch as usize; - if (32..=126).contains(&codepoint) { - return if bold { - BOLD[codepoint - 32] - } else { - REGULAR[codepoint - 32] - } as u32; - } - if ch.is_ascii() { - 500 - } else { - 900 - } -} - -fn text_for_cluster(text: &str, glyphs: &[ShapedGlyph], index: usize) -> String { - let start = glyphs[index].cluster.min(text.len()); - let end = glyphs - .iter() - .map(|glyph| glyph.cluster) - .filter(|cluster| *cluster > start) - .min() - .unwrap_or(text.len()); - text.get(start..end).unwrap_or("\u{fffd}").to_owned() -} - -fn utf16be_hex(text: &str, include_bom: bool) -> String { - let mut result = String::new(); - if include_bom { - result.push_str("FEFF"); - } - for code_unit in text.encode_utf16() { - result.push_str(&format!("{code_unit:04X}")); - } - result -} - -fn write_objects(objects: Vec>) -> Vec { - let mut pdf = Vec::new(); - pdf.extend_from_slice(b"%PDF-1.4\n%\xE2\xE3\xCF\xD3\n"); - - let mut offsets = Vec::with_capacity(objects.len()); - for (index, object) in objects.iter().enumerate() { - offsets.push(pdf.len()); - pdf.extend_from_slice(format!("{} 0 obj\n", index + 1).as_bytes()); - pdf.extend_from_slice(object); - pdf.extend_from_slice(b"\nendobj\n"); - } - - let xref_start = pdf.len(); - pdf.extend_from_slice(format!("xref\n0 {}\n", objects.len() + 1).as_bytes()); - pdf.extend_from_slice(b"0000000000 65535 f \n"); - for offset in offsets { - pdf.extend_from_slice(format!("{offset:010} 00000 n \n").as_bytes()); - } - pdf.extend_from_slice( - format!( - "trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{}\n%%EOF\n", - objects.len() + 1, - xref_start - ) - .as_bytes(), - ); - pdf -} - -fn write_content_stream( - page: &PdfPage, - fonts: &[RegisteredFont], - embedded_fonts: &[EmbeddedFont], -) -> Vec { - let mut content = String::new(); - for op in &page.ops { - match op { - PdfOp::Text { - text, - x, - y, - font_size, - color, - bold, - italic, - preferred_font, - } => { - let built_in_font = match (*bold, *italic) { - (false, false) => "F1", - (true, false) => "F2", - (false, true) => "F3", - (true, true) => "F4", - }; - let mut cursor_x = *x; - let mut cursor_y = *y; - for run in split_font_runs(text, fonts, *bold, *italic, preferred_font.as_deref()) { - let Some(font_index) = run.font_index else { - content.push_str(&format!( - "BT /{built_in_font} {:.2} Tf {:.3} {:.3} {:.3} rg {:.2} {:.2} Td ({}) Tj ET\n", - font_size, - clamp_color(color.r), - clamp_color(color.g), - clamp_color(color.b), - cursor_x, - cursor_y, - escape_pdf_text(&run.text) - )); - cursor_x += run.text.chars().count() as f32 * font_size * 0.5; - continue; - }; - let Some(resource) = embedded_fonts - .iter() - .find(|font| font.registered_index == font_index) - else { - continue; - }; - let Some(shaped) = shape_text(&run.text, &fonts[font_index].data) else { - continue; - }; - let scale = font_size / shaped.units_per_em as f32; - content.push_str(&format!( - "/Span << /ActualText <{}> >> BDC\n", - utf16be_hex(&run.text, true) - )); - for glyph in shaped.glyphs { - let glyph_x = cursor_x + glyph.x_offset as f32 * scale; - let glyph_y = cursor_y + glyph.y_offset as f32 * scale; - content.push_str(&format!( - "BT /{} {:.2} Tf {:.3} {:.3} {:.3} rg 1 0 0 1 {:.2} {:.2} Tm <{:04X}> Tj ET\n", - resource.resource_name, - font_size, - clamp_color(color.r), - clamp_color(color.g), - clamp_color(color.b), - glyph_x, - glyph_y, - resource - .cid_by_glyph - .get(&glyph.id) - .expect("shaped glyph was registered") - )); - cursor_x += glyph.x_advance as f32 * scale; - cursor_y += glyph.y_advance as f32 * scale; - } - content.push_str("EMC\n"); - } - } - PdfOp::Rect { - x, - y, - width, - height, - color, - } => { - content.push_str(&format!( - "{:.3} {:.3} {:.3} rg {:.2} {:.2} {:.2} {:.2} re f\n", - clamp_color(color.r), - clamp_color(color.g), - clamp_color(color.b), - x, - y, - width, - height - )); - } - PdfOp::Ellipse { - x, - y, - width, - height, - color, - } => { - let radius_x = width / 2.0; - let radius_y = height / 2.0; - let center_x = x + radius_x; - let center_y = y + radius_y; - let control_x = radius_x * 0.552_284_8; - let control_y = radius_y * 0.552_284_8; - content.push_str(&format!( - "{:.3} {:.3} {:.3} rg {:.2} {:.2} m {:.2} {:.2} {:.2} {:.2} {:.2} {:.2} c {:.2} {:.2} {:.2} {:.2} {:.2} {:.2} c {:.2} {:.2} {:.2} {:.2} {:.2} {:.2} c {:.2} {:.2} {:.2} {:.2} {:.2} {:.2} c h f\n", - clamp_color(color.r), - clamp_color(color.g), - clamp_color(color.b), - center_x + radius_x, - center_y, - center_x + radius_x, - center_y + control_y, - center_x + control_x, - center_y + radius_y, - center_x, - center_y + radius_y, - center_x - control_x, - center_y + radius_y, - center_x - radius_x, - center_y + control_y, - center_x - radius_x, - center_y, - center_x - radius_x, - center_y - control_y, - center_x - control_x, - center_y - radius_y, - center_x, - center_y - radius_y, - center_x + control_x, - center_y - radius_y, - center_x + radius_x, - center_y - control_y, - center_x + radius_x, - center_y - )); - } - PdfOp::Path { commands, color } => { - content.push_str(&format!( - "{:.3} {:.3} {:.3} rg ", - clamp_color(color.r), - clamp_color(color.g), - clamp_color(color.b) - )); - for command in commands { - match command { - PdfPathCommand::MoveTo(x, y) => { - content.push_str(&format!("{x:.2} {y:.2} m ")); - } - PdfPathCommand::LineTo(x, y) => { - content.push_str(&format!("{x:.2} {y:.2} l ")); - } - PdfPathCommand::CurveTo(x1, y1, x2, y2, x3, y3) => { - content.push_str(&format!( - "{x1:.2} {y1:.2} {x2:.2} {y2:.2} {x3:.2} {y3:.2} c " - )); - } - PdfPathCommand::Close => content.push_str("h "), - } - } - content.push_str("f\n"); - } - PdfOp::Line { - x1, - y1, - x2, - y2, - color, - width, - dash_pattern, - } => { - let dash = dash_pattern - .iter() - .map(|value| format!("{value:.2}")) - .collect::>() - .join(" "); - content.push_str(&format!( - "[{dash}] 0 d {:.3} {:.3} {:.3} RG {:.2} w {:.2} {:.2} m {:.2} {:.2} l S\n", - clamp_color(color.r), - clamp_color(color.g), - clamp_color(color.b), - width, - x1, - y1, - x2, - y2 - )); - } - PdfOp::Image { - image_id, - x, - y, - width, - height, - } => { - content.push_str(&format!( - "q {:.2} 0 0 {:.2} {:.2} {:.2} cm /Im{} Do Q\n", - width, - height, - x, - y, - image_id + 1 - )); - } - PdfOp::PushClip { - x, - y, - width, - height, - } => { - content.push_str(&format!( - "q {:.2} {:.2} {:.2} {:.2} re W n\n", - x, y, width, height - )); - } - PdfOp::PopClip => content.push_str("Q\n"), - } - } - content.into_bytes() -} - -fn clamp_color(value: f32) -> f32 { - value.clamp(0.0, 1.0) -} - -fn escape_pdf_text(text: &str) -> String { - let mut result = String::new(); - for ch in text.chars() { - match ch { - '(' => result.push_str("\\("), - ')' => result.push_str("\\)"), - '\\' => result.push_str("\\\\"), - '\n' | '\r' | '\t' => result.push(' '), - ch if ch.is_control() => result.push(' '), - ch if ch.is_ascii() => result.push(ch), - _ => result.push('?'), - } - } - result -} - -#[cfg(test)] -mod tests { - use super::{ - font_has_subsettable_outlines, font_preference, FontSupportCache, PdfColor, PdfDocument, - PdfPathCommand, - }; - use crate::RegisteredFont; - - fn sfnt_with_table(tag: &[u8; 4]) -> Vec { - let mut data = vec![0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0]; - data.extend_from_slice(tag); - data.extend_from_slice(&[0; 4]); - data.extend_from_slice(&28_u32.to_be_bytes()); - data.extend_from_slice(&1_u32.to_be_bytes()); - data.push(0); - data - } - - #[test] - fn accepts_only_font_outlines_supported_by_subsetter() { - for tag in [b"glyf", b"CFF "] { - let data = sfnt_with_table(tag); - let face = ttf_parser::RawFace::parse(&data, 0).expect("sfnt directory is valid"); - assert!(font_has_subsettable_outlines(&face)); - } - - let data = sfnt_with_table(b"CBDT"); - let face = ttf_parser::RawFace::parse(&data, 0).expect("sfnt directory is valid"); - assert!(!font_has_subsettable_outlines(&face)); - } - - #[test] - fn caches_font_support_by_font_and_character() { - let mut cache = FontSupportCache::default(); - let mut probes = 0; - - for _ in 0..100 { - assert!(cache.get_or_probe(7, 'A', || { - probes += 1; - true - })); - } - - assert_eq!(probes, 1); - } - - #[test] - fn caches_font_selection_by_character_and_style() { - let mut cache = FontSupportCache::default(); - let fonts = (0..300) - .map(|index| RegisteredFont { - name: format!("font-{index}"), - data: Vec::new(), - }) - .collect::>(); - - for _ in 0..100 { - assert_eq!( - cache.select_font(&fonts, 'A', false, false, Some("Arial")), - None - ); - } - - assert_eq!(cache.support_by_character[&'A'].len(), 300); - assert_eq!(cache.selections.len(), 1); - - cache.clear(); - - assert!(cache.support_by_character.is_empty()); - assert!(cache.selections.is_empty()); - } - - #[test] - fn prefers_simhei_for_bold_cjk_text() { - assert_eq!(font_preference("simhei", '学', true, false, None), 0); - assert_eq!( - font_preference("NotoSansSC-VF", '学', false, false, None), - 1 - ); - } - - #[test] - fn prefers_simsun_for_localized_docx_font_name() { - assert_eq!( - font_preference("simsun", '学', false, false, Some("宋体")), - 0 - ); - assert_eq!( - font_preference("simhei", '学', true, false, Some("黑体")), - 0 - ); - } - - #[test] - fn prefers_matching_verdana_style_variant() { - assert_eq!( - font_preference("verdana", 'A', false, false, Some("verdana")), - 0 - ); - assert_eq!( - font_preference("verdanab", 'A', true, false, Some("verdana")), - 0 - ); - assert_eq!( - font_preference("verdanai", 'A', false, true, Some("verdana")), - 0 - ); - assert_eq!( - font_preference("verdanaz", 'A', true, true, Some("verdana")), - 0 - ); - assert_eq!( - font_preference("verdana", 'A', true, false, Some("verdana")), - 1 - ); - assert_eq!( - font_preference("calibrib", 'A', true, false, Some("verdana")), - 2 - ); - } - - #[test] - fn prefers_matching_arial_style_variant() { - assert_eq!( - font_preference("arial", 'A', false, false, Some("arial")), - 0 - ); - assert_eq!( - font_preference("arialbd", 'A', true, false, Some("arial")), - 0 - ); - assert_eq!( - font_preference("ariali", 'A', false, true, Some("arial")), - 0 - ); - assert_eq!( - font_preference("arialbi", 'A', true, true, Some("arial")), - 0 - ); - assert_eq!(font_preference("arial", 'A', true, false, Some("arial")), 1); - } - - #[test] - fn prefers_book_antiqua_for_palatino_compatible_text() { - assert_eq!( - font_preference("bookos", 'A', false, false, Some("bookos")), - 0 - ); - assert_eq!( - font_preference("bookosb", 'A', true, false, Some("bookos")), - 0 - ); - assert_eq!( - font_preference("calibrib", 'A', true, false, Some("bookos")), - 2 - ); - } - - #[test] - fn prefers_matching_invoice_font_variants() { - assert_eq!(font_preference("gara", 'A', false, false, Some("gara")), 0); - assert_eq!(font_preference("garabd", 'A', true, false, Some("gara")), 0); - assert_eq!( - font_preference("tcm_____", 'A', false, false, Some("tcm_____")), - 0 - ); - assert_eq!( - font_preference("tcb_____", 'A', true, false, Some("tcm_____")), - 0 - ); - } - - #[test] - fn writes_jpeg_image_xobject_and_draw_operation() { - let mut document = PdfDocument::new(); - let image_id = document.add_jpeg_image(vec![0xff, 0xd8, 0xff, 0xd9], 2, 3); - document - .add_page(100.0, 100.0) - .add_image(image_id, 10.0, 20.0, 30.0, 40.0); - - let pdf = String::from_utf8_lossy(&document.to_bytes()).into_owned(); - assert!(pdf.contains("/Filter /DCTDecode")); - assert!(pdf.contains("/Width 2 /Height 3")); - assert!(pdf.contains("30.00 0 0 40.00 10.00 20.00 cm /Im1 Do")); - } - - #[test] - fn writes_rgba_image_with_soft_mask() { - let mut document = PdfDocument::new(); - let image_id = document.add_rgba_image(vec![255, 0, 0, 128], 1, 1); - document - .add_page(100.0, 100.0) - .add_image(image_id, 10.0, 20.0, 30.0, 40.0); - - let pdf = String::from_utf8_lossy(&document.to_bytes()).into_owned(); - assert!(pdf.contains("/SMask")); - assert!(pdf.contains("/Filter /FlateDecode")); - } - - #[test] - fn writes_clipping_path_around_page_operations() { - let mut document = PdfDocument::new(); - let page = document.add_page(100.0, 100.0); - page.push_clip(10.0, 20.0, 30.0, 40.0); - page.add_text("clipped", 10.0, 20.0, 12.0, super::PdfColor::BLACK, false); - page.pop_clip(); - - let pdf = String::from_utf8_lossy(&document.to_bytes()).into_owned(); - assert!(pdf.contains("q 10.00 20.00 30.00 40.00 re W n")); - assert!(pdf.contains("Q\n")); - } - - #[test] - fn writes_pptx_vector_primitives() { - let mut document = PdfDocument::new(); - let page = document.add_page(100.0, 100.0); - page.add_ellipse(10.0, 20.0, 30.0, 40.0, PdfColor::BLACK); - page.add_path( - vec![ - PdfPathCommand::MoveTo(1.0, 2.0), - PdfPathCommand::LineTo(3.0, 4.0), - PdfPathCommand::CurveTo(5.0, 6.0, 7.0, 8.0, 9.0, 10.0), - PdfPathCommand::Close, - ], - PdfColor::WHITE, - ); - page.add_line_with_dash_pattern((1.0, 2.0), (3.0, 4.0), PdfColor::BLACK, 1.0, &[3.0, 2.0]); - - let pdf = String::from_utf8_lossy(&document.to_bytes()).into_owned(); - assert!(pdf.contains("c h f")); - assert!(pdf.contains("1.00 2.00 m 3.00 4.00 l")); - assert!(pdf.contains("5.00 6.00 7.00 8.00 9.00 10.00 c h f")); - assert!(pdf.contains("[3.00 2.00] 0 d")); - } -} diff --git a/minipdf-rs/crates/minipdf/src/pptx.rs b/minipdf-rs/crates/minipdf/src/pptx.rs deleted file mode 100644 index 24274aeb..00000000 --- a/minipdf-rs/crates/minipdf/src/pptx.rs +++ /dev/null @@ -1,2840 +0,0 @@ -use std::collections::HashMap; -use std::io::{Cursor, Read}; - -use roxmltree::{Document, Node}; -use zip::ZipArchive; - -use crate::pdf::styled_text_width_with_font; -use crate::pdf::PdfPathCommand; -use crate::{ConversionOptions, MiniPdfError, PdfColor, PdfDocument, Result}; - -const EMUS_PER_POINT: f32 = 12_700.0; -const DEFAULT_SLIDE_WIDTH_EMU: i64 = 9_144_000; -const DEFAULT_SLIDE_HEIGHT_EMU: i64 = 6_858_000; -const OFFICE_RELATIONSHIPS_NS: &str = - "http://schemas.openxmlformats.org/officeDocument/2006/relationships"; - -#[derive(Debug)] -struct PptxDocument { - width: f32, - height: f32, - slides: Vec, -} - -#[derive(Debug)] -struct PptxSlide { - width: f32, - height: f32, - background: Option, - elements: Vec, -} - -#[derive(Debug)] -enum PptxElement { - Shape(PptxShape), - Picture(PptxPicture), - Line(PptxLine), -} - -#[derive(Debug)] -struct PptxShape { - shape_type: String, - bounds: PptxRect, - fill: Option, - outline: Option, - paragraphs: Vec, - text_body: PptxTextBody, -} - -#[derive(Debug)] -struct PptxPicture { - bounds: PptxRect, - data: PptxImageData, -} - -#[derive(Debug)] -enum PptxImageData { - Jpeg { - data: Vec, - width: u16, - height: u16, - }, - Rgba { - data: Vec, - width: u16, - height: u16, - }, - Svg { - data: Vec, - crop: PptxCrop, - }, -} - -#[derive(Debug, Clone, Copy, Default)] -struct PptxCrop { - left: f32, - top: f32, - right: f32, - bottom: f32, -} - -#[derive(Debug)] -struct PptxLine { - x1: f32, - y1: f32, - x2: f32, - y2: f32, - outline: PptxOutline, -} - -#[derive(Debug, Clone)] -struct PptxOutline { - color: PdfColor, - width: f32, - dash_pattern: Vec, -} - -#[derive(Debug)] -struct PptxParagraph { - runs: Vec, - alignment: TextAlignment, - margin_left: f32, - indent: f32, - space_before: f32, - line_spacing: f32, -} - -#[derive(Debug, Clone)] -struct PptxRun { - text: String, - font_size: f32, - color: PdfColor, - bold: bool, - italic: bool, - underline: bool, - font_name: Option, -} - -#[derive(Debug, Clone, Copy)] -enum TextAlignment { - Left, - Center, - Right, -} - -#[derive(Debug, Clone, Copy)] -enum VerticalAnchor { - Top, - Middle, - Bottom, -} - -#[derive(Debug, Clone, Copy)] -struct PptxTextBody { - left_inset: f32, - top_inset: f32, - right_inset: f32, - bottom_inset: f32, - anchor: VerticalAnchor, -} - -#[derive(Debug, Clone, PartialEq, Eq, Hash)] -struct PlaceholderKey { - placeholder_type: String, - index: Option, -} - -#[derive(Debug, Clone)] -struct PlaceholderStyle { - bounds: Option, - shape_type: Option, - fill: Option, - outline: Option, - text_body: PptxTextBody, - paragraphs: HashMap, -} - -#[derive(Debug, Clone, Default)] -struct ParagraphDefaults { - alignment: Option, - margin_left: Option, - indent: Option, - space_before: Option, - line_spacing: Option, - bullet: Option, - run: RunDefaults, -} - -#[derive(Debug, Clone, Default)] -struct RunDefaults { - font_size: Option, - color: Option, - bold: Option, - italic: Option, - underline: Option, - latin_font: Option, - east_asian_font: Option, - complex_font: Option, -} - -impl Default for PptxTextBody { - fn default() -> Self { - Self { - left_inset: 0.0, - top_inset: 0.0, - right_inset: 0.0, - bottom_inset: 0.0, - anchor: VerticalAnchor::Top, - } - } -} - -#[derive(Debug, Clone, Copy)] -struct PptxRect { - x: f32, - y: f32, - width: f32, - height: f32, -} - -#[derive(Debug, Clone, Copy)] -struct CoordinateMap { - target_x: f64, - target_y: f64, - target_width: f64, - target_height: f64, - source_x: f64, - source_y: f64, - source_width: f64, - source_height: f64, -} - -impl CoordinateMap { - fn root(width: i64, height: i64) -> Self { - Self { - target_x: 0.0, - target_y: 0.0, - target_width: width as f64, - target_height: height as f64, - source_x: 0.0, - source_y: 0.0, - source_width: width as f64, - source_height: height as f64, - } - } - - fn map_x(self, value: i64) -> f64 { - self.target_x - + (value as f64 - self.source_x) * self.target_width / self.source_width.max(1.0) - } - - fn map_y(self, value: i64) -> f64 { - self.target_y - + (value as f64 - self.source_y) * self.target_height / self.source_height.max(1.0) - } - - fn map_rect(self, x: i64, y: i64, width: i64, height: i64) -> PptxRect { - let left = self.map_x(x); - let top = self.map_y(y); - let right = self.map_x(x + width); - let bottom = self.map_y(y + height); - PptxRect { - x: (left / EMUS_PER_POINT as f64) as f32, - y: (top / EMUS_PER_POINT as f64) as f32, - width: ((right - left) / EMUS_PER_POINT as f64) as f32, - height: ((bottom - top) / EMUS_PER_POINT as f64) as f32, - } - } -} - -#[derive(Debug, Clone)] -struct Relationship { - target: String, - rel_type: String, - external: bool, - relationship_path: String, -} - -pub(crate) fn convert_pptx_bytes(input: &[u8], options: &ConversionOptions) -> Result> { - let presentation = read_pptx(input)?; - Ok(render_pptx(&presentation, options).to_bytes()) -} - -fn read_pptx(input: &[u8]) -> Result { - let mut archive = ZipArchive::new(Cursor::new(input))?; - let presentation_xml = - read_zip_bytes(&mut archive, "ppt/presentation.xml")?.ok_or_else(|| { - MiniPdfError::InvalidInput("PPTX package is missing ppt/presentation.xml".to_owned()) - })?; - let presentation_text = String::from_utf8(presentation_xml) - .map_err(|_| MiniPdfError::InvalidInput("presentation.xml is not UTF-8".to_owned()))?; - let presentation = Document::parse(&presentation_text)?; - let relationships = read_relationships(&mut archive, "ppt/presentation.xml")?; - let theme = read_theme_colors(&mut archive, &relationships)?; - - let slide_size = presentation - .descendants() - .find(|node| is_element(*node, "sldSz")); - let width_emu = integer_attribute(slide_size, "cx").unwrap_or(DEFAULT_SLIDE_WIDTH_EMU); - let height_emu = integer_attribute(slide_size, "cy").unwrap_or(DEFAULT_SLIDE_HEIGHT_EMU); - let width = width_emu as f32 / EMUS_PER_POINT; - let height = height_emu as f32 / EMUS_PER_POINT; - - let mut slide_paths = Vec::new(); - for slide_id in presentation - .descendants() - .filter(|node| is_element(*node, "sldId")) - { - let Some(id) = slide_id - .attributes() - .find(|attribute| { - attribute.name() == "id" && attribute.namespace() == Some(OFFICE_RELATIONSHIPS_NS) - }) - .map(|attribute| attribute.value()) - else { - continue; - }; - let Some(relationship) = relationships.get(id) else { - continue; - }; - slide_paths.push(resolve_part_target( - "ppt/presentation.xml", - &relationship.target, - )); - } - if slide_paths.is_empty() { - slide_paths = archive - .file_names() - .filter(|name| name.starts_with("ppt/slides/slide") && name.ends_with(".xml")) - .map(str::to_owned) - .collect(); - slide_paths.sort_by_key(|path| natural_slide_number(path)); - } - - let mut slides = Vec::new(); - for slide_path in slide_paths { - if let Some(slide) = read_slide( - &mut archive, - &slide_path, - width, - height, - width_emu, - height_emu, - &theme, - )? { - slides.push(slide); - } - } - if slides.is_empty() { - let mut fallback_paths: Vec<_> = archive - .file_names() - .filter(|name| name.starts_with("ppt/slides/slide") && name.ends_with(".xml")) - .map(str::to_owned) - .collect(); - fallback_paths.sort_by_key(|path| natural_slide_number(path)); - for slide_path in fallback_paths { - if let Some(slide) = read_slide( - &mut archive, - &slide_path, - width, - height, - width_emu, - height_emu, - &theme, - )? { - slides.push(slide); - } - } - } - - Ok(PptxDocument { - width, - height, - slides, - }) -} - -#[allow(clippy::too_many_arguments)] -fn read_slide( - archive: &mut ZipArchive>, - slide_path: &str, - width: f32, - height: f32, - width_emu: i64, - height_emu: i64, - theme: &HashMap, -) -> Result> { - let Some(slide_bytes) = read_zip_bytes(archive, slide_path)? else { - return Ok(None); - }; - let slide_text = String::from_utf8(slide_bytes) - .map_err(|_| MiniPdfError::InvalidInput(format!("{slide_path} is not UTF-8")))?; - let slide = Document::parse(&slide_text)?; - let relationships = read_relationships(archive, slide_path)?; - let root_map = CoordinateMap::root(width_emu, height_emu); - let mut elements = Vec::new(); - - let layout = read_related_xml(archive, slide_path, &relationships, "/slideLayout")?; - let master = if let Some((layout_path, _, layout_relationships)) = &layout { - read_related_xml(archive, layout_path, layout_relationships, "/slideMaster")? - } else { - None - }; - - let master_document = master - .as_ref() - .map(|(_, xml, _)| Document::parse(xml)) - .transpose()?; - let layout_document = layout - .as_ref() - .map(|(_, xml, _)| Document::parse(xml)) - .transpose()?; - let slide_theme = apply_color_map( - theme, - &slide, - layout_document.as_ref(), - master_document.as_ref(), - ); - let mut placeholder_defaults = HashMap::new(); - if let Some(document) = &master_document { - add_placeholder_defaults(document, &slide_theme, root_map, &mut placeholder_defaults); - } - if let Some(document) = &layout_document { - add_placeholder_defaults(document, &slide_theme, root_map, &mut placeholder_defaults); - } - - if let (Some(master_document), Some((_, _, master_relationships))) = (&master_document, &master) - { - read_shape_tree( - archive, - master_document, - master_relationships, - &slide_theme, - root_map, - &mut elements, - false, - None, - )?; - } - if let (Some(layout_document), Some((_, _, layout_relationships))) = (&layout_document, &layout) - { - read_shape_tree( - archive, - layout_document, - layout_relationships, - &slide_theme, - root_map, - &mut elements, - false, - None, - )?; - } - read_shape_tree( - archive, - &slide, - &relationships, - &slide_theme, - root_map, - &mut elements, - true, - Some(&placeholder_defaults), - )?; - - let background = read_background(&slide, &slide_theme) - .or_else(|| { - layout_document - .as_ref() - .and_then(|doc| read_background(doc, &slide_theme)) - }) - .or_else(|| { - master_document - .as_ref() - .and_then(|doc| read_background(doc, &slide_theme)) - }); - - Ok(Some(PptxSlide { - width, - height, - background, - elements, - })) -} - -#[allow(clippy::too_many_arguments)] -fn read_shape_tree( - archive: &mut ZipArchive>, - document: &Document<'_>, - relationships: &HashMap, - theme: &HashMap, - coordinate_map: CoordinateMap, - elements: &mut Vec, - include_placeholders: bool, - placeholder_defaults: Option<&HashMap>, -) -> Result<()> { - let Some(shape_tree) = document - .descendants() - .find(|node| is_element(*node, "spTree")) - else { - return Ok(()); - }; - read_shape_children( - archive, - shape_tree, - relationships, - theme, - coordinate_map, - elements, - include_placeholders, - placeholder_defaults, - ) -} - -#[allow(clippy::too_many_arguments)] -fn read_shape_children( - archive: &mut ZipArchive>, - container: Node<'_, '_>, - relationships: &HashMap, - theme: &HashMap, - coordinate_map: CoordinateMap, - elements: &mut Vec, - include_placeholders: bool, - placeholder_defaults: Option<&HashMap>, -) -> Result<()> { - for child_node in container.children().filter(Node::is_element) { - let placeholder = child_node.descendants().any(|node| is_element(node, "ph")); - if placeholder && !include_placeholders { - continue; - } - match child_node.tag_name().name() { - "sp" => read_shape( - child_node, - theme, - coordinate_map, - elements, - placeholder_defaults, - ), - "cxnSp" => read_connector(child_node, theme, coordinate_map, elements), - "pic" => read_picture(archive, child_node, relationships, coordinate_map, elements)?, - "graphicFrame" => read_graphic_frame( - archive, - child_node, - relationships, - theme, - coordinate_map, - elements, - )?, - "grpSp" => { - let group_map = child(child_node, "grpSpPr") - .and_then(|node| child(node, "xfrm")) - .map(|transform| create_group_map(transform, coordinate_map)) - .unwrap_or(coordinate_map); - read_shape_children( - archive, - child_node, - relationships, - theme, - group_map, - elements, - include_placeholders, - placeholder_defaults, - )?; - } - _ => {} - } - } - Ok(()) -} - -fn read_shape( - shape: Node<'_, '_>, - theme: &HashMap, - coordinate_map: CoordinateMap, - elements: &mut Vec, - placeholder_defaults: Option<&HashMap>, -) { - let inherited = read_placeholder_key(shape).and_then(|key| { - placeholder_defaults.and_then(|defaults| { - defaults.get(&key).or_else(|| { - defaults.get(&PlaceholderKey { - placeholder_type: key.placeholder_type, - index: None, - }) - }) - }) - }); - let shape_properties = child(shape, "spPr"); - let Some(bounds) = shape_properties - .and_then(|node| child(node, "xfrm")) - .map(|transform| read_bounds(transform, coordinate_map)) - .or_else(|| inherited.and_then(|style| style.bounds)) - else { - return; - }; - if bounds.width <= 0.0 || bounds.height <= 0.0 { - return; - } - let shape_type = shape_properties - .and_then(|node| child(node, "prstGeom")) - .and_then(|node| node.attribute("prst")) - .map(str::to_owned) - .or_else(|| inherited.and_then(|style| style.shape_type.clone())) - .unwrap_or_else(|| "rect".to_owned()); - let outline = shape_properties - .and_then(|node| child(node, "ln")) - .and_then(|node| read_outline(node, theme)) - .or_else(|| read_style_outline(shape, theme)) - .or_else(|| inherited.and_then(|style| style.outline.clone())); - if shape_type.eq_ignore_ascii_case("line") { - add_line_from_bounds( - shape_properties.and_then(|node| child(node, "xfrm")), - bounds, - outline.unwrap_or_else(default_outline), - elements, - ); - return; - } - let fill = shape_properties - .and_then(|node| read_fill(node, theme)) - .or_else(|| read_style_fill(shape, theme)) - .or_else(|| inherited.and_then(|style| style.fill)); - let paragraphs = child(shape, "txBody") - .map(|body| read_paragraphs(body, theme, inherited)) - .unwrap_or_default(); - let text_body = child(shape, "txBody") - .and_then(|body| child(body, "bodyPr")) - .map(|body| read_text_body(body, inherited.map(|style| style.text_body))) - .or_else(|| inherited.map(|style| style.text_body)) - .unwrap_or_default(); - if fill.is_some() || outline.is_some() || !paragraphs.is_empty() { - elements.push(PptxElement::Shape(PptxShape { - shape_type, - bounds, - fill, - outline, - paragraphs, - text_body, - })); - } -} - -fn read_connector( - connector: Node<'_, '_>, - theme: &HashMap, - coordinate_map: CoordinateMap, - elements: &mut Vec, -) { - let Some(properties) = child(connector, "spPr") else { - return; - }; - let Some(transform) = child(properties, "xfrm") else { - return; - }; - let bounds = read_bounds(transform, coordinate_map); - let outline = child(properties, "ln") - .and_then(|node| read_outline(node, theme)) - .unwrap_or_else(default_outline); - add_line_from_bounds(Some(transform), bounds, outline, elements); -} - -fn read_picture( - archive: &mut ZipArchive>, - picture: Node<'_, '_>, - relationships: &HashMap, - coordinate_map: CoordinateMap, - elements: &mut Vec, -) -> Result<()> { - if picture - .descendants() - .find(|node| is_element(*node, "cNvPr")) - .and_then(|node| node.attribute("hidden")) - .is_some_and(read_bool) - { - return Ok(()); - } - let Some(transform) = picture - .children() - .find(|node| is_element(*node, "spPr")) - .and_then(|node| child(node, "xfrm")) - else { - return Ok(()); - }; - let bounds = read_bounds(transform, coordinate_map); - if bounds.width <= 0.0 || bounds.height <= 0.0 { - return Ok(()); - } - let Some(embed_id) = picture - .descendants() - .filter(|node| is_element(*node, "blip") || is_element(*node, "svgBlip")) - .find_map(|node| attribute_by_local_name(node, "embed")) - else { - return Ok(()); - }; - let Some(relationship) = relationships.get(embed_id) else { - return Ok(()); - }; - if relationship.external { - return Ok(()); - } - let source_path = relationship_source_path(relationship); - let media_path = resolve_part_target(&source_path, &relationship.target); - let Some(bytes) = read_zip_bytes(archive, &media_path)? else { - return Ok(()); - }; - let crop = picture - .descendants() - .find(|node| is_element(*node, "srcRect")) - .map(|node| PptxCrop { - left: crop_attribute(node, "l"), - top: crop_attribute(node, "t"), - right: crop_attribute(node, "r"), - bottom: crop_attribute(node, "b"), - }) - .unwrap_or_default(); - let data = if media_path.to_ascii_lowercase().ends_with(".svg") || bytes.starts_with(b">, - frame: Node<'_, '_>, - relationships: &HashMap, - theme: &HashMap, - coordinate_map: CoordinateMap, - elements: &mut Vec, -) -> Result<()> { - let Some(transform) = child(frame, "xfrm") else { - return Ok(()); - }; - let bounds = read_bounds(transform, coordinate_map); - let graphic_data = frame - .descendants() - .find(|node| is_element(*node, "graphicData")); - if graphic_data - .and_then(|node| node.attribute("uri")) - .is_some_and(|uri| uri.ends_with("/diagram")) - { - read_diagram(archive, relationships, theme, transform, bounds, elements)?; - return Ok(()); - } - let Some(table) = frame.descendants().find(|node| is_element(*node, "tbl")) else { - return Ok(()); - }; - let widths: Vec = table - .descendants() - .filter(|node| is_element(*node, "gridCol")) - .filter_map(|node| node.attribute("w").and_then(|value| value.parse().ok())) - .collect(); - let rows: Vec<_> = table - .children() - .filter(|node| is_element(*node, "tr")) - .collect(); - let total_width: i64 = widths.iter().sum(); - let total_height: i64 = rows - .iter() - .filter_map(|row| { - row.attribute("h") - .and_then(|value| value.parse::().ok()) - }) - .sum(); - if widths.is_empty() || total_width <= 0 || total_height <= 0 { - return Ok(()); - } - let mut top = bounds.y; - for row in rows { - let row_height = bounds.height - * row - .attribute("h") - .and_then(|value| value.parse::().ok()) - .unwrap_or(0.0) - / total_height as f32; - let mut left = bounds.x; - let mut column = 0; - for cell_node in row.children().filter(|node| is_element(*node, "tc")) { - if column >= widths.len() { - break; - } - let span = cell_node - .attribute("gridSpan") - .and_then(|value| value.parse::().ok()) - .unwrap_or(1) - .max(1); - let spanned_width: i64 = widths.iter().skip(column).take(span).sum(); - let cell_width = bounds.width * spanned_width as f32 / total_width as f32; - let cell_bounds = PptxRect { - x: left, - y: top, - width: cell_width, - height: row_height, - }; - let properties = child(cell_node, "tcPr"); - let fill = properties.and_then(|node| read_fill(node, theme)); - let paragraphs = child(cell_node, "txBody") - .map(|body| read_paragraphs(body, theme, None)) - .unwrap_or_default(); - elements.push(PptxElement::Shape(PptxShape { - shape_type: "rect".to_owned(), - bounds: cell_bounds, - fill, - outline: None, - paragraphs, - text_body: PptxTextBody::default(), - })); - add_table_borders(properties, cell_bounds, theme, elements); - left += cell_width; - column += span; - } - top += row_height; - } - Ok(()) -} - -fn add_table_borders( - properties: Option>, - bounds: PptxRect, - theme: &HashMap, - elements: &mut Vec, -) { - let Some(properties) = properties else { - return; - }; - for (name, x1, y1, x2, y2) in [ - ( - "lnL", - bounds.x, - bounds.y, - bounds.x, - bounds.y + bounds.height, - ), - ( - "lnR", - bounds.x + bounds.width, - bounds.y, - bounds.x + bounds.width, - bounds.y + bounds.height, - ), - ("lnT", bounds.x, bounds.y, bounds.x + bounds.width, bounds.y), - ( - "lnB", - bounds.x, - bounds.y + bounds.height, - bounds.x + bounds.width, - bounds.y + bounds.height, - ), - ] { - if let Some(outline) = child(properties, name).and_then(|node| read_outline(node, theme)) { - elements.push(PptxElement::Line(PptxLine { - x1, - y1, - x2, - y2, - outline, - })); - } - } -} - -fn read_diagram( - archive: &mut ZipArchive>, - relationships: &HashMap, - theme: &HashMap, - frame_transform: Node<'_, '_>, - bounds: PptxRect, - elements: &mut Vec, -) -> Result<()> { - let Some(relationship) = relationships.values().find(|relationship| { - relationship.rel_type.ends_with("/diagramDrawing") && !relationship.external - }) else { - return Ok(()); - }; - let drawing_path = resolve_part_target( - &relationship_source_path(relationship), - &relationship.target, - ); - let Some(bytes) = read_zip_bytes(archive, &drawing_path)? else { - return Ok(()); - }; - let text = String::from_utf8(bytes) - .map_err(|_| MiniPdfError::InvalidInput(format!("{drawing_path} is not UTF-8")))?; - let drawing = Document::parse(&text)?; - let extent = child(frame_transform, "ext"); - let frame_width = integer_attribute(extent, "cx").unwrap_or(0); - let frame_height = integer_attribute(extent, "cy").unwrap_or(0); - if frame_width <= 0 || frame_height <= 0 { - return Ok(()); - } - let map = CoordinateMap { - target_x: bounds.x as f64 * EMUS_PER_POINT as f64, - target_y: bounds.y as f64 * EMUS_PER_POINT as f64, - target_width: bounds.width as f64 * EMUS_PER_POINT as f64, - target_height: bounds.height as f64 * EMUS_PER_POINT as f64, - source_x: 0.0, - source_y: 0.0, - source_width: frame_width as f64, - source_height: frame_height as f64, - }; - let Some(shape_tree) = drawing - .descendants() - .find(|node| is_element(*node, "spTree")) - else { - return Ok(()); - }; - for shape in shape_tree.children().filter(|node| is_element(*node, "sp")) { - read_shape(shape, theme, map, elements, None); - } - Ok(()) -} - -fn add_placeholder_defaults( - document: &Document<'_>, - theme: &HashMap, - coordinate_map: CoordinateMap, - defaults: &mut HashMap, -) { - let Some(shape_tree) = document - .descendants() - .find(|node| is_element(*node, "spTree")) - else { - return; - }; - for shape in shape_tree - .descendants() - .filter(|node| is_element(*node, "sp")) - { - let Some(key) = read_placeholder_key(shape) else { - continue; - }; - let properties = child(shape, "spPr"); - let text_body = child(shape, "txBody"); - let body_properties = text_body.and_then(|node| child(node, "bodyPr")); - let style = PlaceholderStyle { - bounds: properties - .and_then(|node| child(node, "xfrm")) - .map(|node| read_bounds(node, coordinate_map)), - shape_type: properties - .and_then(|node| child(node, "prstGeom")) - .and_then(|node| node.attribute("prst")) - .map(str::to_owned), - fill: properties - .and_then(|node| read_fill(node, theme)) - .or_else(|| read_style_fill(shape, theme)), - outline: properties - .and_then(|node| child(node, "ln")) - .and_then(|node| read_outline(node, theme)) - .or_else(|| read_style_outline(shape, theme)), - text_body: body_properties - .map(|node| read_text_body(node, None)) - .unwrap_or_default(), - paragraphs: text_body - .map(|node| read_paragraph_defaults(node, theme)) - .unwrap_or_default(), - }; - defaults.insert(key.clone(), style.clone()); - defaults - .entry(PlaceholderKey { - placeholder_type: key.placeholder_type, - index: None, - }) - .or_insert(style); - } -} - -fn read_placeholder_key(shape: Node<'_, '_>) -> Option { - let placeholder = shape.descendants().find(|node| is_element(*node, "ph"))?; - Some(PlaceholderKey { - placeholder_type: placeholder.attribute("type").unwrap_or("body").to_owned(), - index: placeholder.attribute("idx").map(str::to_owned), - }) -} - -fn read_paragraph_defaults( - text_body: Node<'_, '_>, - theme: &HashMap, -) -> HashMap { - let Some(list_style) = child(text_body, "lstStyle") else { - return HashMap::new(); - }; - list_style - .children() - .filter(Node::is_element) - .filter_map(|properties| { - let name = properties.tag_name().name(); - let level = name - .strip_prefix("lvl")? - .strip_suffix("pPr")? - .parse::() - .ok()? - .saturating_sub(1); - Some(( - level, - ParagraphDefaults { - alignment: read_alignment(Some(properties)), - margin_left: emu_attribute(Some(properties), "marL"), - indent: emu_attribute(Some(properties), "indent"), - space_before: read_space_before(Some(properties)), - line_spacing: read_line_spacing(Some(properties)), - bullet: read_bullet_setting(properties).or_else(|| (level > 0).then_some(true)), - run: child(properties, "defRPr") - .map(|node| read_run_defaults(node, theme)) - .unwrap_or_default(), - }, - )) - }) - .collect() -} - -fn read_paragraphs( - text_body: Node<'_, '_>, - theme: &HashMap, - inherited_style: Option<&PlaceholderStyle>, -) -> Vec { - text_body - .children() - .filter(|node| is_element(*node, "p")) - .map(|paragraph| { - let properties = child(paragraph, "pPr"); - let level = properties - .and_then(|node| node.attribute("lvl")) - .and_then(|value| value.parse::().ok()) - .unwrap_or(0) - .min(8); - let inherited = inherited_style.and_then(|style| { - style - .paragraphs - .get(&level) - .or_else(|| style.paragraphs.get(&0)) - }); - let default_run = properties.and_then(|node| child(node, "defRPr")); - let is_bullet = properties - .and_then(read_bullet_setting) - .or_else(|| inherited.and_then(|style| style.bullet)) - .unwrap_or(false); - let mut runs = Vec::new(); - let mut has_text = false; - for run_node in paragraph.children().filter(Node::is_element) { - match run_node.tag_name().name() { - "r" | "fld" => { - let Some(text_node) = - run_node.descendants().find(|node| is_element(*node, "t")) - else { - continue; - }; - let mut text = text_node.text().unwrap_or_default().to_owned(); - if is_bullet && !has_text { - text.insert_str(0, "\u{2022} "); - } - if !text.is_empty() { - runs.push(read_run( - text, - child(run_node, "rPr"), - default_run, - inherited.map(|style| &style.run), - theme, - )); - has_text = true; - } - } - "br" => runs.push(read_run( - "\n".to_owned(), - child(run_node, "rPr"), - default_run, - inherited.map(|style| &style.run), - theme, - )), - "tab" => runs.push(read_run( - "\t".to_owned(), - child(run_node, "rPr"), - default_run, - inherited.map(|style| &style.run), - theme, - )), - _ => {} - } - } - PptxParagraph { - runs, - alignment: read_alignment(properties) - .or_else(|| inherited.and_then(|style| style.alignment)) - .unwrap_or(TextAlignment::Left), - margin_left: emu_attribute(properties, "marL") - .or_else(|| inherited.and_then(|style| style.margin_left)) - .unwrap_or(0.0), - indent: emu_attribute(properties, "indent") - .or_else(|| inherited.and_then(|style| style.indent)) - .unwrap_or(0.0), - space_before: read_space_before(properties) - .or_else(|| inherited.and_then(|style| style.space_before)) - .unwrap_or(0.0), - line_spacing: read_line_spacing(properties) - .or_else(|| inherited.and_then(|style| style.line_spacing)) - .unwrap_or(1.15), - } - }) - .collect() -} - -fn read_run( - text: String, - properties: Option>, - defaults: Option>, - inherited: Option<&RunDefaults>, - theme: &HashMap, -) -> PptxRun { - let font_size = properties - .and_then(|node| node.attribute("sz")) - .or_else(|| defaults.and_then(|node| node.attribute("sz"))) - .and_then(|value| value.parse::().ok()) - .map(|value| (value / 100.0).max(1.0)) - .or_else(|| inherited.and_then(|style| style.font_size)) - .unwrap_or(18.0); - let color = properties - .and_then(|node| read_fill(node, theme)) - .or_else(|| defaults.and_then(|node| read_fill(node, theme))) - .or_else(|| inherited.and_then(|style| style.color)) - .or_else(|| theme.get("tx1").copied()) - .unwrap_or(PdfColor::BLACK); - let bold = optional_bool_attribute(properties, "b") - .or_else(|| optional_bool_attribute(defaults, "b")) - .or_else(|| inherited.and_then(|style| style.bold)) - .unwrap_or(false); - let italic = optional_bool_attribute(properties, "i") - .or_else(|| optional_bool_attribute(defaults, "i")) - .or_else(|| inherited.and_then(|style| style.italic)) - .unwrap_or(false); - let underline = properties - .and_then(|node| node.attribute("u")) - .or_else(|| defaults.and_then(|node| node.attribute("u"))) - .map(|value| !value.eq_ignore_ascii_case("none")) - .or_else(|| inherited.and_then(|style| style.underline)) - .unwrap_or(false) - || properties.is_some_and(|node| { - node.children() - .any(|child_node| is_element(child_node, "hlinkClick")) - }); - let font_name = select_font_name(&text, properties) - .or_else(|| select_font_name(&text, defaults)) - .or_else(|| inherited.and_then(|style| inherited_font_name(&text, style))); - PptxRun { - text, - font_size, - color, - bold, - italic, - underline, - font_name, - } -} - -fn read_text_body(properties: Node<'_, '_>, inherited: Option) -> PptxTextBody { - let fallback = inherited.unwrap_or_default(); - PptxTextBody { - left_inset: emu_attribute(Some(properties), "lIns").unwrap_or(fallback.left_inset), - top_inset: emu_attribute(Some(properties), "tIns").unwrap_or(fallback.top_inset), - right_inset: emu_attribute(Some(properties), "rIns").unwrap_or(fallback.right_inset), - bottom_inset: emu_attribute(Some(properties), "bIns").unwrap_or(fallback.bottom_inset), - anchor: match properties.attribute("anchor") { - Some("ctr") => VerticalAnchor::Middle, - Some("b") => VerticalAnchor::Bottom, - Some(_) => VerticalAnchor::Top, - None => fallback.anchor, - }, - } -} - -fn read_alignment(properties: Option>) -> Option { - match properties?.attribute("algn")? { - "ctr" => Some(TextAlignment::Center), - "r" => Some(TextAlignment::Right), - _ => Some(TextAlignment::Left), - } -} - -fn read_space_before(properties: Option>) -> Option { - child(properties?, "spcBef") - .and_then(|node| child(node, "spcPts")) - .and_then(|node| node.attribute("val")) - .and_then(|value| value.parse::().ok()) - .map(|value| (value / 100.0).max(0.0)) -} - -fn read_line_spacing(properties: Option>) -> Option { - child(properties?, "lnSpc") - .and_then(|node| child(node, "spcPct")) - .and_then(|node| node.attribute("val")) - .and_then(|value| value.parse::().ok()) - .map(|value| (value / 100_000.0).max(0.1)) -} - -fn read_bullet_setting(properties: Node<'_, '_>) -> Option { - if child(properties, "buNone").is_some() { - Some(false) - } else if child(properties, "buChar").is_some() || child(properties, "buAutoNum").is_some() { - Some(true) - } else { - None - } -} - -fn read_run_defaults(node: Node<'_, '_>, theme: &HashMap) -> RunDefaults { - RunDefaults { - font_size: node - .attribute("sz") - .and_then(|value| value.parse::().ok()) - .map(|value| (value / 100.0).max(1.0)), - color: read_fill(node, theme), - bold: node.attribute("b").map(read_bool), - italic: node.attribute("i").map(read_bool), - underline: node - .attribute("u") - .map(|value| !value.eq_ignore_ascii_case("none")), - latin_font: child(node, "latin") - .and_then(|font| font.attribute("typeface")) - .map(str::to_owned), - east_asian_font: child(node, "ea") - .and_then(|font| font.attribute("typeface")) - .map(str::to_owned), - complex_font: child(node, "cs") - .and_then(|font| font.attribute("typeface")) - .map(str::to_owned), - } -} - -fn inherited_font_name(text: &str, style: &RunDefaults) -> Option { - if contains_east_asian(text) { - style.east_asian_font.clone() - } else if contains_complex_script(text) { - style.complex_font.clone() - } else { - style.latin_font.clone() - } - .or_else(|| style.latin_font.clone()) - .or_else(|| style.east_asian_font.clone()) - .or_else(|| style.complex_font.clone()) - .filter(|name| !name.starts_with('+')) -} - -fn read_bounds(transform: Node<'_, '_>, coordinate_map: CoordinateMap) -> PptxRect { - let offset = child(transform, "off"); - let extent = child(transform, "ext"); - coordinate_map.map_rect( - integer_attribute(offset, "x").unwrap_or(0), - integer_attribute(offset, "y").unwrap_or(0), - integer_attribute(extent, "cx").unwrap_or(0), - integer_attribute(extent, "cy").unwrap_or(0), - ) -} - -fn create_group_map(transform: Node<'_, '_>, parent: CoordinateMap) -> CoordinateMap { - let offset = child(transform, "off"); - let extent = child(transform, "ext"); - let child_offset = child(transform, "chOff"); - let child_extent = child(transform, "chExt"); - let group_x = integer_attribute(offset, "x").unwrap_or(0); - let group_y = integer_attribute(offset, "y").unwrap_or(0); - let group_width = integer_attribute(extent, "cx").unwrap_or(0); - let group_height = integer_attribute(extent, "cy").unwrap_or(0); - if group_width <= 0 || group_height <= 0 { - return parent; - } - CoordinateMap { - target_x: parent.map_x(group_x), - target_y: parent.map_y(group_y), - target_width: parent.map_x(group_x + group_width) - parent.map_x(group_x), - target_height: parent.map_y(group_y + group_height) - parent.map_y(group_y), - source_x: integer_attribute(child_offset, "x").unwrap_or(group_x) as f64, - source_y: integer_attribute(child_offset, "y").unwrap_or(group_y) as f64, - source_width: integer_attribute(child_extent, "cx").unwrap_or(group_width) as f64, - source_height: integer_attribute(child_extent, "cy").unwrap_or(group_height) as f64, - } -} - -fn add_line_from_bounds( - transform: Option>, - bounds: PptxRect, - outline: PptxOutline, - elements: &mut Vec, -) { - let flip_horizontal = transform - .and_then(|node| node.attribute("flipH")) - .is_some_and(read_bool); - let flip_vertical = transform - .and_then(|node| node.attribute("flipV")) - .is_some_and(read_bool); - elements.push(PptxElement::Line(PptxLine { - x1: if flip_horizontal { - bounds.x + bounds.width - } else { - bounds.x - }, - y1: if flip_vertical { - bounds.y + bounds.height - } else { - bounds.y - }, - x2: if flip_horizontal { - bounds.x - } else { - bounds.x + bounds.width - }, - y2: if flip_vertical { - bounds.y - } else { - bounds.y + bounds.height - }, - outline, - })); -} - -fn read_outline(node: Node<'_, '_>, theme: &HashMap) -> Option { - if child(node, "noFill").is_some() { - return None; - } - let width = node - .attribute("w") - .and_then(|value| value.parse::().ok()) - .map(|value| value / EMUS_PER_POINT) - .filter(|value| *value > 0.0) - .unwrap_or(1.0); - let dash_pattern = child(node, "prstDash") - .and_then(|dash| dash.attribute("val")) - .map(|value| match value { - "dot" | "sysDot" => vec![1.0, 2.0], - "dash" | "sysDash" => vec![3.0, 3.0], - "lgDash" => vec![6.0, 3.0], - "dashDot" | "sysDashDot" => vec![3.0, 2.0, 1.0, 2.0], - _ => Vec::new(), - }) - .unwrap_or_default(); - Some(PptxOutline { - color: read_fill(node, theme).unwrap_or(PdfColor::BLACK), - width, - dash_pattern, - }) -} - -fn default_outline() -> PptxOutline { - PptxOutline { - color: PdfColor::BLACK, - width: 1.0, - dash_pattern: Vec::new(), - } -} - -fn read_fill(node: Node<'_, '_>, theme: &HashMap) -> Option { - if child(node, "noFill").is_some() { - return None; - } - let fill = if is_element(node, "solidFill") { - Some(node) - } else { - child(node, "solidFill") - }?; - let color_node = fill.children().find(Node::is_element)?; - let color = match color_node.tag_name().name() { - "srgbClr" => color_node.attribute("val").and_then(parse_hex_color), - "schemeClr" => color_node - .attribute("val") - .and_then(|name| theme.get(name).copied()), - "sysClr" => color_node - .attribute("lastClr") - .or_else(|| color_node.attribute("val")) - .and_then(parse_hex_color), - "prstClr" => color_node.attribute("val").and_then(preset_color), - _ => None, - }?; - Some(apply_luminance(color, color_node)) -} - -fn read_style_fill(shape: Node<'_, '_>, theme: &HashMap) -> Option { - child(shape, "style") - .and_then(|style| child(style, "fillRef")) - .and_then(|reference| reference.children().find(Node::is_element)) - .and_then(|color| read_color_node(color, theme)) -} - -fn read_style_outline( - shape: Node<'_, '_>, - theme: &HashMap, -) -> Option { - let color = child(shape, "style") - .and_then(|style| child(style, "lnRef")) - .and_then(|reference| reference.children().find(Node::is_element)) - .and_then(|color| read_color_node(color, theme))?; - Some(PptxOutline { - color, - width: 1.0, - dash_pattern: Vec::new(), - }) -} - -fn read_background(document: &Document<'_>, theme: &HashMap) -> Option { - let background = document - .descendants() - .find(|node| is_element(*node, "bg"))?; - child(background, "bgPr") - .and_then(|node| read_fill(node, theme)) - .or_else(|| { - child(background, "bgRef") - .and_then(|node| node.children().find(Node::is_element)) - .and_then(|node| read_color_node(node, theme)) - }) -} - -fn apply_color_map( - theme: &HashMap, - slide: &Document<'_>, - layout: Option<&Document<'_>>, - master: Option<&Document<'_>>, -) -> HashMap { - let mut mapped = theme.clone(); - let color_map = override_color_map(slide) - .or_else(|| layout.and_then(override_color_map)) - .or_else(|| { - master.and_then(|document| { - document - .root_element() - .children() - .find(|node| is_element(*node, "clrMap")) - }) - }); - let Some(color_map) = color_map else { - return mapped; - }; - for alias in [ - "bg1", "tx1", "bg2", "tx2", "accent1", "accent2", "accent3", "accent4", "accent5", - "accent6", "hlink", "folHlink", - ] { - if let Some(source) = color_map.attribute(alias) { - if let Some(color) = theme.get(source).copied() { - mapped.insert(alias.to_owned(), color); - } - } - } - mapped -} - -fn override_color_map<'a, 'input>(document: &'a Document<'input>) -> Option> { - document - .root_element() - .children() - .find(|node| is_element(*node, "clrMapOvr")) - .and_then(|node| child(node, "overrideClrMapping")) -} - -fn read_theme_colors( - archive: &mut ZipArchive>, - relationships: &HashMap, -) -> Result> { - let mut colors = default_theme_colors(); - let theme_path = relationships - .values() - .find(|relationship| relationship.rel_type.ends_with("/theme")) - .map(|relationship| resolve_part_target("ppt/presentation.xml", &relationship.target)) - .unwrap_or_else(|| "ppt/theme/theme1.xml".to_owned()); - let Some(bytes) = read_zip_bytes(archive, &theme_path)? else { - return Ok(colors); - }; - let Ok(text) = String::from_utf8(bytes) else { - return Ok(colors); - }; - let Ok(document) = Document::parse(&text) else { - return Ok(colors); - }; - if let Some(scheme) = document - .descendants() - .find(|node| is_element(*node, "clrScheme")) - { - for slot in scheme.children().filter(Node::is_element) { - if let Some(color_node) = slot.children().find(Node::is_element) { - if let Some(color) = read_color_node(color_node, &colors) { - colors.insert(slot.tag_name().name().to_owned(), color); - } - } - } - } - add_theme_aliases(&mut colors); - Ok(colors) -} - -fn read_color_node(node: Node<'_, '_>, theme: &HashMap) -> Option { - let color = match node.tag_name().name() { - "srgbClr" => node.attribute("val").and_then(parse_hex_color), - "schemeClr" => node - .attribute("val") - .and_then(|name| theme.get(name).copied()), - "sysClr" => node - .attribute("lastClr") - .or_else(|| node.attribute("val")) - .and_then(parse_hex_color), - "prstClr" => node.attribute("val").and_then(preset_color), - _ => None, - }?; - Some(apply_luminance(color, node)) -} - -fn default_theme_colors() -> HashMap { - let mut colors = HashMap::from([ - ("lt1".to_owned(), PdfColor::WHITE), - ("dk1".to_owned(), PdfColor::BLACK), - ("lt2".to_owned(), parse_hex_color("EEECE1").unwrap()), - ("dk2".to_owned(), parse_hex_color("1F497D").unwrap()), - ("accent1".to_owned(), parse_hex_color("4F81BD").unwrap()), - ("accent2".to_owned(), parse_hex_color("C0504D").unwrap()), - ("accent3".to_owned(), parse_hex_color("9BBB59").unwrap()), - ("accent4".to_owned(), parse_hex_color("8064A2").unwrap()), - ("accent5".to_owned(), parse_hex_color("4BACC6").unwrap()), - ("accent6".to_owned(), parse_hex_color("F79646").unwrap()), - ("hlink".to_owned(), parse_hex_color("0000FF").unwrap()), - ("folHlink".to_owned(), parse_hex_color("800080").unwrap()), - ]); - add_theme_aliases(&mut colors); - colors -} - -fn add_theme_aliases(colors: &mut HashMap) { - for (alias, source) in [ - ("bg1", "lt1"), - ("tx1", "dk1"), - ("bg2", "lt2"), - ("tx2", "dk2"), - ] { - if let Some(color) = colors.get(source).copied() { - colors.insert(alias.to_owned(), color); - } - } -} - -fn render_pptx(presentation: &PptxDocument, options: &ConversionOptions) -> PdfDocument { - let mut document = PdfDocument::new(); - if presentation.slides.is_empty() { - let size = options.page_size.unwrap_or(crate::PageSize { - width: presentation.width, - height: presentation.height, - }); - document.add_page(size.width, size.height); - return document; - } - for slide in &presentation.slides { - render_slide(&mut document, slide, options); - } - document -} - -fn render_slide(document: &mut PdfDocument, slide: &PptxSlide, options: &ConversionOptions) { - let page_size = options.page_size.unwrap_or(crate::PageSize { - width: slide.width, - height: slide.height, - }); - let scale_x = page_size.width / slide.width; - let scale_y = page_size.height / slide.height; - let image_ids: HashMap = slide - .elements - .iter() - .enumerate() - .filter_map(|(index, element)| { - let PptxElement::Picture(picture) = element else { - return None; - }; - let image_id = match &picture.data { - PptxImageData::Jpeg { - data, - width, - height, - } => document.add_jpeg_image(data.clone(), *width, *height), - PptxImageData::Rgba { - data, - width, - height, - } => document.add_rgba_image(data.clone(), *width, *height), - PptxImageData::Svg { .. } => return None, - }; - Some((index, image_id)) - }) - .collect(); - let page = document.add_page(page_size.width, page_size.height); - if let Some(background) = slide.background { - page.add_rect(0.0, 0.0, page_size.width, page_size.height, background); - } - for (index, element) in slide.elements.iter().enumerate() { - match element { - PptxElement::Picture(picture) => { - let bounds = scale_rect(picture.bounds, scale_x, scale_y); - if let PptxImageData::Svg { data, crop } = &picture.data { - render_svg( - page, - data, - *crop, - bounds, - page_size.height, - slide.background, - ); - } else if let Some(image_id) = image_ids.get(&index) { - page.add_image( - *image_id, - bounds.x, - page_size.height - bounds.y - bounds.height, - bounds.width, - bounds.height, - ); - } - } - PptxElement::Line(line) => { - page.add_line_with_dash_pattern( - (line.x1 * scale_x, page_size.height - line.y1 * scale_y), - (line.x2 * scale_x, page_size.height - line.y2 * scale_y), - line.outline.color, - line.outline.width * scale_x.min(scale_y), - &line.outline.dash_pattern, - ); - } - PptxElement::Shape(shape) => { - render_shape(page, shape, page_size.height, scale_x, scale_y); - } - } - } -} - -fn render_svg( - page: &mut crate::pdf::PdfPage, - data: &[u8], - crop: PptxCrop, - bounds: PptxRect, - page_height: f32, - background: Option, -) { - let Ok(text) = std::str::from_utf8(data) else { - return; - }; - let Ok(document) = Document::parse(text) else { - return; - }; - let root = document.root_element(); - let Some(mut view_box) = read_svg_view_box(root) else { - return; - }; - view_box.x += view_box.width * crop.left; - view_box.y += view_box.height * crop.top; - view_box.width *= (1.0 - crop.left - crop.right).max(0.01); - view_box.height *= (1.0 - crop.top - crop.bottom).max(0.01); - if view_box.width <= 0.0 || view_box.height <= 0.0 { - return; - } - let scale_x = bounds.width / view_box.width; - let scale_y = bounds.height / view_box.height; - let pdf_bottom = page_height - bounds.y - bounds.height; - for path in root.descendants().filter(|node| is_element(*node, "path")) { - let Some(path_data) = path.attribute("d") else { - continue; - }; - let Some(fill) = svg_fill(path, background.unwrap_or(PdfColor::WHITE)) else { - continue; - }; - let commands = parse_svg_path(path_data, |x, y| { - ( - bounds.x + (x - view_box.x) * scale_x, - pdf_bottom + (view_box.height - (y - view_box.y)) * scale_y, - ) - }); - page.add_path(commands, fill); - } -} - -fn read_svg_view_box(root: Node<'_, '_>) -> Option { - if let Some(value) = root.attribute("viewBox") { - let values = parse_number_list(value); - if values.len() >= 4 { - return Some(PptxRect { - x: values[0], - y: values[1], - width: values[2], - height: values[3], - }); - } - } - Some(PptxRect { - x: 0.0, - y: 0.0, - width: parse_svg_length(root.attribute("width")?)?, - height: parse_svg_length(root.attribute("height")?)?, - }) -} - -fn parse_svg_length(value: &str) -> Option { - let end = value - .char_indices() - .find(|(_, character)| !character.is_ascii_digit() && !matches!(character, '.' | '-' | '+')) - .map(|(index, _)| index) - .unwrap_or(value.len()); - value[..end].parse().ok() -} - -fn svg_fill(path: Node<'_, '_>, background: PdfColor) -> Option { - let value = path.attribute("fill")?.trim(); - if value.eq_ignore_ascii_case("none") { - return None; - } - let color = if value.starts_with('#') { - let mut hex = value.trim_start_matches('#').to_owned(); - if hex.len() == 3 { - hex = hex - .chars() - .flat_map(|character| [character, character]) - .collect(); - } - parse_hex_color(&hex) - } else { - preset_color(value) - }?; - let opacity = path - .attribute("fill-opacity") - .and_then(|value| value.parse::().ok()) - .unwrap_or(1.0) - .clamp(0.0, 1.0); - Some(PdfColor::new( - color.r * opacity + background.r * (1.0 - opacity), - color.g * opacity + background.g * (1.0 - opacity), - color.b * opacity + background.b * (1.0 - opacity), - )) -} - -fn parse_svg_path(path_data: &str, map: impl Fn(f32, f32) -> (f32, f32)) -> Vec { - let tokens = tokenize_svg_path(path_data); - let mut commands = Vec::new(); - let mut index = 0; - let mut command = ' '; - let mut current = (0.0, 0.0); - let mut start = (0.0, 0.0); - let mut last_control = None; - while index < tokens.len() { - let iteration_start = index; - if let Some(value) = command_token(&tokens[index]) { - command = value; - index += 1; - } - if command == ' ' { - break; - } - let relative = command.is_ascii_lowercase(); - match command.to_ascii_uppercase() { - 'M' => { - let mut first = true; - while let Some((x, y)) = read_pair(&tokens, &mut index) { - current = if relative { - (current.0 + x, current.1 + y) - } else { - (x, y) - }; - let point = map(current.0, current.1); - if first { - commands.push(PdfPathCommand::MoveTo(point.0, point.1)); - start = current; - first = false; - } else { - commands.push(PdfPathCommand::LineTo(point.0, point.1)); - } - last_control = None; - } - } - 'L' => { - while let Some((x, y)) = read_pair(&tokens, &mut index) { - current = if relative { - (current.0 + x, current.1 + y) - } else { - (x, y) - }; - let point = map(current.0, current.1); - commands.push(PdfPathCommand::LineTo(point.0, point.1)); - last_control = None; - } - } - 'H' | 'V' => { - while let Some(value) = read_number(&tokens, &mut index) { - if command.eq_ignore_ascii_case(&'H') { - current.0 = if relative { current.0 + value } else { value }; - } else { - current.1 = if relative { current.1 + value } else { value }; - } - let point = map(current.0, current.1); - commands.push(PdfPathCommand::LineTo(point.0, point.1)); - last_control = None; - } - } - 'C' => { - while let (Some((mut x1, mut y1)), Some((mut x2, mut y2)), Some((mut x, mut y))) = ( - read_pair(&tokens, &mut index), - read_pair(&tokens, &mut index), - read_pair(&tokens, &mut index), - ) { - if relative { - x1 += current.0; - y1 += current.1; - x2 += current.0; - y2 += current.1; - x += current.0; - y += current.1; - } - let first = map(x1, y1); - let second = map(x2, y2); - let end = map(x, y); - commands.push(PdfPathCommand::CurveTo( - first.0, first.1, second.0, second.1, end.0, end.1, - )); - current = (x, y); - last_control = Some((x2, y2)); - } - } - 'S' => { - while let (Some((mut x2, mut y2)), Some((mut x, mut y))) = ( - read_pair(&tokens, &mut index), - read_pair(&tokens, &mut index), - ) { - let first_control = last_control - .map(|point| (current.0 * 2.0 - point.0, current.1 * 2.0 - point.1)) - .unwrap_or(current); - if relative { - x2 += current.0; - y2 += current.1; - x += current.0; - y += current.1; - } - let first = map(first_control.0, first_control.1); - let second = map(x2, y2); - let end = map(x, y); - commands.push(PdfPathCommand::CurveTo( - first.0, first.1, second.0, second.1, end.0, end.1, - )); - current = (x, y); - last_control = Some((x2, y2)); - } - } - 'Z' => { - commands.push(PdfPathCommand::Close); - current = start; - last_control = None; - } - _ => break, - } - if index == iteration_start { - break; - } - } - commands -} - -fn tokenize_svg_path(value: &str) -> Vec { - let mut tokens = Vec::new(); - let mut number = String::new(); - for character in value.chars() { - if matches!(character, 'e' | 'E') && !number.is_empty() && !number.ends_with(['e', 'E']) { - number.push(character); - } else if character.is_ascii_alphabetic() { - if !number.is_empty() { - tokens.push(std::mem::take(&mut number)); - } - tokens.push(character.to_string()); - } else if character == ',' || character.is_whitespace() { - if !number.is_empty() { - tokens.push(std::mem::take(&mut number)); - } - } else if matches!(character, '-' | '+') - && !number.is_empty() - && !number.ends_with('e') - && !number.ends_with('E') - { - tokens.push(std::mem::take(&mut number)); - number.push(character); - } else { - number.push(character); - } - } - if !number.is_empty() { - tokens.push(number); - } - tokens -} - -fn command_token(value: &str) -> Option { - let mut characters = value.chars(); - let character = characters.next()?; - (characters.next().is_none() && character.is_ascii_alphabetic()).then_some(character) -} - -fn read_number(tokens: &[String], index: &mut usize) -> Option { - if *index >= tokens.len() || command_token(&tokens[*index]).is_some() { - return None; - } - let value = tokens[*index].parse().ok()?; - *index += 1; - Some(value) -} - -fn read_pair(tokens: &[String], index: &mut usize) -> Option<(f32, f32)> { - let original = *index; - let first = read_number(tokens, index)?; - let Some(second) = read_number(tokens, index) else { - *index = original; - return None; - }; - Some((first, second)) -} - -fn parse_number_list(value: &str) -> Vec { - value - .split(|character: char| character == ',' || character.is_whitespace()) - .filter(|part| !part.is_empty()) - .filter_map(|part| part.parse().ok()) - .collect() -} - -fn render_shape( - page: &mut crate::pdf::PdfPage, - shape: &PptxShape, - page_height: f32, - scale_x: f32, - scale_y: f32, -) { - let bounds = scale_rect(shape.bounds, scale_x, scale_y); - let bottom = page_height - bounds.y - bounds.height; - let ellipse = matches!(shape.shape_type.as_str(), "ellipse" | "arc"); - if let Some(fill) = shape.fill { - if ellipse { - page.add_ellipse(bounds.x, bottom, bounds.width, bounds.height, fill); - } else { - page.add_rect(bounds.x, bottom, bounds.width, bounds.height, fill); - } - } - if !ellipse { - if let Some(outline) = &shape.outline { - let left = bounds.x; - let right = bounds.x + bounds.width; - let top = page_height - bounds.y; - let bottom = top - bounds.height; - for (start, end) in [ - ((left, top), (right, top)), - ((right, top), (right, bottom)), - ((right, bottom), (left, bottom)), - ((left, bottom), (left, top)), - ] { - page.add_line_with_dash_pattern( - start, - end, - outline.color, - outline.width * scale_x.min(scale_y), - &outline.dash_pattern, - ); - } - } - } - render_text(page, shape, bounds, page_height, scale_x.min(scale_y)); -} - -fn render_text( - page: &mut crate::pdf::PdfPage, - shape: &PptxShape, - bounds: PptxRect, - page_height: f32, - font_scale: f32, -) { - if shape.paragraphs.is_empty() { - return; - } - let text_body = shape.text_body; - let left = bounds.x + text_body.left_inset * font_scale; - let top = bounds.y + text_body.top_inset * font_scale; - let width = - (bounds.width - (text_body.left_inset + text_body.right_inset) * font_scale).max(1.0); - let available_height = - (bounds.height - (text_body.top_inset + text_body.bottom_inset) * font_scale).max(1.0); - let total_height: f32 = shape - .paragraphs - .iter() - .map(|paragraph| paragraph_height(paragraph, width, font_scale)) - .sum(); - let mut current_top = match text_body.anchor { - VerticalAnchor::Top => top, - VerticalAnchor::Middle => top + ((available_height - total_height) / 2.0).max(0.0), - VerticalAnchor::Bottom => top + (available_height - total_height).max(0.0), - }; - page.push_clip( - bounds.x, - page_height - bounds.y - bounds.height, - bounds.width, - bounds.height, - ); - for paragraph in &shape.paragraphs { - current_top += paragraph.space_before * font_scale; - let paragraph_left = - left + (paragraph.margin_left + paragraph.indent.min(0.0)).max(0.0) * font_scale; - let paragraph_width = (width - - (paragraph.margin_left + paragraph.indent.min(0.0)).max(0.0) * font_scale) - .max(1.0); - let lines = wrap_paragraph(paragraph, paragraph_width, font_scale); - for line in lines { - let line_width: f32 = line.iter().map(|segment| segment.width).sum(); - let line_height = line - .iter() - .map(|segment| segment.run.font_size * font_scale) - .fold(12.0, f32::max) - * paragraph.line_spacing; - let mut x = match paragraph.alignment { - TextAlignment::Left => paragraph_left, - TextAlignment::Center => { - paragraph_left + ((paragraph_width - line_width) / 2.0).max(0.0) - } - TextAlignment::Right => paragraph_left + (paragraph_width - line_width).max(0.0), - }; - for segment in line { - let font_size = segment.run.font_size * font_scale; - let baseline = page_height - current_top - font_size; - page.add_styled_text_with_font( - &segment.text, - x, - baseline, - font_size, - segment.run.color, - segment.run.bold, - segment.run.italic, - segment.run.font_name.as_deref(), - ); - if segment.run.underline && !segment.text.trim().is_empty() { - page.add_line( - x, - baseline - font_size * 0.08, - x + segment.width, - baseline - font_size * 0.08, - segment.run.color, - (font_size * 0.05).max(0.5), - ); - } - x += segment.width; - } - current_top += line_height; - } - if current_top > bounds.y + bounds.height { - break; - } - } - page.pop_clip(); -} - -#[derive(Debug)] -struct TextSegment<'a> { - text: String, - run: &'a PptxRun, - width: f32, -} - -fn wrap_paragraph<'a>( - paragraph: &'a PptxParagraph, - max_width: f32, - font_scale: f32, -) -> Vec>> { - let mut lines = Vec::new(); - let mut line = Vec::new(); - let mut line_width = 0.0; - for run in ¶graph.runs { - for token in split_text_tokens(&run.text) { - if token == "\n" { - lines.push(std::mem::take(&mut line)); - line_width = 0.0; - continue; - } - let font_size = run.font_size * font_scale; - let width = styled_text_width_with_font( - &token, - font_size, - run.bold, - run.italic, - run.font_name.as_deref(), - ); - if !line.is_empty() && line_width + width > max_width { - lines.push(std::mem::take(&mut line)); - line_width = 0.0; - } - line.push(TextSegment { - text: token, - run, - width, - }); - line_width += width; - } - } - if !line.is_empty() || lines.is_empty() { - lines.push(line); - } - lines -} - -fn paragraph_height(paragraph: &PptxParagraph, width: f32, font_scale: f32) -> f32 { - let lines = wrap_paragraph(paragraph, width, font_scale); - paragraph.space_before * font_scale - + lines - .iter() - .map(|line| { - line.iter() - .map(|segment| segment.run.font_size * font_scale) - .fold(12.0, f32::max) - * paragraph.line_spacing - }) - .sum::() -} - -fn split_text_tokens(text: &str) -> Vec { - let mut tokens = Vec::new(); - let mut current = String::new(); - let mut whitespace = false; - for character in text.replace('\t', " ").chars() { - if character == '\r' { - continue; - } - if character == '\n' { - if !current.is_empty() { - tokens.push(std::mem::take(&mut current)); - } - tokens.push("\n".to_owned()); - continue; - } - let is_whitespace = character.is_whitespace(); - if !current.is_empty() && is_whitespace != whitespace { - tokens.push(std::mem::take(&mut current)); - } - current.push(character); - whitespace = is_whitespace; - } - if !current.is_empty() { - tokens.push(current); - } - tokens -} - -fn scale_rect(rect: PptxRect, scale_x: f32, scale_y: f32) -> PptxRect { - PptxRect { - x: rect.x * scale_x, - y: rect.y * scale_y, - width: rect.width * scale_x, - height: rect.height * scale_y, - } -} - -fn read_relationships( - archive: &mut ZipArchive>, - part_path: &str, -) -> Result> { - let relationship_path = relationship_part_path(part_path); - let Some(bytes) = read_zip_bytes(archive, &relationship_path)? else { - return Ok(HashMap::new()); - }; - let text = String::from_utf8(bytes) - .map_err(|_| MiniPdfError::InvalidInput(format!("{relationship_path} is not UTF-8")))?; - let document = Document::parse(&text)?; - Ok(document - .descendants() - .filter(|node| is_element(*node, "Relationship")) - .filter_map(|node| { - Some(( - node.attribute("Id")?.to_owned(), - Relationship { - target: node.attribute("Target")?.to_owned(), - rel_type: node.attribute("Type").unwrap_or_default().to_owned(), - external: node - .attribute("TargetMode") - .is_some_and(|value| value.eq_ignore_ascii_case("External")), - relationship_path: relationship_path.clone(), - }, - )) - }) - .collect()) -} - -type RelatedXml = (String, String, HashMap); - -fn read_related_xml( - archive: &mut ZipArchive>, - source_path: &str, - relationships: &HashMap, - type_suffix: &str, -) -> Result> { - let Some(relationship) = relationships.values().find(|relationship| { - relationship.rel_type.ends_with(type_suffix) && !relationship.external - }) else { - return Ok(None); - }; - let path = resolve_part_target(source_path, &relationship.target); - let Some(bytes) = read_zip_bytes(archive, &path)? else { - return Ok(None); - }; - let xml = String::from_utf8(bytes) - .map_err(|_| MiniPdfError::InvalidInput(format!("{path} is not UTF-8")))?; - let part_relationships = read_relationships(archive, &path)?; - Ok(Some((path, xml, part_relationships))) -} - -fn read_zip_bytes(archive: &mut ZipArchive>, path: &str) -> Result>> { - let Ok(mut entry) = archive.by_name(path) else { - return Ok(None); - }; - let mut bytes = Vec::with_capacity(entry.size() as usize); - entry.read_to_end(&mut bytes)?; - Ok(Some(bytes)) -} - -fn relationship_part_path(part_path: &str) -> String { - match part_path.rsplit_once('/') { - Some((directory, file_name)) => format!("{directory}/_rels/{file_name}.rels"), - None => format!("_rels/{part_path}.rels"), - } -} - -fn relationship_source_path(relationship: &Relationship) -> String { - let Some((directory, file_name)) = relationship.relationship_path.split_once("/_rels/") else { - return relationship.relationship_path.clone(); - }; - format!("{directory}/{}", file_name.trim_end_matches(".rels")) -} - -fn resolve_part_target(source_path: &str, target: &str) -> String { - if target.starts_with('/') { - return target.trim_start_matches('/').to_owned(); - } - let directory = source_path - .rsplit_once('/') - .map(|(path, _)| path) - .unwrap_or_default(); - let mut normalized = Vec::new(); - let combined = format!("{directory}/{target}"); - for segment in combined.split('/') { - match segment { - "" | "." => {} - ".." => { - normalized.pop(); - } - value => normalized.push(value), - } - } - normalized.join("/") -} - -fn child<'a, 'input>(node: Node<'a, 'input>, local_name: &str) -> Option> { - node.children() - .find(|child_node| is_element(*child_node, local_name)) -} - -fn is_element(node: Node<'_, '_>, local_name: &str) -> bool { - node.is_element() && node.tag_name().name() == local_name -} - -fn attribute_by_local_name<'a, 'input>(node: Node<'a, 'input>, name: &str) -> Option<&'a str> { - node.attributes() - .find(|attribute| attribute.name() == name) - .map(|attribute| attribute.value()) -} - -fn integer_attribute(node: Option>, name: &str) -> Option { - node?.attribute(name)?.parse().ok() -} - -fn emu_attribute(node: Option>, name: &str) -> Option { - integer_attribute(node, name).map(|value| value as f32 / EMUS_PER_POINT) -} - -fn crop_attribute(node: Node<'_, '_>, name: &str) -> f32 { - node.attribute(name) - .and_then(|value| value.parse::().ok()) - .map(|value| (value / 100_000.0).clamp(0.0, 0.95)) - .unwrap_or(0.0) -} - -fn optional_bool_attribute(node: Option>, name: &str) -> Option { - node?.attribute(name).map(read_bool) -} - -fn read_bool(value: &str) -> bool { - value == "1" || value.eq_ignore_ascii_case("true") -} - -fn parse_hex_color(value: &str) -> Option { - let value = value.trim_start_matches('#'); - if value.len() != 6 { - return None; - } - Some(PdfColor::new( - u8::from_str_radix(&value[0..2], 16).ok()? as f32 / 255.0, - u8::from_str_radix(&value[2..4], 16).ok()? as f32 / 255.0, - u8::from_str_radix(&value[4..6], 16).ok()? as f32 / 255.0, - )) -} - -fn preset_color(value: &str) -> Option { - match value.to_ascii_lowercase().as_str() { - "black" => Some(PdfColor::BLACK), - "white" => Some(PdfColor::WHITE), - "red" => Some(PdfColor::new(1.0, 0.0, 0.0)), - "green" => Some(PdfColor::new(0.0, 0.5, 0.0)), - "blue" => Some(PdfColor::new(0.0, 0.0, 1.0)), - "yellow" => Some(PdfColor::new(1.0, 1.0, 0.0)), - _ => None, - } -} - -fn apply_luminance(color: PdfColor, node: Node<'_, '_>) -> PdfColor { - let modifier = child(node, "lumMod") - .and_then(|node| node.attribute("val")) - .and_then(|value| value.parse::().ok()) - .map(|value| value / 100_000.0) - .unwrap_or(1.0); - let offset = child(node, "lumOff") - .and_then(|node| node.attribute("val")) - .and_then(|value| value.parse::().ok()) - .map(|value| value / 100_000.0) - .unwrap_or(0.0); - if (modifier - 1.0).abs() < f32::EPSILON && offset.abs() < f32::EPSILON { - return color; - } - let (hue, saturation, luminance) = rgb_to_hsl(color); - hsl_to_rgb( - hue, - saturation, - (luminance * modifier + offset).clamp(0.0, 1.0), - ) -} - -fn rgb_to_hsl(color: PdfColor) -> (f32, f32, f32) { - let max = color.r.max(color.g).max(color.b); - let min = color.r.min(color.g).min(color.b); - let luminance = (max + min) / 2.0; - if (max - min).abs() < 0.000_01 { - return (0.0, 0.0, luminance); - } - let delta = max - min; - let saturation = if luminance > 0.5 { - delta / (2.0 - max - min) - } else { - delta / (max + min) - }; - let hue = if (max - color.r).abs() < 0.000_01 { - (color.g - color.b) / delta + if color.g < color.b { 6.0 } else { 0.0 } - } else if (max - color.g).abs() < 0.000_01 { - (color.b - color.r) / delta + 2.0 - } else { - (color.r - color.g) / delta + 4.0 - }; - (hue / 6.0, saturation, luminance) -} - -fn hsl_to_rgb(hue: f32, saturation: f32, luminance: f32) -> PdfColor { - if saturation <= 0.000_01 { - return PdfColor::new(luminance, luminance, luminance); - } - let upper = if luminance < 0.5 { - luminance * (1.0 + saturation) - } else { - luminance + saturation - luminance * saturation - }; - let lower = 2.0 * luminance - upper; - PdfColor::new( - hue_to_rgb(lower, upper, hue + 1.0 / 3.0), - hue_to_rgb(lower, upper, hue), - hue_to_rgb(lower, upper, hue - 1.0 / 3.0), - ) -} - -fn hue_to_rgb(lower: f32, upper: f32, mut hue: f32) -> f32 { - if hue < 0.0 { - hue += 1.0; - } - if hue > 1.0 { - hue -= 1.0; - } - if hue < 1.0 / 6.0 { - lower + (upper - lower) * 6.0 * hue - } else if hue < 0.5 { - upper - } else if hue < 2.0 / 3.0 { - lower + (upper - lower) * (2.0 / 3.0 - hue) * 6.0 - } else { - lower - } -} - -fn select_font_name(text: &str, properties: Option>) -> Option { - let properties = properties?; - let preferred = if contains_east_asian(text) { - child(properties, "ea") - } else if contains_complex_script(text) { - child(properties, "cs") - } else { - child(properties, "latin") - }; - preferred - .or_else(|| child(properties, "latin")) - .or_else(|| child(properties, "ea")) - .or_else(|| child(properties, "cs")) - .and_then(|node| node.attribute("typeface")) - .filter(|name| !name.starts_with('+')) - .map(str::to_owned) -} - -fn contains_east_asian(text: &str) -> bool { - text.chars().any(|character| { - matches!(character as u32, 0x3000..=0x30ff | 0x3400..=0x4dbf | 0x4e00..=0x9fff | 0xac00..=0xd7af | 0xf900..=0xfaff | 0xff00..=0xffef) - }) -} - -fn contains_complex_script(text: &str) -> bool { - text.chars().any( - |character| matches!(character as u32, 0x0590..=0x08ff | 0x0900..=0x0d7f | 0x0e00..=0x0eff), - ) -} - -fn natural_slide_number(path: &str) -> u32 { - path.rsplit_once("slide") - .and_then(|(_, suffix)| suffix.trim_end_matches(".xml").parse().ok()) - .unwrap_or(u32::MAX) -} - -fn jpeg_dimensions(data: &[u8]) -> Option<(u16, u16)> { - if data.len() < 4 || data[..2] != [0xff, 0xd8] { - return None; - } - let mut offset = 2; - while offset + 4 <= data.len() { - if data[offset] != 0xff { - offset += 1; - continue; - } - let marker = data[offset + 1]; - offset += 2; - if marker == 0xd9 || marker == 0xda { - break; - } - if offset + 2 > data.len() { - break; - } - let length = u16::from_be_bytes([data[offset], data[offset + 1]]) as usize; - if length < 2 || offset + length > data.len() { - break; - } - if matches!(marker, 0xc0..=0xc3 | 0xc5..=0xc7 | 0xc9..=0xcb | 0xcd..=0xcf) && length >= 7 { - return Some(( - u16::from_be_bytes([data[offset + 5], data[offset + 6]]), - u16::from_be_bytes([data[offset + 3], data[offset + 4]]), - )); - } - offset += length; - } - None -} - -#[cfg(test)] -mod tests { - use std::io::{Cursor, Write}; - - use zip::write::SimpleFileOptions; - - use super::{convert_pptx_bytes, read_pptx}; - use crate::{convert_bytes_to_pdf, detect_office_format, ConversionOptions, OfficeFormat}; - - #[test] - fn converts_text_shapes_and_custom_slide_size() { - let pptx = create_pptx(); - assert_eq!(detect_office_format(&pptx).unwrap(), OfficeFormat::Pptx); - let presentation = read_pptx(&pptx).expect("PPTX parses"); - assert_eq!(presentation.slides.len(), 1); - assert!((presentation.width - 720.0).abs() < 0.01); - assert!((presentation.height - 540.0).abs() < 0.01); - assert_eq!(presentation.slides[0].elements.len(), 2); - let super::PptxElement::Shape(shape) = &presentation.slides[0].elements[0] else { - panic!("first element is a shape"); - }; - assert_eq!(shape.paragraphs[0].runs[0].text, "Hello Rust PPTX"); - - let pdf = convert_pptx_bytes(&pptx, &ConversionOptions::default()).expect("PPTX converts"); - let text = String::from_utf8_lossy(&pdf); - assert!(pdf.starts_with(b"%PDF-1.4")); - assert!(pdf.ends_with(b"%%EOF\n")); - assert!(pdf.len() > 500); - assert!(text.contains("/MediaBox [0 0 720.00 540.00]")); - - let detected_pdf = convert_bytes_to_pdf(&pptx).expect("detected PPTX converts"); - assert!(detected_pdf.starts_with(b"%PDF-1.4")); - } - - #[test] - fn renders_office_svg_and_smartart_fallback() { - let pptx = create_svg_and_smartart_pptx(); - let presentation = read_pptx(&pptx).expect("PPTX parses"); - assert!(presentation.slides[0].elements.iter().any(|element| { - matches!( - element, - super::PptxElement::Picture(super::PptxPicture { - data: super::PptxImageData::Svg { .. }, - .. - }) - ) - })); - assert!(presentation.slides[0].elements.iter().any(|element| { - let super::PptxElement::Shape(shape) = element else { - return false; - }; - shape.paragraphs.iter().any(|paragraph| { - paragraph - .runs - .iter() - .any(|run| run.text.contains("SmartArt Text")) - }) - })); - - let pdf = convert_pptx_bytes(&pptx, &ConversionOptions::default()).expect("PPTX converts"); - assert!(pdf.starts_with(b"%PDF-1.4")); - assert!(pdf.len() > 700); - } - - #[test] - fn inherits_placeholder_bounds_and_text_layout() { - let pptx = create_placeholder_pptx(); - let presentation = read_pptx(&pptx).expect("PPTX parses"); - let shapes: Vec<_> = presentation.slides[0] - .elements - .iter() - .filter_map(|element| { - let super::PptxElement::Shape(shape) = element else { - return None; - }; - Some(shape) - }) - .collect(); - assert_eq!(shapes.len(), 2); - assert!((shapes[0].bounds.x - 72.0).abs() < 0.01); - assert!((shapes[0].bounds.width - 288.0).abs() < 0.01); - assert!(matches!( - shapes[0].paragraphs[0].alignment, - super::TextAlignment::Center - )); - assert!((shapes[0].paragraphs[0].runs[0].font_size - 24.0).abs() < 0.01); - assert!(shapes[1].paragraphs[1].runs[0].text.starts_with('\u{2022}')); - - let pdf = convert_pptx_bytes(&pptx, &ConversionOptions::default()).expect("PPTX converts"); - assert!(pdf.starts_with(b"%PDF-1.4")); - } - - #[test] - fn applies_master_color_map_aliases() { - let theme = super::default_theme_colors(); - let slide = roxmltree::Document::parse( - r#""#, - ) - .unwrap(); - let master = roxmltree::Document::parse( - r#""#, - ) - .unwrap(); - let mapped = super::apply_color_map(&theme, &slide, None, Some(&master)); - assert_eq!(mapped["bg1"], super::PdfColor::BLACK); - assert_eq!(mapped["tx1"], super::PdfColor::WHITE); - } - - #[test] - fn preserves_presentation_slide_order() { - let pptx = create_reordered_pptx(); - let presentation = read_pptx(&pptx).expect("PPTX parses"); - let slide_text = |index: usize| { - presentation.slides[index] - .elements - .iter() - .find_map(|element| { - let super::PptxElement::Shape(shape) = element else { - return None; - }; - shape - .paragraphs - .first()? - .runs - .first() - .map(|run| run.text.as_str()) - }) - .unwrap() - }; - assert_eq!(slide_text(0), "Second"); - assert_eq!(slide_text(1), "First"); - } - - #[test] - fn falls_back_when_slide_relationship_targets_are_missing() { - let pptx = create_broken_relationship_pptx(); - let presentation = read_pptx(&pptx).expect("PPTX parses"); - assert_eq!(presentation.slides.len(), 1); - let super::PptxElement::Shape(shape) = &presentation.slides[0].elements[0] else { - panic!("fallback slide element is a shape"); - }; - assert_eq!(shape.paragraphs[0].runs[0].text, "Recovered"); - } - - #[test] - fn skips_pictures_with_non_positive_bounds() { - let pptx = create_invalid_picture_bounds_pptx(); - let presentation = read_pptx(&pptx).expect("PPTX parses"); - assert!(presentation.slides[0] - .elements - .iter() - .all(|element| !matches!(element, super::PptxElement::Picture(_)))); - } - - #[test] - fn parses_svg_path_scientific_notation_without_stalling() { - let commands = super::parse_svg_path("M1e-3 2E+2 L3.5e1 4e0 Z", |x, y| (x, y)); - assert_eq!(commands.len(), 3); - assert!( - matches!(commands[0], super::PdfPathCommand::MoveTo(x, y) if (x - 0.001).abs() < f32::EPSILON && (y - 200.0).abs() < f32::EPSILON) - ); - assert!( - matches!(commands[1], super::PdfPathCommand::LineTo(x, y) if (x - 35.0).abs() < f32::EPSILON && (y - 4.0).abs() < f32::EPSILON) - ); - assert!(matches!(commands[2], super::PdfPathCommand::Close)); - } - - fn create_pptx() -> Vec { - let mut output = Cursor::new(Vec::new()); - { - let mut archive = zip::ZipWriter::new(&mut output); - let options = SimpleFileOptions::default(); - write_entry( - &mut archive, - options, - "ppt/presentation.xml", - r#""#, - ); - write_entry( - &mut archive, - options, - "ppt/_rels/presentation.xml.rels", - r#""#, - ); - write_entry( - &mut archive, - options, - "ppt/slides/slide1.xml", - r#"Hello Rust PPTX"#, - ); - archive.finish().expect("finish PPTX ZIP"); - } - output.into_inner() - } - - fn create_svg_and_smartart_pptx() -> Vec { - let mut output = Cursor::new(Vec::new()); - { - let mut archive = zip::ZipWriter::new(&mut output); - let options = SimpleFileOptions::default(); - write_entry( - &mut archive, - options, - "ppt/presentation.xml", - r#""#, - ); - write_entry( - &mut archive, - options, - "ppt/_rels/presentation.xml.rels", - r#""#, - ); - write_entry( - &mut archive, - options, - "ppt/slides/slide1.xml", - r#""#, - ); - write_entry( - &mut archive, - options, - "ppt/slides/_rels/slide1.xml.rels", - r#""#, - ); - write_entry( - &mut archive, - options, - "ppt/media/image1.svg", - r##""##, - ); - write_entry( - &mut archive, - options, - "ppt/diagrams/drawing1.xml", - r#"SmartArt Text"#, - ); - archive.finish().expect("finish PPTX ZIP"); - } - output.into_inner() - } - - fn create_placeholder_pptx() -> Vec { - let mut output = Cursor::new(Vec::new()); - { - let mut archive = zip::ZipWriter::new(&mut output); - let options = SimpleFileOptions::default(); - write_entry( - &mut archive, - options, - "ppt/presentation.xml", - r#""#, - ); - write_entry( - &mut archive, - options, - "ppt/_rels/presentation.xml.rels", - r#""#, - ); - write_entry( - &mut archive, - options, - "ppt/slides/slide1.xml", - r#"Centered TitleHeadingIndented bullet"#, - ); - write_entry( - &mut archive, - options, - "ppt/slides/_rels/slide1.xml.rels", - r#""#, - ); - write_entry( - &mut archive, - options, - "ppt/slideLayouts/slideLayout1.xml", - r#""#, - ); - archive.finish().expect("finish PPTX ZIP"); - } - output.into_inner() - } - - fn create_reordered_pptx() -> Vec { - let mut output = Cursor::new(Vec::new()); - { - let mut archive = zip::ZipWriter::new(&mut output); - let options = SimpleFileOptions::default(); - write_entry( - &mut archive, - options, - "ppt/presentation.xml", - r#""#, - ); - write_entry( - &mut archive, - options, - "ppt/_rels/presentation.xml.rels", - r#""#, - ); - for (index, text) in [(1, "First"), (2, "Second")] { - write_entry( - &mut archive, - options, - &format!("ppt/slides/slide{index}.xml"), - &format!( - r#"{text}"# - ), - ); - } - archive.finish().expect("finish PPTX ZIP"); - } - output.into_inner() - } - - fn create_broken_relationship_pptx() -> Vec { - let mut output = Cursor::new(Vec::new()); - { - let mut archive = zip::ZipWriter::new(&mut output); - let options = SimpleFileOptions::default(); - write_entry( - &mut archive, - options, - "ppt/presentation.xml", - r#""#, - ); - write_entry( - &mut archive, - options, - "ppt/_rels/presentation.xml.rels", - r#""#, - ); - write_entry( - &mut archive, - options, - "ppt/slides/slide1.xml", - r#"Recovered"#, - ); - archive.finish().expect("finish PPTX ZIP"); - } - output.into_inner() - } - - fn create_invalid_picture_bounds_pptx() -> Vec { - let mut output = Cursor::new(Vec::new()); - { - let mut archive = zip::ZipWriter::new(&mut output); - let options = SimpleFileOptions::default(); - write_entry( - &mut archive, - options, - "ppt/presentation.xml", - r#""#, - ); - write_entry( - &mut archive, - options, - "ppt/_rels/presentation.xml.rels", - r#""#, - ); - write_entry( - &mut archive, - options, - "ppt/slides/slide1.xml", - r#""#, - ); - write_entry( - &mut archive, - options, - "ppt/slides/_rels/slide1.xml.rels", - r#""#, - ); - archive - .start_file("ppt/media/image1.jpg", options) - .expect("start image entry"); - archive - .write_all(&[ - 0xff, 0xd8, 0xff, 0xc0, 0x00, 0x07, 0x08, 0x00, 0x01, 0x00, 0x01, - ]) - .expect("write image entry"); - archive.finish().expect("finish PPTX ZIP"); - } - output.into_inner() - } - - fn write_entry( - archive: &mut zip::ZipWriter<&mut Cursor>>, - options: SimpleFileOptions, - path: &str, - content: &str, - ) { - archive.start_file(path, options).expect("start ZIP entry"); - archive - .write_all(content.as_bytes()) - .expect("write ZIP entry"); - } -} diff --git a/minipdf-rs/crates/minipdf/src/xlsx.rs b/minipdf-rs/crates/minipdf/src/xlsx.rs deleted file mode 100644 index 323e508d..00000000 --- a/minipdf-rs/crates/minipdf/src/xlsx.rs +++ /dev/null @@ -1,6642 +0,0 @@ -use std::collections::HashMap; -use std::io::{Cursor, Read}; - -use unicode_bidi::{bidi_class, BidiClass}; -use zip::ZipArchive; - -use crate::pdf::{ - helvetica_glyph_width, styled_text_width_with_font, PdfColor, PdfDocument, PdfTextStyle, -}; -use crate::{read_zip_text, ConversionOptions, PageSize, Result}; - -const MARGIN_X: f32 = 54.0; -const MARGIN_TOP: f32 = 70.55; -const MARGIN_BOTTOM: f32 = 54.0; -const CELL_FONT_SIZE: f32 = 11.0; -const CELL_BORDER_WIDTH: f32 = 0.96; -const PRINT_TITLE_HORIZONTAL_SCALE: f32 = 0.9957; -const PRINT_TITLE_HORIZONTAL_OFFSET: f32 = 0.4; -const EXPLICIT_PRINT_TITLE_HORIZONTAL_SCALE: f32 = 0.9797; -const EXPLICIT_PRINT_TITLE_LEFT_OFFSET: f32 = 4.32; -const FIT_TO_PAGE_HORIZONTAL_SCALE: f32 = 1.0048; -const FIT_TO_PAGE_HORIZONTAL_OFFSET: f32 = 0.5; -const PRINT_TITLE_VERTICAL_SCALE: f32 = 0.98; -const FIT_TO_PAGE_VERTICAL_SCALE: f32 = 1.0104; -const FIT_TO_WIDTH_ONLY_VERTICAL_SCALE: f32 = 0.972; -const PRINT_TITLE_WIDTH_ONLY_VERTICAL_SCALE: f32 = 1.0233; -const FIT_TO_PAGE_TOP_OFFSET: f32 = 0.96; -const O365_PRINTER_FALLBACK_VERTICAL_SCALE: f32 = 0.946_666_7; -const O365_PRINTER_FALLBACK_TOP_MARGIN: f32 = 57.0; -const O365_PRINTER_FALLBACK_FONT_SCALE: f32 = 0.96; -const O365_PRINTER_FALLBACK_HORIZONTAL_SCALE: f32 = 1.0046; -const O365_PRINTER_FALLBACK_LEFT_OFFSET: f32 = 0.48; -const O365_PRINTER_FALLBACK_BORDER_SCALE: f32 = 1.8; -const CENTERED_VML_HORIZONTAL_SCALE: f32 = 0.9754; -const CENTERED_VML_VERTICAL_SCALE: f32 = 1.005; -const CENTERED_VML_IMAGE_HORIZONTAL_SCALE: f32 = 1.04; -const CENTERED_VML_IMAGE_VERTICAL_SCALE: f32 = 1.017; -const CENTERED_VML_IMAGE_VERTICAL_OFFSET: f32 = 4.8; -const SVG_FALLBACK_HORIZONTAL_SCALE: f32 = 0.972; -const GROUP_DRAWING_TOP_OFFSET: f32 = 0.96; -const CALIBRI_FITTING_SCALE: f32 = 0.85; -const ROW_HEIGHT: f32 = 15.0; -const COL_WIDTH: f32 = 47.4; - -#[derive(Debug, Clone, Default)] -struct CellData { - text: String, - is_numeric: bool, - style: CellStyle, -} - -#[derive(Debug, Clone)] -struct SheetData { - rows: Vec, - images: Vec, - column_widths: Vec, - merges: Vec, - row_breaks: Vec, - default_row_height: f32, - print_title_rows: Option<(usize, usize)>, - page_setup: SheetPageSetup, - footer: Option, -} - -#[derive(Debug, Clone)] -struct SheetFooter { - format: String, - margin: f32, -} - -#[derive(Debug, Clone, Copy)] -struct SheetPageSetup { - page_size: PageSize, - page_size_from_printer: bool, - margin_left: f32, - margin_right: f32, - margin_top: f32, - margin_bottom: f32, - print_scale: f32, - fit_to_width: bool, - fit_to_height: bool, - horizontal_centered: bool, - vertical_centered: bool, - legacy_vml_drawing: bool, - o365_printer_fallback: bool, -} - -impl Default for SheetPageSetup { - fn default() -> Self { - Self { - page_size: PageSize::A4, - page_size_from_printer: false, - margin_left: MARGIN_X, - margin_right: MARGIN_X, - margin_top: MARGIN_TOP, - margin_bottom: MARGIN_BOTTOM, - print_scale: 1.0, - fit_to_width: false, - fit_to_height: false, - horizontal_centered: false, - vertical_centered: false, - legacy_vml_drawing: false, - o365_printer_fallback: false, - } - } -} - -#[derive(Debug, Clone)] -struct RowData { - index: usize, - height: f32, - cells: Vec, -} - -#[derive(Debug, Clone, Copy)] -struct CellStyle { - bold: bool, - italic: bool, - strike: bool, - font_size: f32, - font_color: PdfColor, - fill_color: Option, - borders: CellBorders, - number_format: NumberFormat, - horizontal_alignment: HorizontalAlignment, - vertical_alignment: VerticalAlignment, - indent: f32, - wrap_text: bool, - stacked_text: bool, - preferred_font: Option<&'static str>, -} - -#[derive(Debug, Clone, Copy, Default)] -struct CellBorders { - left: Option, - right: Option, - top: Option, - bottom: Option, - left_width: f32, - right_width: f32, - top_width: f32, - bottom_width: f32, - left_dotted: bool, - right_dotted: bool, - top_dotted: bool, - bottom_dotted: bool, -} - -impl CellBorders { - fn any(self) -> bool { - self.left.is_some() || self.right.is_some() || self.top.is_some() || self.bottom.is_some() - } -} - -#[derive(Debug, Clone, Copy, Default)] -struct TableBorders { - edges: CellBorders, - vertical: Option<(PdfColor, f32)>, - horizontal: Option<(PdfColor, f32)>, -} - -#[derive(Debug, Clone, Copy, Default)] -enum NumberFormat { - #[default] - General, - DateMonthDayYear, - DateDayShortMonthYear, - DateYearMonthDay, - PercentageZeroDecimals, - PercentageTwoDecimals, - ThousandsZeroDecimals, - ThousandsTwoDecimals, - DollarTwoDecimals, - DollarAccounting, -} - -#[derive(Debug, Clone, Copy, Default, PartialEq)] -enum HorizontalAlignment { - #[default] - General, - Left, - Center, - Right, -} - -#[derive(Debug, Clone, Copy, Default, PartialEq)] -enum VerticalAlignment { - Top, - Center, - #[default] - Bottom, -} - -impl Default for CellStyle { - fn default() -> Self { - Self { - bold: false, - italic: false, - strike: false, - font_size: CELL_FONT_SIZE, - font_color: PdfColor::BLACK, - fill_color: None, - borders: CellBorders::default(), - number_format: NumberFormat::General, - horizontal_alignment: HorizontalAlignment::General, - vertical_alignment: VerticalAlignment::Bottom, - indent: 0.0, - wrap_text: false, - stacked_text: false, - preferred_font: None, - } - } -} - -#[derive(Debug, Clone, Copy)] -struct FontStyle { - bold: bool, - italic: bool, - size: f32, - color: PdfColor, - preferred_font: Option<&'static str>, -} - -#[derive(Debug, Clone, Copy, Default)] -struct DifferentialFontStyle { - bold: Option, - italic: Option, - strike: Option, - color: Option, -} - -impl DifferentialFontStyle { - fn any(self) -> bool { - self.bold.is_some() - || self.italic.is_some() - || self.strike.is_some() - || self.color.is_some() - } -} - -impl Default for FontStyle { - fn default() -> Self { - Self { - bold: false, - italic: false, - size: CELL_FONT_SIZE, - color: PdfColor::BLACK, - preferred_font: None, - } - } -} - -#[derive(Debug, Default)] -struct XlsxStyles { - cells: Vec, - differential_fonts: Vec, - differential_fills: Vec>, - max_digit_width: f32, - table_base_fills: HashMap, - table_first_row_stripes: HashMap, - table_header_fills: HashMap, - table_total_fills: HashMap, - table_whole_fonts: HashMap, - table_header_fonts: HashMap, - table_total_fonts: HashMap, - table_whole_borders: HashMap, - table_header_borders: HashMap, - table_total_borders: HashMap, -} - -fn parse_number_format( - format_id: Option<&str>, - custom_formats: &HashMap, -) -> NumberFormat { - match format_id { - Some("14") => NumberFormat::DateMonthDayYear, - Some("9") => NumberFormat::PercentageZeroDecimals, - Some("10") => NumberFormat::PercentageTwoDecimals, - Some("3") => NumberFormat::ThousandsZeroDecimals, - Some("4") => NumberFormat::ThousandsTwoDecimals, - Some("44") => NumberFormat::DollarAccounting, - Some(id) => id - .parse::() - .ok() - .and_then(|id| custom_formats.get(&id)) - .map(|code| { - let normalized = code.to_ascii_lowercase(); - let unescaped = normalized.replace('\\', ""); - if normalized.contains('$') && normalized.contains("0.00") { - if normalized.contains('*') { - NumberFormat::DollarAccounting - } else { - NumberFormat::DollarTwoDecimals - } - } else if unescaped.contains("dd-mmm-yyyy") { - NumberFormat::DateDayShortMonthYear - } else if unescaped.contains("yyyy-mm-dd") { - NumberFormat::DateYearMonthDay - } else if unescaped.contains("#,##0") && !unescaped.contains('.') { - NumberFormat::ThousandsZeroDecimals - } else { - NumberFormat::General - } - }) - .unwrap_or(NumberFormat::General), - None => NumberFormat::General, - } -} - -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -struct MergeRange { - start_col: usize, - end_col: usize, - start_row: usize, - end_row: usize, -} - -#[derive(Debug, Clone)] -struct SheetImage { - data: SheetImageData, - pixel_width: u16, - pixel_height: u16, - legacy_vml: bool, - col: usize, - row: usize, - col_offset: f32, - row_offset: f32, - width: f32, - height: f32, - foreground: bool, -} - -#[derive(Debug, Clone)] -enum SheetImageData { - Jpeg(Vec), - Rgba(Vec), -} - -pub(crate) fn convert_xlsx_bytes(input: &[u8], options: &ConversionOptions) -> Result> { - let sheets = read_xlsx_sheets(input)?; - let mut doc = PdfDocument::new(); - render_xlsx(&mut doc, &sheets, options.page_size); - Ok(doc.to_bytes()) -} - -fn read_xlsx_sheets(input: &[u8]) -> Result> { - let cursor = Cursor::new(input); - let mut archive = ZipArchive::new(cursor)?; - let shared_strings = read_shared_strings(&mut archive)?; - let styles = read_styles(&mut archive)?; - let sheet_paths = read_sheet_paths(&mut archive)?; - let print_title_rows = read_print_title_rows(&mut archive)?; - let print_areas = read_print_areas(&mut archive)?; - let mut sheets = Vec::new(); - - for (name, path) in sheet_paths { - let Some(sheet_xml) = read_zip_text(&mut archive, &path)? else { - continue; - }; - let mut rows = read_sheet_rows(&sheet_xml, &shared_strings, &styles)?; - apply_sheet_table_styles(&mut archive, &path, &sheet_xml, &mut rows, &styles)?; - apply_sheet_conditional_formats(&sheet_xml, &mut rows, &styles)?; - let mut column_widths = read_column_widths_with_mdw(&sheet_xml, styles.max_digit_width)?; - let default_row_height = read_default_row_height(&sheet_xml)?; - let mut images = read_sheet_images( - &mut archive, - &path, - &sheet_xml, - &column_widths, - &rows, - default_row_height, - )?; - let mut merges = read_merge_ranges(&sheet_xml)?; - let mut row_breaks = read_row_breaks(&sheet_xml)?; - let mut sheet_print_title_rows = print_title_rows.get(&name).copied(); - if let Some(print_area) = print_areas.get(&name).copied() { - apply_print_area( - &mut rows, - &mut images, - &mut column_widths, - &mut merges, - &mut row_breaks, - &mut sheet_print_title_rows, - print_area, - ); - } - trim_trailing_empty_rows(&mut rows, &images); - let mut page_setup = read_page_setup(&sheet_xml)?; - if let Some(page_size) = read_printer_page_size(&mut archive, &path, &sheet_xml)? { - if should_use_printer_page_size(page_setup, sheet_print_title_rows.is_some()) { - page_setup.page_size = page_size; - page_setup.page_size_from_printer = true; - } else if should_calibrate_ignored_printer_page_size( - page_setup, - page_size, - sheet_print_title_rows.is_some(), - ) { - page_setup.o365_printer_fallback = true; - } - } - sheets.push(SheetData { - rows, - images, - column_widths, - merges, - row_breaks, - default_row_height, - print_title_rows: sheet_print_title_rows, - page_setup, - footer: read_sheet_footer(&sheet_xml)?, - }); - } - - if sheets.is_empty() { - if let Some(sheet_xml) = read_zip_text(&mut archive, "xl/worksheets/sheet1.xml")? { - let mut rows = read_sheet_rows(&sheet_xml, &shared_strings, &styles)?; - apply_sheet_table_styles( - &mut archive, - "xl/worksheets/sheet1.xml", - &sheet_xml, - &mut rows, - &styles, - )?; - apply_sheet_conditional_formats(&sheet_xml, &mut rows, &styles)?; - let column_widths = read_column_widths_with_mdw(&sheet_xml, styles.max_digit_width)?; - let default_row_height = read_default_row_height(&sheet_xml)?; - let images = read_sheet_images( - &mut archive, - "xl/worksheets/sheet1.xml", - &sheet_xml, - &column_widths, - &rows, - default_row_height, - )?; - trim_trailing_empty_rows(&mut rows, &images); - let mut page_setup = read_page_setup(&sheet_xml)?; - if let Some(page_size) = - read_printer_page_size(&mut archive, "xl/worksheets/sheet1.xml", &sheet_xml)? - { - if should_use_printer_page_size(page_setup, false) { - page_setup.page_size = page_size; - page_setup.page_size_from_printer = true; - } else if should_calibrate_ignored_printer_page_size(page_setup, page_size, false) { - page_setup.o365_printer_fallback = true; - } - } - sheets.push(SheetData { - rows, - images, - column_widths, - merges: read_merge_ranges(&sheet_xml)?, - row_breaks: read_row_breaks(&sheet_xml)?, - default_row_height, - print_title_rows: None, - page_setup, - footer: read_sheet_footer(&sheet_xml)?, - }); - } - } - - if sheets.is_empty() { - sheets.push(SheetData { - rows: vec![RowData { - index: 0, - height: ROW_HEIGHT, - cells: vec![CellData { - text: "Empty XLSX workbook".to_owned(), - is_numeric: false, - style: CellStyle::default(), - }], - }], - images: Vec::new(), - column_widths: Vec::new(), - merges: Vec::new(), - row_breaks: Vec::new(), - default_row_height: ROW_HEIGHT, - print_title_rows: None, - page_setup: SheetPageSetup::default(), - footer: None, - }); - } - - Ok(sheets) -} - -fn read_default_row_height(sheet_xml: &str) -> Result { - let document = roxmltree::Document::parse(sheet_xml)?; - Ok(document - .descendants() - .find(|node| node.has_tag_name("sheetFormatPr")) - .and_then(|node| node.attribute("defaultRowHeight")) - .and_then(|value| value.parse::().ok()) - .filter(|value| *value > 0.0) - .unwrap_or(ROW_HEIGHT)) -} - -fn read_print_title_rows( - archive: &mut ZipArchive, -) -> Result> { - let Some(workbook_xml) = read_zip_text(archive, "xl/workbook.xml")? else { - return Ok(HashMap::new()); - }; - let document = roxmltree::Document::parse(&workbook_xml)?; - let mut titles = HashMap::new(); - for name in document.descendants().filter(|node| { - node.has_tag_name("definedName") && node.attribute("name") == Some("_xlnm.Print_Titles") - }) { - let Some((sheet_name, range)) = name.text().and_then(|value| value.split_once('!')) else { - continue; - }; - let Some((start, end)) = range.split(',').find_map(|part| { - let (start, end) = part.split_once(':')?; - let start = start.trim().trim_start_matches('$').parse::().ok()?; - let end = end.trim().trim_start_matches('$').parse::().ok()?; - Some((start.checked_sub(1)?, end.checked_sub(1)?)) - }) else { - continue; - }; - titles.insert( - sheet_name.trim_matches('\'').replace("''", "'"), - (start, end), - ); - } - Ok(titles) -} - -fn read_print_areas( - archive: &mut ZipArchive, -) -> Result> { - let Some(workbook_xml) = read_zip_text(archive, "xl/workbook.xml")? else { - return Ok(HashMap::new()); - }; - let document = roxmltree::Document::parse(&workbook_xml)?; - Ok(document - .descendants() - .filter(|node| { - node.has_tag_name("definedName") && node.attribute("name") == Some("_xlnm.Print_Area") - }) - .filter_map(|node| node.text().and_then(parse_print_area)) - .collect()) -} - -fn parse_print_area(value: &str) -> Option<(String, MergeRange)> { - let (sheet_name, ranges) = value.rsplit_once('!')?; - let (start, end) = ranges.split(',').next()?.split_once(':')?; - let (start_col, start_row) = cell_position(start)?; - let (end_col, end_row) = cell_position(end)?; - Some(( - sheet_name.trim_matches('\'').replace("''", "'"), - MergeRange { - start_col, - end_col, - start_row, - end_row, - }, - )) -} - -#[allow(clippy::too_many_arguments)] -fn apply_print_area( - rows: &mut Vec, - images: &mut Vec, - column_widths: &mut Vec, - merges: &mut Vec, - row_breaks: &mut Vec, - print_title_rows: &mut Option<(usize, usize)>, - print_area: MergeRange, -) { - rows.retain_mut(|row| { - if row.index < print_area.start_row || row.index > print_area.end_row { - return false; - } - row.index -= print_area.start_row; - row.cells = row - .cells - .get(print_area.start_col..=print_area.end_col.min(row.cells.len().saturating_sub(1))) - .unwrap_or_default() - .to_vec(); - true - }); - *column_widths = column_widths - .get( - print_area.start_col - ..=print_area - .end_col - .min(column_widths.len().saturating_sub(1)), - ) - .unwrap_or_default() - .to_vec(); - images.retain_mut(|image| { - if image.col < print_area.start_col - || image.col > print_area.end_col - || image.row < print_area.start_row - || image.row > print_area.end_row - { - return false; - } - image.col -= print_area.start_col; - image.row -= print_area.start_row; - true - }); - merges.retain_mut(|merge| { - if merge.end_col < print_area.start_col - || merge.start_col > print_area.end_col - || merge.end_row < print_area.start_row - || merge.start_row > print_area.end_row - { - return false; - } - merge.start_col = merge.start_col.max(print_area.start_col) - print_area.start_col; - merge.end_col = merge.end_col.min(print_area.end_col) - print_area.start_col; - merge.start_row = merge.start_row.max(print_area.start_row) - print_area.start_row; - merge.end_row = merge.end_row.min(print_area.end_row) - print_area.start_row; - true - }); - row_breaks.retain_mut(|row| { - if *row <= print_area.start_row || *row > print_area.end_row { - return false; - } - *row -= print_area.start_row; - true - }); - *print_title_rows = print_title_rows.and_then(|(start, end)| { - let start = start.max(print_area.start_row); - let end = end.min(print_area.end_row); - (start <= end).then_some((start - print_area.start_row, end - print_area.start_row)) - }); -} - -fn read_page_setup(sheet_xml: &str) -> Result { - let document = roxmltree::Document::parse(sheet_xml)?; - let page_setup = document - .descendants() - .find(|node| node.is_element() && node.tag_name().name() == "pageSetup"); - let mut page_size = match page_setup.and_then(|node| node.attribute("paperSize")) { - Some("1") => PageSize::LETTER, - Some("9") | None => PageSize::A4, - Some(_) => PageSize::A4, - }; - if page_setup.and_then(|node| node.attribute("orientation")) == Some("landscape") { - std::mem::swap(&mut page_size.width, &mut page_size.height); - } - let page_margins = document - .descendants() - .find(|node| node.is_element() && node.tag_name().name() == "pageMargins"); - let margin = |name: &str, fallback: f32| { - page_margins - .and_then(|node| node.attribute(name)) - .and_then(|value| value.parse::().ok()) - .filter(|value| *value >= 0.0) - .map(|inches| inches * 72.0) - .unwrap_or(fallback) - }; - let print_scale = page_setup - .and_then(|node| node.attribute("scale")) - .and_then(|value| value.parse::().ok()) - .filter(|value| *value > 0.0) - .map(|percent| percent / 100.0) - .unwrap_or(1.0); - let fit_to_page = document - .descendants() - .find(|node| node.is_element() && node.tag_name().name() == "pageSetUpPr") - .and_then(|node| node.attribute("fitToPage")) - == Some("1"); - let fit_to_width = page_setup - .and_then(|node| node.attribute("fitToWidth")) - .and_then(|value| value.parse::().ok()) - .unwrap_or(1); - let fit_to_height = page_setup - .and_then(|node| node.attribute("fitToHeight")) - .and_then(|value| value.parse::().ok()) - .unwrap_or(1); - let horizontal_centered = document - .descendants() - .find(|node| node.is_element() && node.tag_name().name() == "printOptions") - .and_then(|node| node.attribute("horizontalCentered")) - .is_some_and(|value| matches!(value, "1" | "true")); - let vertical_centered = document - .descendants() - .find(|node| node.is_element() && node.tag_name().name() == "printOptions") - .and_then(|node| node.attribute("verticalCentered")) - .is_some_and(|value| matches!(value, "1" | "true")); - let legacy_vml_drawing = document - .descendants() - .any(|node| node.has_tag_name("legacyDrawing")); - - let margin_top = margin("top", MARGIN_TOP); - Ok(SheetPageSetup { - page_size, - page_size_from_printer: false, - margin_left: margin("left", MARGIN_X), - margin_right: margin("right", MARGIN_X), - margin_top: if fit_to_page { - margin_top.max(13.0) - } else { - margin_top - }, - margin_bottom: margin("bottom", MARGIN_BOTTOM), - print_scale, - fit_to_width: fit_to_page && fit_to_width > 0, - fit_to_height: fit_to_page && fit_to_height > 0, - horizontal_centered, - vertical_centered, - legacy_vml_drawing, - o365_printer_fallback: false, - }) -} - -fn read_sheet_footer(sheet_xml: &str) -> Result> { - let document = roxmltree::Document::parse(sheet_xml)?; - let format = document - .descendants() - .find(|node| node.has_tag_name("oddFooter")) - .and_then(|node| node.text()) - .filter(|value| !value.is_empty()) - .map(str::to_owned); - let Some(format) = format else { - return Ok(None); - }; - let margin = document - .descendants() - .find(|node| node.has_tag_name("pageMargins")) - .and_then(|node| node.attribute("footer")) - .and_then(|value| value.parse::().ok()) - .filter(|value| *value >= 0.0) - .map(|inches| inches * 72.0) - .unwrap_or(18.0); - Ok(Some(SheetFooter { format, margin })) -} - -fn read_printer_page_size( - archive: &mut ZipArchive, - sheet_path: &str, - sheet_xml: &str, -) -> Result> { - let sheet = roxmltree::Document::parse(sheet_xml)?; - let Some(page_setup) = sheet - .descendants() - .find(|node| node.has_tag_name("pageSetup")) - else { - return Ok(None); - }; - if page_setup.attribute("paperSize").is_some() { - return Ok(None); - } - let Some(settings_id) = relationship_id(page_setup) else { - return Ok(None); - }; - let relationships = read_part_relationships(archive, sheet_path)?; - let Some(target) = relationships.get(&settings_id) else { - return Ok(None); - }; - let settings_path = resolve_part_target(sheet_path, target); - let Some(data) = read_zip_bytes(archive, &settings_path)? else { - return Ok(None); - }; - Ok(parse_windows_devmode_page_size(&data)) -} - -fn should_use_printer_page_size(page_setup: SheetPageSetup, has_print_title_rows: bool) -> bool { - page_setup.fit_to_height || has_print_title_rows -} - -fn should_calibrate_ignored_printer_page_size( - page_setup: SheetPageSetup, - printer_page_size: PageSize, - has_print_title_rows: bool, -) -> bool { - !page_setup.fit_to_width - && !should_use_printer_page_size(page_setup, has_print_title_rows) - && ((page_setup.page_size.width - printer_page_size.width).abs() > 0.1 - || (page_setup.page_size.height - printer_page_size.height).abs() > 0.1) -} - -fn parse_windows_devmode_page_size(data: &[u8]) -> Option { - let read_u16 = |offset: usize| { - Some(u16::from_le_bytes([ - *data.get(offset)?, - *data.get(offset + 1)?, - ])) - }; - let size = read_u16(68)? as usize; - if size < 84 || data.len() < size { - return None; - } - let orientation = read_u16(76)?; - let paper_size = read_u16(78)?; - let paper_length = read_u16(80)?; - let paper_width = read_u16(82)?; - let mut page_size = match paper_size { - 1 => PageSize::LETTER, - 9 => PageSize::A4, - _ if paper_width > 0 && paper_length > 0 => PageSize { - width: paper_width as f32 * 72.0 / 254.0, - height: paper_length as f32 * 72.0 / 254.0, - }, - _ => return None, - }; - if orientation == 2 { - std::mem::swap(&mut page_size.width, &mut page_size.height); - } - Some(page_size) -} - -#[cfg(test)] -fn read_column_widths(sheet_xml: &str) -> Result> { - read_column_widths_with_mdw(sheet_xml, 7.0) -} - -fn read_column_widths_with_mdw(sheet_xml: &str, max_digit_width: f32) -> Result> { - let xml = roxmltree::Document::parse(sheet_xml)?; - let mut widths = Vec::new(); - for column in xml.descendants().filter(|node| node.has_tag_name("col")) { - let Some(min) = column - .attribute("min") - .and_then(|value| value.parse::().ok()) - else { - continue; - }; - let max = column - .attribute("max") - .and_then(|value| value.parse::().ok()) - .unwrap_or(min); - let width = if matches!(column.attribute("hidden"), Some("1" | "true")) { - 0.0 - } else { - column - .attribute("width") - .and_then(|value| value.parse::().ok()) - .filter(|value| *value > 0.0) - .map(|width| excel_column_width_to_points_with_mdw(width, max_digit_width)) - .unwrap_or(COL_WIDTH) - }; - if widths.len() < max { - widths.resize(max, COL_WIDTH); - } - for column_index in min..=max { - widths[column_index - 1] = width; - } - } - Ok(widths) -} - -fn excel_column_width_to_points_with_mdw(char_units: f32, max_digit_width: f32) -> f32 { - let padding = (128.0 / max_digit_width).floor(); - (((256.0 * char_units + padding) / 256.0) * max_digit_width).floor() * 0.75 -} - -fn read_merge_ranges(sheet_xml: &str) -> Result> { - let xml = roxmltree::Document::parse(sheet_xml)?; - Ok(xml - .descendants() - .filter(|node| node.has_tag_name("mergeCell")) - .filter_map(|node| node.attribute("ref")) - .filter_map(|reference| { - let (start, end) = reference.split_once(':')?; - let (start_col, start_row) = cell_position(start)?; - let (end_col, end_row) = cell_position(end)?; - Some(MergeRange { - start_col, - end_col, - start_row, - end_row, - }) - }) - .collect()) -} - -fn read_row_breaks(sheet_xml: &str) -> Result> { - let xml = roxmltree::Document::parse(sheet_xml)?; - Ok(xml - .descendants() - .filter(|node| node.has_tag_name("rowBreaks")) - .flat_map(|row_breaks| row_breaks.children()) - .filter(|node| node.has_tag_name("brk")) - .filter_map(|node| node.attribute("id")) - .filter_map(|value| value.parse::().ok()) - .filter(|row_index| *row_index > 0) - .collect()) -} - -fn column_groups(widths: &[f32], usable_width: f32) -> Vec<(usize, usize)> { - let mut groups = Vec::new(); - let mut start = 0; - while start < widths.len() { - let mut end = start; - let mut group_width = 0.0; - while end < widths.len() { - let width = widths[end]; - if end > start && group_width + width > usable_width { - break; - } - group_width += width; - end += 1; - } - groups.push((start, end.max(start + 1))); - start = end.max(start + 1); - } - groups -} - -fn effective_content_scale( - unscaled_width: f32, - usable_width: f32, - print_scale: f32, - fit_to_width: bool, -) -> f32 { - if !fit_to_width || unscaled_width <= 0.0 { - return print_scale; - } - (usable_width / unscaled_width).min(1.0) -} - -fn read_sheet_images( - archive: &mut ZipArchive, - sheet_path: &str, - sheet_xml: &str, - column_widths: &[f32], - rows: &[RowData], - default_row_height: f32, -) -> Result> { - let sheet = roxmltree::Document::parse(sheet_xml)?; - let mut images = read_legacy_drawing_images( - archive, - sheet_path, - &sheet, - column_widths, - rows, - default_row_height, - )?; - let Some(drawing_id) = sheet - .descendants() - .find(|node| node.has_tag_name("drawing")) - .and_then(relationship_id) - else { - return Ok(images); - }; - let sheet_rels = read_part_relationships(archive, sheet_path)?; - let Some(drawing_target) = sheet_rels.get(&drawing_id) else { - return Ok(images); - }; - let drawing_path = resolve_part_target(sheet_path, drawing_target); - let Some(drawing_xml) = read_zip_text(archive, &drawing_path)? else { - return Ok(images); - }; - let drawing_rels = read_part_relationships(archive, &drawing_path)?; - let theme_colors = read_theme_colors(archive)?; - let drawing = roxmltree::Document::parse(&drawing_xml)?; - - for anchor in drawing - .descendants() - .filter(|node| node.has_tag_name("oneCellAnchor")) - { - let Some(from) = anchor.children().find(|node| node.has_tag_name("from")) else { - continue; - }; - let Some(ext) = anchor.children().find(|node| node.has_tag_name("ext")) else { - continue; - }; - let Some(image_id) = anchor - .descendants() - .find(|node| node.has_tag_name("blip")) - .and_then(relationship_id) - else { - continue; - }; - let Some(image_target) = drawing_rels.get(&image_id) else { - continue; - }; - let image_path = resolve_part_target(&drawing_path, image_target); - if !image_path.to_ascii_lowercase().ends_with(".jpeg") - && !image_path.to_ascii_lowercase().ends_with(".jpg") - { - continue; - } - let Some(data) = read_zip_bytes(archive, &image_path)? else { - continue; - }; - let Some((pixel_width, pixel_height)) = jpeg_dimensions(&data) else { - continue; - }; - images.push(SheetImage { - data: SheetImageData::Jpeg(data), - pixel_width, - pixel_height, - legacy_vml: false, - col: child_number(from, "col").unwrap_or(0), - row: child_number(from, "row").unwrap_or(0), - col_offset: child_number(from, "colOff").unwrap_or(0) as f32 / 12_700.0, - row_offset: child_number(from, "rowOff").unwrap_or(0) as f32 / 12_700.0, - width: ext - .attribute("cx") - .and_then(|value| value.parse::().ok()) - .unwrap_or(0.0) - / 12_700.0, - height: ext - .attribute("cy") - .and_then(|value| value.parse::().ok()) - .unwrap_or(0.0) - / 12_700.0, - foreground: false, - }); - } - for anchor in drawing - .descendants() - .filter(|node| node.has_tag_name("twoCellAnchor")) - { - if let Some(image) = read_group_image(archive, &drawing_path, &drawing_rels, anchor)? { - images.push(image); - } else if let Some(image) = - read_two_cell_picture(archive, &drawing_path, &drawing_rels, anchor, &theme_colors)? - { - images.push(image); - } else if let Some(image) = read_two_cell_shape( - anchor, - &theme_colors, - column_widths, - rows, - default_row_height, - ) { - images.push(image); - } - } - Ok(images) -} - -fn read_legacy_drawing_images( - archive: &mut ZipArchive, - sheet_path: &str, - sheet: &roxmltree::Document<'_>, - column_widths: &[f32], - rows: &[RowData], - default_row_height: f32, -) -> Result> { - let Some(vml_id) = sheet - .descendants() - .find(|node| node.has_tag_name("legacyDrawing")) - .and_then(relationship_id) - else { - return Ok(Vec::new()); - }; - let sheet_rels = read_part_relationships(archive, sheet_path)?; - let Some(vml_target) = sheet_rels.get(&vml_id) else { - return Ok(Vec::new()); - }; - let vml_path = resolve_part_target(sheet_path, vml_target); - let Some(vml_xml) = read_zip_text(archive, &vml_path)? else { - return Ok(Vec::new()); - }; - let vml_rels = read_part_relationships(archive, &vml_path)?; - let vml = roxmltree::Document::parse(&vml_xml)?; - let mut images = Vec::new(); - - for shape in vml.descendants().filter(|node| node.has_tag_name("shape")) { - let Some(client_data) = shape - .children() - .find(|node| node.has_tag_name("ClientData")) - .filter(|node| node.attribute("ObjectType") == Some("Pict")) - else { - continue; - }; - let Some(image_data) = shape.children().find(|node| node.has_tag_name("imagedata")) else { - continue; - }; - let Some(image_id) = image_data - .attributes() - .find(|attribute| attribute.name() == "relid") - .map(|attribute| attribute.value()) - else { - continue; - }; - let Some(image_target) = vml_rels.get(image_id) else { - continue; - }; - let Some(anchor) = client_data - .children() - .find(|node| node.has_tag_name("Anchor")) - .and_then(|node| node.text()) - .and_then(parse_vml_anchor) - else { - continue; - }; - let style = shape.attribute("style").unwrap_or_default(); - let Some(width) = parse_vml_style_points(style, "width").filter(|value| *value > 0.0) - else { - continue; - }; - let Some(height) = parse_vml_style_points(style, "height").filter(|value| *value > 0.0) - else { - continue; - }; - let image_path = resolve_part_target(&vml_path, image_target); - let Some(bytes) = read_zip_bytes(archive, &image_path)? else { - continue; - }; - let (data, pixel_width, pixel_height) = if image_path.to_ascii_lowercase().ends_with(".emf") - { - let crop = [ - parse_vml_crop(image_data.attribute("cropleft")), - parse_vml_crop(image_data.attribute("croptop")), - parse_vml_crop(image_data.attribute("cropright")), - parse_vml_crop(image_data.attribute("cropbottom")), - ]; - let Some(rgba) = rasterize_emf(&bytes, height, crop) else { - continue; - }; - let pixel_width = rgba.width().min(u16::MAX.into()) as u16; - let pixel_height = rgba.height().min(u16::MAX.into()) as u16; - ( - SheetImageData::Rgba(rgba.into_raw()), - pixel_width, - pixel_height, - ) - } else if let Some((pixel_width, pixel_height)) = jpeg_dimensions(&bytes) { - (SheetImageData::Jpeg(bytes), pixel_width, pixel_height) - } else { - let Ok(decoded) = image::load_from_memory(&bytes) else { - continue; - }; - let rgba = decoded.into_rgba8(); - let pixel_width = rgba.width().min(u16::MAX.into()) as u16; - let pixel_height = rgba.height().min(u16::MAX.into()) as u16; - ( - SheetImageData::Rgba(rgba.into_raw()), - pixel_width, - pixel_height, - ) - }; - let col = anchor[0]; - let row = anchor[2]; - let col_offset = - column_widths.get(col).copied().unwrap_or(COL_WIDTH) * anchor[1] as f32 / 1024.0; - let row_height = rows - .iter() - .find(|candidate| candidate.index == row) - .map(|candidate| candidate.height) - .unwrap_or(default_row_height); - let row_offset = row_height * anchor[3] as f32 / 256.0; - images.push(SheetImage { - data, - pixel_width, - pixel_height, - legacy_vml: true, - col, - row, - col_offset, - row_offset, - width, - height, - foreground: true, - }); - } - - Ok(images) -} - -fn parse_vml_anchor(value: &str) -> Option<[usize; 8]> { - value - .split(',') - .map(|part| part.trim().parse::().ok()) - .collect::>>()? - .try_into() - .ok() -} - -fn parse_vml_style_points(style: &str, property: &str) -> Option { - style.split(';').find_map(|declaration| { - let (name, value) = declaration.split_once(':')?; - if !name.trim().eq_ignore_ascii_case(property) { - return None; - } - let value = value.trim(); - let number = value.get(..value.len().checked_sub(2)?)?; - value - .get(value.len() - 2..) - .filter(|unit| unit.eq_ignore_ascii_case("pt"))?; - number.parse().ok() - }) -} - -fn parse_vml_crop(value: Option<&str>) -> f32 { - value - .and_then(|value| value.strip_suffix('f').or_else(|| value.strip_suffix('F'))) - .and_then(|value| value.parse::().ok()) - .map(|value| (value / 65_536.0).clamp(0.0, 1.0)) - .unwrap_or(0.0) -} - -#[cfg(not(windows))] -fn rasterize_emf(_data: &[u8], _display_height: f32, _crop: [f32; 4]) -> Option { - None -} - -#[cfg(windows)] -fn rasterize_emf(data: &[u8], display_height: f32, crop: [f32; 4]) -> Option { - use std::ffi::c_void; - use std::mem::size_of; - use std::ptr::null_mut; - - use windows_sys::Win32::Foundation::RECT; - use windows_sys::Win32::Graphics::Gdi::{ - CreateCompatibleDC, CreateDIBSection, DeleteDC, DeleteEnhMetaFile, DeleteObject, - PlayEnhMetaFile, SelectObject, SetEnhMetaFileBits, BITMAPINFO, BITMAPINFOHEADER, BI_RGB, - DIB_RGB_COLORS, - }; - - if data.len() < 24 || data.len() > u32::MAX as usize || display_height <= 0.0 { - return None; - } - let read_i32 = |offset: usize| { - Some(i32::from_le_bytes( - data.get(offset..offset + 4)?.try_into().ok()?, - )) - }; - let bounds_width = read_i32(16)?.checked_sub(read_i32(8)?)?.unsigned_abs(); - let bounds_height = read_i32(20)?.checked_sub(read_i32(12)?)?.unsigned_abs(); - if bounds_width == 0 || bounds_height == 0 { - return None; - } - let visible_height = (1.0 - crop[1] - crop[3]).max(0.01); - let raster_height = (display_height * 300.0 / 72.0 / visible_height) - .ceil() - .clamp(32.0, 4096.0) as u32; - let raster_width = (raster_height as f32 * bounds_width as f32 / bounds_height as f32) - .round() - .clamp(32.0, 4096.0) as u32; - - unsafe { - let metafile = SetEnhMetaFileBits(data.len() as u32, data.as_ptr()); - if metafile.is_null() { - return None; - } - let dc = CreateCompatibleDC(null_mut()); - if dc.is_null() { - DeleteEnhMetaFile(metafile); - return None; - } - let mut bitmap_info: BITMAPINFO = std::mem::zeroed(); - bitmap_info.bmiHeader = BITMAPINFOHEADER { - biSize: size_of::() as u32, - biWidth: raster_width as i32, - biHeight: -(raster_height as i32), - biPlanes: 1, - biBitCount: 32, - biCompression: BI_RGB, - ..std::mem::zeroed() - }; - let mut bits: *mut c_void = null_mut(); - let bitmap = CreateDIBSection(dc, &bitmap_info, DIB_RGB_COLORS, &mut bits, null_mut(), 0); - if bitmap.is_null() || bits.is_null() { - DeleteDC(dc); - DeleteEnhMetaFile(metafile); - return None; - } - let old_bitmap = SelectObject(dc, bitmap); - let byte_len = raster_width as usize * raster_height as usize * 4; - std::ptr::write_bytes(bits, 255, byte_len); - let destination = RECT { - left: 0, - top: 0, - right: raster_width as i32, - bottom: raster_height as i32, - }; - let rendered = PlayEnhMetaFile(dc, metafile, &destination) != 0; - let bgra = std::slice::from_raw_parts(bits.cast::(), byte_len); - let mut rgba = Vec::with_capacity(byte_len); - for pixel in bgra.chunks_exact(4) { - rgba.extend_from_slice(&[pixel[2], pixel[1], pixel[0], 255]); - } - SelectObject(dc, old_bitmap); - DeleteObject(bitmap); - DeleteDC(dc); - DeleteEnhMetaFile(metafile); - if !rendered { - return None; - } - - let source = image::RgbaImage::from_raw(raster_width, raster_height, rgba)?; - let crop_x = (raster_width as f32 * crop[0]).round() as u32; - let crop_y = (raster_height as f32 * crop[1]).round() as u32; - let crop_width = (raster_width as f32 * (1.0 - crop[0] - crop[2])) - .round() - .max(1.0) as u32; - let crop_height = (raster_height as f32 * visible_height).round().max(1.0) as u32; - Some( - image::imageops::crop_imm( - &source, - crop_x.min(raster_width - 1), - crop_y.min(raster_height - 1), - crop_width.min(raster_width.saturating_sub(crop_x).max(1)), - crop_height.min(raster_height.saturating_sub(crop_y).max(1)), - ) - .to_image(), - ) - } -} - -fn read_two_cell_shape( - anchor: roxmltree::Node<'_, '_>, - theme_colors: &[PdfColor], - column_widths: &[f32], - rows: &[RowData], - default_row_height: f32, -) -> Option { - let from = anchor.children().find(|node| node.has_tag_name("from"))?; - let shape = anchor.children().find(|node| node.has_tag_name("sp"))?; - let shape_properties = shape.children().find(|node| node.has_tag_name("spPr"))?; - let transform = shape_properties - .children() - .find(|node| node.has_tag_name("xfrm"))?; - let extent = transform.children().find(|node| node.has_tag_name("ext"))?; - let transform_width = emu_attribute(extent, "cx")? / 12_700.0; - let transform_height = emu_attribute(extent, "cy")? / 12_700.0; - let (width, height) = anchor - .children() - .find(|node| node.has_tag_name("to")) - .map(|to| { - let from_x = drawing_column_position(from, column_widths); - let from_y = drawing_row_position(from, rows, default_row_height); - let to_x = drawing_column_position(to, column_widths); - let to_y = drawing_row_position(to, rows, default_row_height); - (to_x - from_x, to_y - from_y) - }) - .filter(|(width, height)| *width > 0.0 && *height > 0.0) - .unwrap_or((transform_width, transform_height)); - if width <= 0.0 || height <= 0.0 { - return None; - } - let fill = shape_properties - .children() - .find(|node| node.has_tag_name("solidFill")) - .and_then(|solid_fill| solid_fill.children().find(|node| node.is_element())) - .and_then(|color| drawing_color(color, theme_colors)) - .or_else(|| { - shape - .children() - .find(|node| node.has_tag_name("style")) - .and_then(|style| style.children().find(|node| node.has_tag_name("fillRef"))) - .and_then(|fill_ref| fill_ref.children().find(|node| node.is_element())) - .and_then(|color| drawing_color(color, theme_colors)) - })?; - let pixel_width = (width * 2.0).round().clamp(1.0, u16::MAX as f32) as u16; - let pixel_height = (height * 2.0).round().clamp(1.0, u16::MAX as f32) as u16; - let fill_pixel = image::Rgba([ - (fill.r * 255.0).round() as u8, - (fill.g * 255.0).round() as u8, - (fill.b * 255.0).round() as u8, - 255, - ]); - let mut canvas = if shape_properties - .children() - .any(|node| node.has_tag_name("prstGeom") && node.attribute("prst") == Some("rect")) - { - image::RgbaImage::from_pixel(pixel_width.into(), pixel_height.into(), fill_pixel) - } else { - let geometry = shape_properties - .children() - .find(|node| node.has_tag_name("custGeom"))?; - let path = geometry - .descendants() - .find(|node| node.has_tag_name("path") && node.attribute("fill") != Some("none"))?; - let path_width = path.attribute("w")?.parse::().ok()?; - let path_height = path.attribute("h")?.parse::().ok()?; - if path_width <= 0.0 || path_height <= 0.0 { - return None; - } - let mut points = Vec::new(); - for command in path.children().filter(|node| node.is_element()) { - if !matches!(command.tag_name().name(), "moveTo" | "lnTo" | "cubicBezTo") { - continue; - } - let Some(point) = command.descendants().rfind(|node| node.has_tag_name("pt")) else { - continue; - }; - let x = - point.attribute("x")?.parse::().ok()? / path_width * f32::from(pixel_width); - let y = - point.attribute("y")?.parse::().ok()? / path_height * f32::from(pixel_height); - points.push((x, y)); - } - if points.len() < 3 { - return None; - } - let mut canvas = image::RgbaImage::new(pixel_width.into(), pixel_height.into()); - draw_filled_polygon(&mut canvas, &points, fill_pixel); - canvas - }; - if transform.attribute("rot") == Some("10800000") { - canvas = image::imageops::rotate180(&canvas); - } - Some(SheetImage { - data: SheetImageData::Rgba(canvas.into_raw()), - pixel_width, - pixel_height, - legacy_vml: false, - col: child_number(from, "col").unwrap_or(0), - row: child_number(from, "row").unwrap_or(0), - col_offset: child_number(from, "colOff").unwrap_or(0) as f32 / 12_700.0, - row_offset: child_number(from, "rowOff").unwrap_or(0) as f32 / 12_700.0, - width, - height, - foreground: true, - }) -} - -fn drawing_column_position(marker: roxmltree::Node<'_, '_>, column_widths: &[f32]) -> f32 { - let column = child_number(marker, "col").unwrap_or(0); - (0..column) - .map(|index| column_widths.get(index).copied().unwrap_or(COL_WIDTH)) - .sum::() - + child_number(marker, "colOff").unwrap_or(0) as f32 / 12_700.0 -} - -fn drawing_row_position( - marker: roxmltree::Node<'_, '_>, - rows: &[RowData], - default_row_height: f32, -) -> f32 { - let row = child_number(marker, "row").unwrap_or(0); - (0..row) - .map(|index| { - rows.iter() - .find(|candidate| candidate.index == index) - .map(|candidate| candidate.height) - .unwrap_or(default_row_height) - }) - .sum::() - + child_number(marker, "rowOff").unwrap_or(0) as f32 / 12_700.0 -} - -fn drawing_color(node: roxmltree::Node<'_, '_>, theme_colors: &[PdfColor]) -> Option { - match node.tag_name().name() { - "schemeClr" => theme_scheme_color(node.attribute("val")?, theme_colors), - "srgbClr" => parse_rgb_color(node.attribute("val")?), - "sysClr" => node - .attribute("lastClr") - .and_then(parse_rgb_color) - .or_else(|| node.attribute("val").and_then(parse_rgb_color)), - _ => None, - } -} - -fn theme_scheme_color(name: &str, theme_colors: &[PdfColor]) -> Option { - let index = match name { - "lt1" | "bg1" => 0, - "dk1" | "tx1" => 1, - "lt2" | "bg2" => 2, - "dk2" | "tx2" => 3, - "accent1" => 4, - "accent2" => 5, - "accent3" => 6, - "accent4" => 7, - "accent5" => 8, - "accent6" => 9, - "hlink" => 10, - "folHlink" => 11, - _ => return None, - }; - theme_colors.get(index).copied() -} - -fn read_two_cell_picture( - archive: &mut ZipArchive, - drawing_path: &str, - drawing_rels: &HashMap, - anchor: roxmltree::Node<'_, '_>, - theme_colors: &[PdfColor], -) -> Result> { - let Some(from) = anchor.children().find(|node| node.has_tag_name("from")) else { - return Ok(None); - }; - let Some(picture) = anchor.children().find(|node| node.has_tag_name("pic")) else { - return Ok(None); - }; - let Some(image_id) = picture - .descendants() - .find(|node| node.has_tag_name("blip")) - .and_then(relationship_id) - else { - return Ok(None); - }; - let Some(image_target) = drawing_rels.get(&image_id) else { - return Ok(None); - }; - let image_path = resolve_part_target(drawing_path, image_target); - let Some(data) = read_zip_bytes(archive, &image_path)? else { - return Ok(None); - }; - let Ok(source) = image::load_from_memory(&data) else { - return Ok(None); - }; - let Some(shape_properties) = picture.children().find(|node| node.has_tag_name("spPr")) else { - return Ok(None); - }; - let Some(transform) = shape_properties - .children() - .find(|child| child.has_tag_name("xfrm")) - else { - return Ok(None); - }; - let Some(extent) = transform.children().find(|node| node.has_tag_name("ext")) else { - return Ok(None); - }; - let width = emu_attribute(extent, "cx").unwrap_or(0.0) / 12_700.0; - let height = emu_attribute(extent, "cy").unwrap_or(0.0) / 12_700.0; - if width <= 0.0 || height <= 0.0 { - return Ok(None); - } - let mut rgba = source.into_rgba8(); - if let Some(background) = shape_properties - .children() - .find(|node| node.has_tag_name("solidFill")) - .and_then(|solid_fill| solid_fill.children().find(|node| node.is_element())) - .and_then(|color| drawing_color(color, theme_colors)) - { - composite_rgba_background(&mut rgba, background); - } - let pixel_width = rgba.width().min(u16::MAX.into()) as u16; - let pixel_height = rgba.height().min(u16::MAX.into()) as u16; - Ok(Some(SheetImage { - data: SheetImageData::Rgba(rgba.into_raw()), - pixel_width, - pixel_height, - legacy_vml: false, - col: child_number(from, "col").unwrap_or(0), - row: child_number(from, "row").unwrap_or(0), - col_offset: child_number(from, "colOff").unwrap_or(0) as f32 / 12_700.0, - row_offset: child_number(from, "rowOff").unwrap_or(0) as f32 / 12_700.0, - width, - height, - foreground: true, - })) -} - -fn composite_rgba_background(image: &mut image::RgbaImage, background: PdfColor) { - let background = [ - (background.r * 255.0).round() as u16, - (background.g * 255.0).round() as u16, - (background.b * 255.0).round() as u16, - ]; - for pixel in image.pixels_mut() { - let alpha = u16::from(pixel[3]); - if alpha == 255 { - continue; - } - for channel in 0..3 { - pixel[channel] = - ((u16::from(pixel[channel]) * alpha + background[channel] * (255 - alpha) + 127) - / 255) as u8; - } - pixel[3] = 255; - } -} - -fn read_group_image( - archive: &mut ZipArchive, - drawing_path: &str, - drawing_rels: &HashMap, - anchor: roxmltree::Node<'_, '_>, -) -> Result> { - let Some(from) = anchor.children().find(|node| node.has_tag_name("from")) else { - return Ok(None); - }; - let Some(group) = anchor.children().find(|node| node.has_tag_name("grpSp")) else { - return Ok(None); - }; - let Some(group_transform) = group - .children() - .find(|node| node.has_tag_name("grpSpPr")) - .and_then(|node| node.children().find(|child| child.has_tag_name("xfrm"))) - else { - return Ok(None); - }; - let Some(group_extent) = group_transform - .children() - .find(|node| node.has_tag_name("ext")) - else { - return Ok(None); - }; - let width = emu_attribute(group_extent, "cx").unwrap_or(0.0) / 12_700.0; - let height = emu_attribute(group_extent, "cy").unwrap_or(0.0) / 12_700.0; - if width <= 0.0 || height <= 0.0 { - return Ok(None); - } - let child_offset = group_transform - .children() - .find(|node| node.has_tag_name("chOff")); - let child_extent = group_transform - .children() - .find(|node| node.has_tag_name("chExt")); - let child_x = child_offset - .and_then(|node| emu_attribute(node, "x")) - .unwrap_or(0.0); - let child_y = child_offset - .and_then(|node| emu_attribute(node, "y")) - .unwrap_or(0.0); - let child_width = child_extent - .and_then(|node| emu_attribute(node, "cx")) - .filter(|value| *value > 0.0) - .unwrap_or(1.0); - let child_height = child_extent - .and_then(|node| emu_attribute(node, "cy")) - .filter(|value| *value > 0.0) - .unwrap_or(1.0); - let pixel_width = (width * 2.0).round().clamp(1.0, u16::MAX as f32) as u16; - let pixel_height = (height * 2.0).round().clamp(1.0, u16::MAX as f32) as u16; - let mut canvas = image::RgbaImage::new(pixel_width.into(), pixel_height.into()); - - for picture in group.children().filter(|node| node.has_tag_name("pic")) { - let Some(image_id) = picture - .descendants() - .find(|node| node.has_tag_name("blip")) - .and_then(relationship_id) - else { - continue; - }; - let Some(image_target) = drawing_rels.get(&image_id) else { - continue; - }; - let image_path = resolve_part_target(drawing_path, image_target); - let Some(data) = read_zip_bytes(archive, &image_path)? else { - continue; - }; - let Ok(source) = image::load_from_memory(&data) else { - continue; - }; - let Some(transform) = picture - .children() - .find(|node| node.has_tag_name("spPr")) - .and_then(|node| node.children().find(|child| child.has_tag_name("xfrm"))) - else { - continue; - }; - let Some((left, top, image_width, image_height)) = group_child_rect( - transform, - child_x, - child_y, - child_width, - child_height, - pixel_width, - pixel_height, - ) else { - continue; - }; - let image_width = (image_width as f32 * SVG_FALLBACK_HORIZONTAL_SCALE) - .round() - .max(1.0) as u32; - let resized = source.resize_exact( - image_width, - image_height, - image::imageops::FilterType::Lanczos3, - ); - image::imageops::overlay(&mut canvas, &resized, left.into(), top.into()); - } - - for shape in group.children().filter(|node| node.has_tag_name("sp")) { - let Some(transform) = shape - .children() - .find(|node| node.has_tag_name("spPr")) - .and_then(|node| node.children().find(|child| child.has_tag_name("xfrm"))) - else { - continue; - }; - let Some((left, top, shape_width, shape_height)) = group_child_rect( - transform, - child_x, - child_y, - child_width, - child_height, - pixel_width, - pixel_height, - ) else { - continue; - }; - let fill = shape - .descendants() - .find(|node| node.has_tag_name("srgbClr")) - .and_then(|node| node.attribute("val")) - .and_then(parse_rgb_color) - .unwrap_or(PdfColor::BLACK); - let alpha = shape - .descendants() - .find(|node| node.has_tag_name("alpha")) - .and_then(|node| node.attribute("val")) - .and_then(|value| value.parse::().ok()) - .map(|value| (value * 255.0 / 100_000.0).round() as u8) - .unwrap_or(255); - draw_lower_half_ellipse( - &mut canvas, - left, - top, - shape_width, - shape_height, - image::Rgba([ - (fill.r * 255.0).round() as u8, - (fill.g * 255.0).round() as u8, - (fill.b * 255.0).round() as u8, - alpha, - ]), - ); - } - - Ok(Some(SheetImage { - data: SheetImageData::Rgba(canvas.into_raw()), - pixel_width, - pixel_height, - legacy_vml: false, - col: child_number(from, "col").unwrap_or(0), - row: child_number(from, "row").unwrap_or(0), - col_offset: child_number(from, "colOff").unwrap_or(0) as f32 / 12_700.0, - row_offset: child_number(from, "rowOff").unwrap_or(0) as f32 / 12_700.0, - width, - height, - foreground: true, - })) -} - -fn emu_attribute(node: roxmltree::Node<'_, '_>, name: &str) -> Option { - node.attribute(name)?.parse().ok() -} - -fn group_child_rect( - transform: roxmltree::Node<'_, '_>, - group_x: f32, - group_y: f32, - group_width: f32, - group_height: f32, - pixel_width: u16, - pixel_height: u16, -) -> Option<(u32, u32, u32, u32)> { - let offset = transform.children().find(|node| node.has_tag_name("off"))?; - let extent = transform.children().find(|node| node.has_tag_name("ext"))?; - let left = ((emu_attribute(offset, "x")? - group_x) / group_width * f32::from(pixel_width)) - .round() - .max(0.0) as u32; - let top = ((emu_attribute(offset, "y")? - group_y) / group_height * f32::from(pixel_height)) - .round() - .max(0.0) as u32; - let width = (emu_attribute(extent, "cx")? / group_width * f32::from(pixel_width)) - .round() - .max(1.0) as u32; - let height = (emu_attribute(extent, "cy")? / group_height * f32::from(pixel_height)) - .round() - .max(1.0) as u32; - Some((left, top, width, height)) -} - -fn draw_lower_half_ellipse( - canvas: &mut image::RgbaImage, - left: u32, - top: u32, - width: u32, - height: u32, - color: image::Rgba, -) { - let radius_x = width as f32 / 2.0; - let radius_y = height as f32; - for y in 0..height { - for x in 0..width { - let normalized_x = (x as f32 + 0.5 - radius_x) / radius_x; - let normalized_y = (y as f32 + 0.5) / radius_y; - if normalized_x * normalized_x + normalized_y * normalized_y <= 1.0 - && left + x < canvas.width() - && top + y < canvas.height() - { - canvas.put_pixel(left + x, top + y, color); - } - } - } -} - -fn draw_filled_polygon( - canvas: &mut image::RgbaImage, - points: &[(f32, f32)], - color: image::Rgba, -) { - for y in 0..canvas.height() { - let scan_y = y as f32 + 0.5; - let mut intersections = Vec::new(); - for index in 0..points.len() { - let (x1, y1) = points[index]; - let (x2, y2) = points[(index + 1) % points.len()]; - if (y1 <= scan_y && scan_y < y2) || (y2 <= scan_y && scan_y < y1) { - intersections.push(x1 + (scan_y - y1) * (x2 - x1) / (y2 - y1)); - } - } - intersections.sort_by(f32::total_cmp); - for pair in intersections.chunks_exact(2) { - let start = pair[0].ceil().max(0.0) as u32; - let end = pair[1].floor().min(canvas.width() as f32 - 1.0) as u32; - for x in start..=end { - canvas.put_pixel(x, y, color); - } - } - } -} - -fn read_part_relationships( - archive: &mut ZipArchive, - part_path: &str, -) -> Result> { - let Some(file_name) = part_path.rsplit('/').next() else { - return Ok(HashMap::new()); - }; - let parent = part_path - .strip_suffix(file_name) - .unwrap_or_default() - .trim_end_matches('/'); - let rels_path = format!("{parent}/_rels/{file_name}.rels"); - let Some(rels_xml) = read_zip_text(archive, &rels_path)? else { - return Ok(HashMap::new()); - }; - let rels_doc = roxmltree::Document::parse(&rels_xml)?; - Ok(rels_doc - .descendants() - .filter(|node| node.has_tag_name("Relationship")) - .filter_map(|rel| Some((rel.attribute("Id")?, rel.attribute("Target")?))) - .map(|(id, target)| (id.to_owned(), target.to_owned())) - .collect()) -} - -fn relationship_id(node: roxmltree::Node<'_, '_>) -> Option { - node.attributes() - .find(|attribute| matches!(attribute.name(), "id" | "embed")) - .map(|attribute| attribute.value().to_owned()) -} - -fn resolve_part_target(source_part: &str, target: &str) -> String { - let combined = if target.starts_with('/') { - target.trim_start_matches('/').to_owned() - } else { - let parent = source_part - .rsplit_once('/') - .map(|(path, _)| path) - .unwrap_or(""); - format!("{parent}/{target}") - }; - let mut segments = Vec::new(); - let normalized = combined.replace('\\', "/"); - for segment in normalized.split('/') { - match segment { - "" | "." => {} - ".." => { - segments.pop(); - } - _ => segments.push(segment), - } - } - segments.join("/") -} - -fn child_number(node: roxmltree::Node<'_, '_>, name: &str) -> Option { - node.children() - .find(|child| child.has_tag_name(name)) - .and_then(|child| child.text()) - .and_then(|value| value.parse().ok()) -} - -fn read_zip_bytes( - archive: &mut ZipArchive, - path: &str, -) -> Result>> { - let Ok(mut entry) = archive.by_name(path) else { - return Ok(None); - }; - let mut bytes = Vec::with_capacity(entry.size() as usize); - entry.read_to_end(&mut bytes)?; - Ok(Some(bytes)) -} - -fn jpeg_dimensions(data: &[u8]) -> Option<(u16, u16)> { - if !data.starts_with(&[0xff, 0xd8]) { - return None; - } - let mut index = 2; - while index + 3 < data.len() { - while index < data.len() && data[index] != 0xff { - index += 1; - } - while index < data.len() && data[index] == 0xff { - index += 1; - } - let marker = *data.get(index)?; - index += 1; - if marker == 0xd9 || marker == 0xda { - break; - } - if marker == 0x01 || (0xd0..=0xd8).contains(&marker) { - continue; - } - let length = u16::from_be_bytes([*data.get(index)?, *data.get(index + 1)?]) as usize; - if length < 2 || index + length > data.len() { - return None; - } - if matches!( - marker, - 0xc0..=0xc3 | 0xc5..=0xc7 | 0xc9..=0xcb | 0xcd..=0xcf - ) { - let height = u16::from_be_bytes([*data.get(index + 3)?, *data.get(index + 4)?]); - let width = u16::from_be_bytes([*data.get(index + 5)?, *data.get(index + 6)?]); - return Some((width, height)); - } - index += length; - } - None -} - -fn read_styles( - archive: &mut ZipArchive, -) -> Result { - let Some(styles_xml) = read_zip_text(archive, "xl/styles.xml")? else { - return Ok(XlsxStyles::default()); - }; - let theme_colors = read_theme_colors(archive)?; - let xml = roxmltree::Document::parse(&styles_xml)?; - let custom_formats = xml - .descendants() - .filter(|node| node.has_tag_name("numFmt")) - .filter_map(|node| { - Some(( - node.attribute("numFmtId")?.parse::().ok()?, - node.attribute("formatCode")?.to_owned(), - )) - }) - .collect::>(); - let fonts = xml - .descendants() - .find(|node| node.has_tag_name("fonts")) - .map(|fonts| { - fonts - .children() - .filter(|node| node.has_tag_name("font")) - .map(|font| { - let font_name = font - .children() - .find(|node| node.has_tag_name("name")) - .and_then(|node| node.attribute("val")); - let font_size = font - .children() - .find(|node| node.has_tag_name("sz")) - .and_then(|node| node.attribute("val")) - .and_then(|value| value.parse::().ok()) - .unwrap_or(CELL_FONT_SIZE); - FontStyle { - bold: font.children().any(|node| { - node.has_tag_name("b") && node.attribute("val") != Some("0") - }) || font_name_is_emphasis(font_name), - italic: font.children().any(|node| { - node.has_tag_name("i") && node.attribute("val") != Some("0") - }), - size: excel_pdf_font_size(font_name, font_size), - color: font - .children() - .find(|node| node.has_tag_name("color")) - .and_then(|node| parse_xlsx_color(node, &theme_colors)) - .unwrap_or(PdfColor::BLACK), - preferred_font: xlsx_preferred_font(font_name), - } - }) - .collect::>() - }) - .unwrap_or_default(); - let max_digit_width = xml - .descendants() - .find(|node| node.has_tag_name("fonts")) - .and_then(|fonts| fonts.children().find(|node| node.has_tag_name("font"))) - .map(|font| { - let name = font - .children() - .find(|node| node.has_tag_name("name")) - .and_then(|node| node.attribute("val")); - let size = font - .children() - .find(|node| node.has_tag_name("sz")) - .and_then(|node| node.attribute("val")) - .and_then(|value| value.parse::().ok()) - .unwrap_or(CELL_FONT_SIZE); - excel_max_digit_width(name, size) - }) - .unwrap_or(7.0); - let fills = xml - .descendants() - .find(|node| node.has_tag_name("fills")) - .map(|fills| { - fills - .children() - .filter(|node| node.has_tag_name("fill")) - .map(|fill| { - fill.descendants() - .find(|node| node.has_tag_name("patternFill")) - .filter(|node| node.attribute("patternType") == Some("solid")) - .and_then(|pattern| { - pattern.children().find(|node| node.has_tag_name("fgColor")) - }) - .and_then(|color| parse_xlsx_color(color, &theme_colors)) - }) - .collect::>() - }) - .unwrap_or_default(); - let borders = xml - .descendants() - .find(|node| node.has_tag_name("borders")) - .map(|borders| { - borders - .children() - .filter(|node| node.has_tag_name("border")) - .map(|border| parse_cell_borders(border, &theme_colors)) - .collect::>() - }) - .unwrap_or_default(); - let cells = xml - .descendants() - .find(|node| node.has_tag_name("cellXfs")) - .map(|cell_xfs| { - cell_xfs - .children() - .filter(|node| node.has_tag_name("xf")) - .map(|xf| { - let font = xf - .attribute("fontId") - .and_then(|value| value.parse::().ok()) - .and_then(|font_id| fonts.get(font_id).copied()) - .unwrap_or_default(); - let fill_color = xf - .attribute("fillId") - .and_then(|value| value.parse::().ok()) - .and_then(|fill_id| fills.get(fill_id).copied().flatten()); - let cell_borders = xf - .attribute("borderId") - .and_then(|value| value.parse::().ok()) - .and_then(|border_id| borders.get(border_id).copied()) - .unwrap_or_default(); - let alignment = xf.children().find(|node| node.has_tag_name("alignment")); - let stacked_text = - is_stacked_text(alignment.and_then(|node| node.attribute("textRotation"))); - CellStyle { - bold: font.bold, - italic: font.italic, - strike: false, - font_size: font.size, - font_color: font.color, - fill_color, - borders: cell_borders, - number_format: parse_number_format( - xf.attribute("numFmtId"), - &custom_formats, - ), - horizontal_alignment: parse_horizontal_alignment( - alignment.and_then(|node| node.attribute("horizontal")), - ), - vertical_alignment: parse_vertical_alignment( - alignment.and_then(|node| node.attribute("vertical")), - ), - indent: alignment - .and_then(|node| node.attribute("indent")) - .and_then(|value| value.parse::().ok()) - .filter(|value| *value > 0.0) - .unwrap_or(0.0), - wrap_text: alignment - .and_then(|node| node.attribute("wrapText")) - .is_some_and(|value| matches!(value, "1" | "true")), - stacked_text, - preferred_font: font.preferred_font, - } - }) - .collect::>() - }) - .unwrap_or_default(); - let differential_fills = xml - .descendants() - .find(|node| node.has_tag_name("dxfs")) - .map(|dxfs| { - dxfs.children() - .filter(|node| node.has_tag_name("dxf")) - .map(|dxf| { - dxf.descendants() - .find(|node| node.has_tag_name("patternFill")) - .and_then(|pattern| { - pattern - .children() - .find(|node| node.has_tag_name("fgColor")) - .or_else(|| { - pattern.children().find(|node| node.has_tag_name("bgColor")) - }) - }) - .and_then(|color| parse_xlsx_color(color, &theme_colors)) - }) - .collect::>() - }) - .unwrap_or_default(); - let differential_fonts = xml - .descendants() - .find(|node| node.has_tag_name("dxfs")) - .map(|dxfs| { - dxfs.children() - .filter(|node| node.has_tag_name("dxf")) - .map(|dxf| { - let Some(font) = dxf.children().find(|node| node.has_tag_name("font")) else { - return DifferentialFontStyle::default(); - }; - DifferentialFontStyle { - bold: font - .children() - .find(|node| node.has_tag_name("b")) - .map(|node| node.attribute("val") != Some("0")), - italic: font - .children() - .find(|node| node.has_tag_name("i")) - .map(|node| node.attribute("val") != Some("0")), - strike: font - .children() - .find(|node| node.has_tag_name("strike")) - .map(|node| node.attribute("val") != Some("0")), - color: font - .children() - .find(|node| node.has_tag_name("color")) - .and_then(|color| parse_xlsx_color(color, &theme_colors)), - } - }) - .collect::>() - }) - .unwrap_or_default(); - let differential_borders = xml - .descendants() - .find(|node| node.has_tag_name("dxfs")) - .map(|dxfs| { - dxfs.children() - .filter(|node| node.has_tag_name("dxf")) - .map(|dxf| { - dxf.children() - .find(|node| node.has_tag_name("border")) - .map(|border| parse_table_borders(border, &theme_colors)) - }) - .collect::>() - }) - .unwrap_or_default(); - let table_base_fills = xml - .descendants() - .filter(|node| node.has_tag_name("tableStyle")) - .filter_map(|style| { - let name = style.attribute("name")?; - let whole_table = style.children().find(|node| { - node.has_tag_name("tableStyleElement") - && node.attribute("type") == Some("wholeTable") - })?; - let dxf_id = whole_table.attribute("dxfId")?.parse::().ok()?; - let fill = differential_fills.get(dxf_id).copied().flatten()?; - Some((name.to_owned(), fill)) - }) - .collect(); - let table_first_row_stripes = xml - .descendants() - .filter(|node| node.has_tag_name("tableStyle")) - .filter_map(|style| { - let name = style.attribute("name")?; - let stripe = style.children().find(|node| { - node.has_tag_name("tableStyleElement") - && node.attribute("type") == Some("firstRowStripe") - })?; - let dxf_id = stripe.attribute("dxfId")?.parse::().ok()?; - let fill = differential_fills.get(dxf_id).copied().flatten()?; - let size = stripe - .attribute("size") - .and_then(|value| value.parse::().ok()) - .filter(|value| *value > 0) - .unwrap_or(1); - Some((name.to_owned(), (fill, size))) - }) - .collect(); - let collect_table_fills = |element_type: &str| { - xml.descendants() - .filter(|node| node.has_tag_name("tableStyle")) - .filter_map(|style| { - let name = style.attribute("name")?; - let element = style.children().find(|node| { - node.has_tag_name("tableStyleElement") - && node.attribute("type") == Some(element_type) - })?; - let dxf_id = element.attribute("dxfId")?.parse::().ok()?; - let fill = differential_fills.get(dxf_id).copied().flatten()?; - Some((name.to_owned(), fill)) - }) - .collect::>() - }; - let table_header_fills = collect_table_fills("headerRow"); - let table_total_fills = collect_table_fills("totalRow"); - let collect_table_fonts = |element_type: &str| { - xml.descendants() - .filter(|node| node.has_tag_name("tableStyle")) - .filter_map(|style| { - let name = style.attribute("name")?; - let element = style.children().find(|node| { - node.has_tag_name("tableStyleElement") - && node.attribute("type") == Some(element_type) - })?; - let dxf_id = element.attribute("dxfId")?.parse::().ok()?; - let font = differential_fonts.get(dxf_id).copied()?; - font.any().then(|| (name.to_owned(), font)) - }) - .collect::>() - }; - let table_whole_fonts = collect_table_fonts("wholeTable"); - let table_header_fonts = collect_table_fonts("headerRow"); - let table_total_fonts = collect_table_fonts("totalRow"); - let collect_table_borders = |element_type: &str| { - xml.descendants() - .filter(|node| node.has_tag_name("tableStyle")) - .filter_map(|style| { - let name = style.attribute("name")?; - let element = style.children().find(|node| { - node.has_tag_name("tableStyleElement") - && node.attribute("type") == Some(element_type) - })?; - let dxf_id = element.attribute("dxfId")?.parse::().ok()?; - let borders = differential_borders.get(dxf_id).copied().flatten()?; - Some((name.to_owned(), borders)) - }) - .collect::>() - }; - let table_whole_borders = collect_table_borders("wholeTable"); - let table_header_borders = collect_table_borders("headerRow"); - let table_total_borders = collect_table_borders("totalRow"); - Ok(XlsxStyles { - cells, - differential_fonts, - differential_fills, - max_digit_width, - table_base_fills, - table_first_row_stripes, - table_header_fills, - table_total_fills, - table_whole_fonts, - table_header_fonts, - table_total_fonts, - table_whole_borders, - table_header_borders, - table_total_borders, - }) -} - -fn apply_sheet_conditional_formats( - sheet_xml: &str, - rows: &mut [RowData], - styles: &XlsxStyles, -) -> Result<()> { - let sheet = roxmltree::Document::parse(sheet_xml)?; - for formatting in sheet - .descendants() - .filter(|node| node.has_tag_name("conditionalFormatting")) - { - let ranges = formatting.attribute("sqref").unwrap_or_default(); - for rule in formatting.children().filter(|node| { - node.has_tag_name("cfRule") - && node.attribute("type") == Some("cellIs") - && node.attribute("operator") == Some("equal") - }) { - let Some(color) = rule - .attribute("dxfId") - .and_then(|value| value.parse::().ok()) - .and_then(|index| { - styles - .differential_fonts - .get(index) - .and_then(|style| style.color) - }) - else { - continue; - }; - let Some(expected) = rule - .children() - .find(|node| node.has_tag_name("formula")) - .and_then(|node| node.text()) - .map(|value| value.trim_matches('"')) - else { - continue; - }; - for range in ranges.split_whitespace() { - let (start, end) = range.split_once(':').unwrap_or((range, range)); - let Some((start_col, start_row)) = cell_position(start) else { - continue; - }; - let Some((end_col, end_row)) = cell_position(end) else { - continue; - }; - for row in rows - .iter_mut() - .filter(|row| row.index >= start_row && row.index <= end_row) - { - for cell in row - .cells - .iter_mut() - .enumerate() - .filter(|(column, _)| *column >= start_col && *column <= end_col) - .map(|(_, cell)| cell) - { - if cell.text == expected { - cell.style.font_color = color; - } - } - } - } - } - for rule in formatting.children().filter(|node| { - node.has_tag_name("cfRule") && node.attribute("type") == Some("containsText") - }) { - let Some(expected) = rule.attribute("text") else { - continue; - }; - let differential_index = rule - .attribute("dxfId") - .and_then(|value| value.parse::().ok()); - let font = differential_index - .and_then(|index| styles.differential_fonts.get(index).copied()) - .unwrap_or_default(); - let fill = differential_index - .and_then(|index| styles.differential_fills.get(index).copied().flatten()); - for range in ranges.split_whitespace() { - let (start, end) = range.split_once(':').unwrap_or((range, range)); - let Some((start_col, start_row)) = cell_position(start) else { - continue; - }; - let Some((end_col, end_row)) = cell_position(end) else { - continue; - }; - for row in rows - .iter_mut() - .filter(|row| row.index >= start_row && row.index <= end_row) - { - for cell in row - .cells - .iter_mut() - .enumerate() - .filter(|(column, _)| *column >= start_col && *column <= end_col) - .map(|(_, cell)| cell) - { - if !cell - .text - .to_ascii_lowercase() - .contains(&expected.to_ascii_lowercase()) - { - continue; - } - if let Some(bold) = font.bold { - cell.style.bold = bold; - } - if let Some(italic) = font.italic { - cell.style.italic = italic; - } - if let Some(strike) = font.strike { - cell.style.strike = strike; - } - if let Some(color) = font.color { - cell.style.font_color = color; - } - if let Some(fill) = fill { - cell.style.fill_color = Some(fill); - } - } - } - } - } - for rule in formatting.children().filter(|node| { - node.has_tag_name("cfRule") && node.attribute("type") == Some("expression") - }) { - let Some(formula) = rule - .children() - .find(|node| node.has_tag_name("formula")) - .and_then(|node| node.text()) - else { - continue; - }; - if let Some((reference_col, reference_row, expected)) = - parse_conditional_text_search(formula) - { - let differential_index = rule - .attribute("dxfId") - .and_then(|value| value.parse::().ok()); - let fill = differential_index - .and_then(|index| styles.differential_fills.get(index).copied().flatten()); - let matches = rows - .iter() - .find(|row| row.index == reference_row) - .and_then(|row| row.cells.get(reference_col)) - .is_some_and(|cell| { - cell.text - .to_ascii_lowercase() - .contains(&expected.to_ascii_lowercase()) - }); - if matches { - for range in ranges.split_whitespace() { - let (start, end) = range.split_once(':').unwrap_or((range, range)); - let Some((start_col, start_row)) = cell_position(start) else { - continue; - }; - let Some((end_col, end_row)) = cell_position(end) else { - continue; - }; - for row in rows - .iter_mut() - .filter(|row| row.index >= start_row && row.index <= end_row) - { - if row.cells.len() <= end_col { - row.cells.resize(end_col + 1, CellData::default()); - } - if let Some(fill) = fill { - for cell in &mut row.cells[start_col..=end_col] { - cell.style.fill_color = Some(fill); - } - } - } - } - } - continue; - } - if let Some((reference_col, reference_row, row_absolute, expected)) = - parse_conditional_text_equality(formula) - { - let differential_index = rule - .attribute("dxfId") - .and_then(|value| value.parse::().ok()); - let font = differential_index - .and_then(|index| styles.differential_fonts.get(index).copied()) - .unwrap_or_default(); - let fill = differential_index - .and_then(|index| styles.differential_fills.get(index).copied().flatten()); - for range in ranges.split_whitespace() { - let (start, end) = range.split_once(':').unwrap_or((range, range)); - let Some((start_col, start_row)) = cell_position(start) else { - continue; - }; - let Some((end_col, end_row)) = cell_position(end) else { - continue; - }; - for row_position in 0..rows.len() { - let target_row = rows[row_position].index; - if target_row < start_row || target_row > end_row { - continue; - } - let source_row = if row_absolute { - reference_row - } else { - reference_row + target_row - start_row - }; - let matches = rows - .iter() - .find(|candidate| candidate.index == source_row) - .and_then(|source| source.cells.get(reference_col)) - .is_some_and(|cell| cell.text.eq_ignore_ascii_case(&expected)); - if !matches { - continue; - } - let row = &mut rows[row_position]; - if row.cells.len() <= end_col { - row.cells.resize(end_col + 1, CellData::default()); - } - for cell in &mut row.cells[start_col..=end_col] { - if let Some(bold) = font.bold { - cell.style.bold = bold; - } - if let Some(italic) = font.italic { - cell.style.italic = italic; - } - if let Some(strike) = font.strike { - cell.style.strike = strike; - } - if let Some(color) = font.color { - cell.style.font_color = color; - } - if let Some(fill) = fill { - cell.style.fill_color = Some(fill); - } - } - } - } - continue; - } - if formula.replace(' ', "") != "StartDate+0=TODAY()" { - continue; - } - let Some(fill) = rule - .attribute("dxfId") - .and_then(|value| value.parse::().ok()) - .and_then(|index| styles.differential_fills.get(index).copied().flatten()) - else { - continue; - }; - for range in ranges.split_whitespace() { - let (start, end) = range.split_once(':').unwrap_or((range, range)); - let Some((start_col, start_row)) = cell_position(start) else { - continue; - }; - let Some((end_col, end_row)) = cell_position(end) else { - continue; - }; - for row in rows - .iter_mut() - .filter(|row| row.index >= start_row && row.index <= end_row) - { - if row.cells.len() <= end_col { - row.cells.resize(end_col + 1, CellData::default()); - } - for cell in &mut row.cells[start_col..=end_col] { - cell.style.fill_color = Some(fill); - } - } - } - } - } - Ok(()) -} - -fn parse_conditional_text_equality(formula: &str) -> Option<(usize, usize, bool, String)> { - let (reference, expected) = formula.split_once('=')?; - let reference = reference.trim(); - let expected = expected - .trim() - .strip_prefix('"')? - .strip_suffix('"')? - .to_owned(); - let row_absolute = reference - .trim_start_matches('$') - .chars() - .find(|ch| !ch.is_ascii_alphabetic()) - == Some('$'); - let (column, row) = cell_position(reference)?; - Some((column, row, row_absolute, expected)) -} - -fn parse_conditional_text_search(formula: &str) -> Option<(usize, usize, String)> { - const PREFIX: &str = "ISNUMBER(SEARCH(\""; - const SUFFIX: &str = "))=TRUE"; - let compact = formula.replace(' ', ""); - let upper = compact.to_ascii_uppercase(); - if !upper.starts_with(PREFIX) || !upper.ends_with(SUFFIX) { - return None; - } - let body = &compact[PREFIX.len()..compact.len() - SUFFIX.len()]; - let (expected, reference) = body.split_once("\",")?; - let (column, row) = cell_position(reference)?; - Some((column, row, expected.to_owned())) -} - -fn apply_sheet_table_styles( - archive: &mut ZipArchive, - sheet_path: &str, - sheet_xml: &str, - rows: &mut [RowData], - styles: &XlsxStyles, -) -> Result<()> { - let sheet = roxmltree::Document::parse(sheet_xml)?; - let relationships = read_part_relationships(archive, sheet_path)?; - for table_id in sheet - .descendants() - .filter(|node| node.has_tag_name("tablePart")) - .filter_map(relationship_id) - { - let Some(target) = relationships.get(&table_id) else { - continue; - }; - let table_path = resolve_part_target(sheet_path, target); - let Some(table_xml) = read_zip_text(archive, &table_path)? else { - continue; - }; - let table = roxmltree::Document::parse(&table_xml)?; - let root = table.root_element(); - let Some((start, end)) = root - .attribute("ref") - .and_then(|range| range.split_once(':')) - else { - continue; - }; - let Some((start_col, start_row)) = cell_position(start) else { - continue; - }; - let Some((end_col, end_row)) = cell_position(end) else { - continue; - }; - let Some(style_info) = root - .children() - .find(|node| node.has_tag_name("tableStyleInfo")) - else { - continue; - }; - let header_rows = root - .attribute("headerRowCount") - .and_then(|value| value.parse::().ok()) - .unwrap_or(1); - let data_start = start_row + header_rows; - let total_rows = root - .attribute("totalsRowCount") - .and_then(|value| value.parse::().ok()) - .unwrap_or(0); - let direct_font = |attribute: &str| { - root.attribute(attribute) - .and_then(|value| value.parse::().ok()) - .and_then(|index| styles.differential_fonts.get(index).copied()) - .filter(|font| font.any()) - }; - let direct_header_font = direct_font("headerRowDxfId"); - let direct_data_font = direct_font("dataDxfId"); - let direct_total_font = direct_font("totalsRowDxfId"); - let style_name = style_info.attribute("name").unwrap_or_default(); - let total_start = (end_row + 1).saturating_sub(total_rows).max(start_row); - let data_end = total_start.saturating_sub(1); - if data_start <= data_end { - if let Some(font) = styles.table_whole_fonts.get(style_name).copied() { - apply_table_font_layer(rows, start_col, end_col, data_start, data_end, font); - } - if let Some(font) = direct_data_font { - apply_table_font_layer(rows, start_col, end_col, data_start, data_end, font); - } - } - if header_rows > 0 { - let header_end = (start_row + header_rows - 1).min(end_row); - if let Some(fill) = styles.table_header_fills.get(style_name).copied() { - apply_table_fill_layer(rows, start_col, end_col, start_row, header_end, fill); - } - if let Some(font) = direct_header_font { - apply_table_font_layer(rows, start_col, end_col, start_row, header_end, font); - } - if let Some(font) = styles.table_header_fonts.get(style_name).copied() { - apply_table_font_layer(rows, start_col, end_col, start_row, header_end, font); - } - } - if total_rows > 0 { - if let Some(fill) = styles.table_total_fills.get(style_name).copied() { - apply_table_fill_layer(rows, start_col, end_col, total_start, end_row, fill); - } - if let Some(font) = styles.table_total_fonts.get(style_name).copied() { - apply_table_font_layer(rows, start_col, end_col, total_start, end_row, font); - } - if let Some(font) = direct_total_font { - apply_table_font_layer(rows, start_col, end_col, total_start, end_row, font); - } - } - if let Some(borders) = styles.table_whole_borders.get(style_name).copied() { - apply_table_border_layer(rows, start_col, end_col, start_row, end_row, borders); - } - if header_rows > 0 { - if let Some(borders) = styles.table_header_borders.get(style_name).copied() { - apply_table_border_layer( - rows, - start_col, - end_col, - start_row, - (start_row + header_rows - 1).min(end_row), - borders, - ); - } - } - if total_rows > 0 { - if let Some(borders) = styles.table_total_borders.get(style_name).copied() { - apply_table_border_layer( - rows, - start_col, - end_col, - (end_row + 1).saturating_sub(total_rows).max(start_row), - end_row, - borders, - ); - } - } - let base_fill = styles.table_base_fills.get(style_name).copied(); - let stripe = style_info - .attribute("showRowStripes") - .is_some_and(|value| matches!(value, "1" | "true")) - .then(|| styles.table_first_row_stripes.get(style_name).copied()) - .flatten(); - for row in rows - .iter_mut() - .filter(|row| row.index >= data_start && row.index <= end_row) - { - if row.cells.len() <= end_col { - row.cells.resize(end_col + 1, CellData::default()); - } - let fill = stripe - .filter(|(_, size)| ((row.index - data_start) / size) % 2 == 0) - .map(|(fill, _)| fill) - .or(base_fill); - let Some(fill) = fill else { - continue; - }; - for cell in &mut row.cells[start_col..=end_col] { - cell.style.fill_color = Some(fill); - } - } - } - Ok(()) -} - -fn apply_table_fill_layer( - rows: &mut [RowData], - start_col: usize, - end_col: usize, - start_row: usize, - end_row: usize, - fill: PdfColor, -) { - for row in rows - .iter_mut() - .filter(|row| row.index >= start_row && row.index <= end_row) - { - if row.cells.len() <= end_col { - row.cells.resize(end_col + 1, CellData::default()); - } - for cell in &mut row.cells[start_col..=end_col] { - cell.style.fill_color = Some(fill); - } - } -} - -fn apply_table_font_layer( - rows: &mut [RowData], - start_col: usize, - end_col: usize, - start_row: usize, - end_row: usize, - font: DifferentialFontStyle, -) { - for row in rows - .iter_mut() - .filter(|row| row.index >= start_row && row.index <= end_row) - { - if row.cells.len() <= end_col { - row.cells.resize(end_col + 1, CellData::default()); - } - for cell in &mut row.cells[start_col..=end_col] { - if let Some(bold) = font.bold { - cell.style.bold = bold; - } - if let Some(italic) = font.italic { - cell.style.italic = italic; - } - if let Some(strike) = font.strike { - cell.style.strike = strike; - } - if let Some(color) = font.color { - cell.style.font_color = color; - } - } - } -} - -fn apply_table_border_layer( - rows: &mut [RowData], - start_col: usize, - end_col: usize, - start_row: usize, - end_row: usize, - borders: TableBorders, -) { - for row in rows - .iter_mut() - .filter(|row| row.index >= start_row && row.index <= end_row) - { - if row.cells.len() <= end_col { - row.cells.resize(end_col + 1, CellData::default()); - } - for column in start_col..=end_col { - let cell_borders = &mut row.cells[column].style.borders; - if column == start_col { - cell_borders.left = borders.edges.left.or(cell_borders.left); - if borders.edges.left.is_some() { - cell_borders.left_width = borders.edges.left_width; - } - } else { - if let Some((color, width)) = borders.vertical { - cell_borders.left = Some(color); - cell_borders.left_width = width; - } - } - if column == end_col { - cell_borders.right = borders.edges.right.or(cell_borders.right); - if borders.edges.right.is_some() { - cell_borders.right_width = borders.edges.right_width; - } - } - if row.index == start_row { - cell_borders.top = borders.edges.top.or(cell_borders.top); - if borders.edges.top.is_some() { - cell_borders.top_width = borders.edges.top_width; - } - } else { - if let Some((color, width)) = borders.horizontal { - cell_borders.top = Some(color); - cell_borders.top_width = width; - } - } - if row.index == end_row { - cell_borders.bottom = borders.edges.bottom.or(cell_borders.bottom); - if borders.edges.bottom.is_some() { - cell_borders.bottom_width = borders.edges.bottom_width; - } - } - } - } -} - -fn excel_pdf_font_size(font_name: Option<&str>, size: f32) -> f32 { - match font_name.unwrap_or_default().to_ascii_lowercase().as_str() { - "corbel" => size * 0.962, - "franklin gothic medium" if size >= 30.0 => size * 0.984, - "franklin gothic medium" => size * 0.93, - "grandview" => size * 0.956, - "grandview display" if size >= 30.0 => size * 0.947, - "grandview display" => size * 0.956, - "palatino linotype" => size * 0.967, - "verdana" => size * 0.96, - _ => size, - } -} - -fn xlsx_preferred_font(font_name: Option<&str>) -> Option<&'static str> { - let normalized_name = font_name - .unwrap_or_default() - .chars() - .filter(|character| !character.is_whitespace()) - .flat_map(char::to_lowercase) - .collect::(); - match normalized_name.as_str() { - "arial" => Some("arial"), - "corbel" => Some("corbel"), - "franklingothicmedium" => Some("framd"), - "garamond" => Some("gara"), - "grandview" => Some("grandview"), - "grandviewdisplay" => Some("grandviewdisplay"), - "stkaiti" | "华文楷体" => Some("stkaiti"), - "kaiti" | "楷体" => Some("simkai"), - "palatinolinotype" => Some("bookos"), - "twcenmt" => Some("tcm_____"), - "verdana" => Some("verdana"), - _ => None, - } -} - -fn excel_max_digit_width(font_name: Option<&str>, size: f32) -> f32 { - let width_at_ten_points = match font_name.unwrap_or_default().to_ascii_lowercase().as_str() { - "arial" => 7.06, - "palatino linotype" => 6.42, - "verdana" => 7.55, - _ => 7.0, - }; - width_at_ten_points * size / 10.0 -} - -fn read_theme_colors( - archive: &mut ZipArchive, -) -> Result> { - let Some(theme_xml) = read_zip_text(archive, "xl/theme/theme1.xml")? else { - return Ok(Vec::new()); - }; - let document = roxmltree::Document::parse(&theme_xml)?; - let scheme_colors = document - .descendants() - .find(|node| node.has_tag_name("clrScheme")) - .map(|scheme| { - scheme - .children() - .filter(|node| node.is_element()) - .filter_map(|entry| { - let color = entry.children().find(|node| node.is_element())?; - color - .attribute("val") - .and_then(parse_rgb_color) - .or_else(|| color.attribute("lastClr").and_then(parse_rgb_color)) - }) - .collect::>() - }) - .unwrap_or_default(); - Ok(spreadsheet_theme_colors(&scheme_colors)) -} - -fn spreadsheet_theme_colors(scheme_colors: &[PdfColor]) -> Vec { - const INDEX_ORDER: [usize; 12] = [1, 0, 3, 2, 4, 5, 6, 7, 8, 9, 10, 11]; - INDEX_ORDER - .into_iter() - .filter_map(|index| scheme_colors.get(index).copied()) - .collect() -} - -fn parse_xlsx_color(node: roxmltree::Node<'_, '_>, theme_colors: &[PdfColor]) -> Option { - let color = node - .attribute("rgb") - .and_then(parse_rgb_color) - .or_else(|| { - node.attribute("theme") - .and_then(|value| value.parse::().ok()) - .and_then(|index| theme_colors.get(index).copied()) - }) - .or_else(|| { - node.attribute("indexed") - .and_then(|value| value.parse::().ok()) - .and_then(indexed_color) - })?; - let tint = node - .attribute("tint") - .and_then(|value| value.parse::().ok()) - .unwrap_or(0.0) - .clamp(-1.0, 1.0); - Some(apply_color_tint(color, tint)) -} - -fn indexed_color(index: usize) -> Option { - match index % 8 { - 0 => Some(PdfColor::BLACK), - 1 => Some(PdfColor::new(1.0, 1.0, 1.0)), - 2 => Some(PdfColor::new(1.0, 0.0, 0.0)), - 3 => Some(PdfColor::new(0.0, 1.0, 0.0)), - 4 => Some(PdfColor::new(0.0, 0.0, 1.0)), - 5 => Some(PdfColor::new(1.0, 1.0, 0.0)), - 6 => Some(PdfColor::new(1.0, 0.0, 1.0)), - 7 => Some(PdfColor::new(0.0, 1.0, 1.0)), - _ => None, - } -} - -fn apply_color_tint(color: PdfColor, tint: f32) -> PdfColor { - if tint.abs() < f32::EPSILON { - return color; - } - let is_neutral = (color.r - color.g).abs() < 0.0001 && (color.g - color.b).abs() < 0.0001; - if is_neutral { - let channel = if tint < 0.0 { - color.r * (1.0 + tint) - } else { - color.r + (1.0 - color.r) * tint - }; - if tint < 0.0 { - if channel >= 0.9 { - return PdfColor::new(channel - 0.004, channel, channel - 0.004); - } - return PdfColor::new(channel, (channel + 0.001).min(1.0), channel); - } - return PdfColor::new(channel, channel, channel); - } - - let max = color.r.max(color.g).max(color.b); - let min = color.r.min(color.g).min(color.b); - let mut hue = 0.0; - let lightness = (max + min) / 2.0; - let delta = max - min; - let saturation = if delta == 0.0 { - 0.0 - } else if lightness <= 0.5 { - delta / (max + min) - } else { - delta / (2.0 - max - min) - }; - if delta != 0.0 { - hue = if max == color.r { - (color.g - color.b) / delta - } else if max == color.g { - 2.0 + (color.b - color.r) / delta - } else { - 4.0 + (color.r - color.g) / delta - } / 6.0; - if hue < 0.0 { - hue += 1.0; - } - } - let tinted_lightness = if tint < 0.0 { - lightness * (1.0 + tint) - } else { - lightness * (1.0 - tint) + tint - }; - let hue_to_rgb = |mut component: f32| { - if component < 0.0 { - component += 1.0; - } else if component > 1.0 { - component -= 1.0; - } - let upper = if tinted_lightness < 0.5 { - tinted_lightness * (1.0 + saturation) - } else { - tinted_lightness + saturation - tinted_lightness * saturation - }; - let lower = 2.0 * tinted_lightness - upper; - if component * 6.0 < 1.0 { - lower + (upper - lower) * component * 6.0 - } else if component * 2.0 < 1.0 { - upper - } else if component * 3.0 < 2.0 { - lower + (upper - lower) * (2.0 / 3.0 - component) * 6.0 - } else { - lower - } - }; - PdfColor::new( - hue_to_rgb(hue + 1.0 / 3.0), - hue_to_rgb(hue), - hue_to_rgb(hue - 1.0 / 3.0), - ) -} - -fn font_name_is_emphasis(font_name: Option<&str>) -> bool { - font_name.is_some_and(|name| name.contains("黑体") || name.contains("小标宋")) -} - -fn parse_cell_borders(border: roxmltree::Node<'_, '_>, theme_colors: &[PdfColor]) -> CellBorders { - let side = |side_name: &str| { - let side = border - .children() - .find(|side| side.has_tag_name(side_name) && side.attribute("style").is_some()); - let color = side.map(|side| { - side.children() - .find(|node| node.has_tag_name("color")) - .and_then(|node| parse_xlsx_color(node, theme_colors)) - .unwrap_or(PdfColor::BLACK) - }); - let width = side - .and_then(|side| side.attribute("style")) - .map(border_style_width) - .unwrap_or(0.0); - let dotted = side.is_some_and(|side| side.attribute("style") == Some("dotted")); - (color, width, dotted) - }; - let (left, left_width, left_dotted) = side("left"); - let (right, right_width, right_dotted) = side("right"); - let (top, top_width, top_dotted) = side("top"); - let (bottom, bottom_width, bottom_dotted) = side("bottom"); - CellBorders { - left, - right, - top, - bottom, - left_width, - right_width, - top_width, - bottom_width, - left_dotted, - right_dotted, - top_dotted, - bottom_dotted, - } -} - -fn border_style_width(style: &str) -> f32 { - match style { - "hair" => 0.1, - "thin" | "dashed" | "dotted" => 0.5, - "medium" | "mediumDashed" | "mediumDashDot" | "mediumDashDotDot" => 1.0, - "thick" | "double" => 1.5, - _ => CELL_BORDER_WIDTH, - } -} - -fn parse_table_borders(border: roxmltree::Node<'_, '_>, theme_colors: &[PdfColor]) -> TableBorders { - let side = |side_name: &str| { - let side = border - .children() - .find(|side| side.has_tag_name(side_name) && side.attribute("style").is_some())?; - let color = side - .children() - .find(|node| node.has_tag_name("color")) - .and_then(|node| parse_xlsx_color(node, theme_colors)) - .unwrap_or(PdfColor::BLACK); - Some((color, border_style_width(side.attribute("style")?))) - }; - TableBorders { - edges: parse_cell_borders(border, theme_colors), - vertical: side("vertical"), - horizontal: side("horizontal"), - } -} - -fn merged_cell_borders(rows: &[RowData], merge_range: &MergeRange) -> CellBorders { - let cell_at = |row_index: usize, column_index: usize| { - rows.iter() - .find(|row| row.index == row_index) - .and_then(|row| row.cells.get(column_index)) - }; - CellBorders { - left: (merge_range.start_row..=merge_range.end_row).find_map(|row_index| { - cell_at(row_index, merge_range.start_col)? - .style - .borders - .left - }), - right: (merge_range.start_row..=merge_range.end_row) - .find_map(|row_index| cell_at(row_index, merge_range.end_col)?.style.borders.right), - top: (merge_range.start_col..=merge_range.end_col).find_map(|column_index| { - cell_at(merge_range.start_row, column_index)? - .style - .borders - .top - }), - bottom: (merge_range.start_col..=merge_range.end_col).find_map(|column_index| { - cell_at(merge_range.end_row, column_index)? - .style - .borders - .bottom - }), - left_width: cell_at(merge_range.start_row, merge_range.start_col) - .map(|cell| cell.style.borders.left_width) - .unwrap_or(0.0), - right_width: cell_at(merge_range.start_row, merge_range.end_col) - .map(|cell| cell.style.borders.right_width) - .unwrap_or(0.0), - top_width: cell_at(merge_range.start_row, merge_range.start_col) - .map(|cell| cell.style.borders.top_width) - .unwrap_or(0.0), - bottom_width: cell_at(merge_range.end_row, merge_range.start_col) - .map(|cell| cell.style.borders.bottom_width) - .unwrap_or(0.0), - left_dotted: cell_at(merge_range.start_row, merge_range.start_col) - .is_some_and(|cell| cell.style.borders.left_dotted), - right_dotted: cell_at(merge_range.start_row, merge_range.end_col) - .is_some_and(|cell| cell.style.borders.right_dotted), - top_dotted: cell_at(merge_range.start_row, merge_range.start_col) - .is_some_and(|cell| cell.style.borders.top_dotted), - bottom_dotted: cell_at(merge_range.end_row, merge_range.start_col) - .is_some_and(|cell| cell.style.borders.bottom_dotted), - } -} - -fn merged_cell_render_row(merge_range: &MergeRange, page_start_row: usize) -> Option { - let render_row = merge_range.start_row.max(page_start_row); - (render_row <= merge_range.end_row).then_some(render_row) -} - -fn parse_rgb_color(value: &str) -> Option { - let rgb = value.get(value.len().checked_sub(6)?..)?; - let number = u32::from_str_radix(rgb, 16).ok()?; - Some(PdfColor::new( - ((number >> 16) & 0xff) as f32 / 255.0, - ((number >> 8) & 0xff) as f32 / 255.0, - (number & 0xff) as f32 / 255.0, - )) -} - -fn parse_horizontal_alignment(value: Option<&str>) -> HorizontalAlignment { - match value { - Some("left") => HorizontalAlignment::Left, - Some("center") => HorizontalAlignment::Center, - Some("right") => HorizontalAlignment::Right, - _ => HorizontalAlignment::General, - } -} - -fn parse_vertical_alignment(value: Option<&str>) -> VerticalAlignment { - match value { - Some("top") => VerticalAlignment::Top, - Some("center") => VerticalAlignment::Center, - _ => VerticalAlignment::Bottom, - } -} - -fn is_stacked_text(text_rotation: Option<&str>) -> bool { - text_rotation == Some("255") -} - -fn should_use_kaiti_fallback(text: &str, style: CellStyle) -> bool { - style.preferred_font == Some("simkai") && style.stacked_text && !text.is_empty() -} - -fn is_kaiti_slash_date(text: &str, style: CellStyle) -> bool { - style.preferred_font == Some("simkai") - && text.matches('/').count() == 2 - && text - .chars() - .all(|character| character.is_ascii_digit() || character == '/') -} - -fn read_shared_strings( - archive: &mut ZipArchive, -) -> Result> { - let Some(shared_xml) = read_zip_text(archive, "xl/sharedStrings.xml")? else { - return Ok(Vec::new()); - }; - let xml = roxmltree::Document::parse(&shared_xml)?; - let strings = xml - .descendants() - .filter(|node| node.has_tag_name("si")) - .map(|si| { - si.descendants() - .filter(|node| node.has_tag_name("t")) - .filter_map(|node| node.text()) - .collect::() - }) - .collect(); - Ok(strings) -} - -fn read_sheet_paths( - archive: &mut ZipArchive, -) -> Result> { - let rels = read_workbook_relationships(archive)?; - let Some(workbook_xml) = read_zip_text(archive, "xl/workbook.xml")? else { - return Ok(Vec::new()); - }; - let workbook = roxmltree::Document::parse(&workbook_xml)?; - let mut result = Vec::new(); - - for (index, sheet) in workbook - .descendants() - .filter(|node| node.has_tag_name("sheet")) - .enumerate() - { - if matches!(sheet.attribute("state"), Some("hidden" | "veryHidden")) { - continue; - } - let name = sheet.attribute("name").unwrap_or("Sheet").to_owned(); - let rel_id = sheet - .attributes() - .find(|attr| attr.name() == "id") - .map(|attr| attr.value().to_owned()); - let path = rel_id - .and_then(|id| rels.get(&id).cloned()) - .unwrap_or_else(|| format!("xl/worksheets/sheet{}.xml", index + 1)); - result.push((name, normalize_xl_path(&path))); - } - - Ok(result) -} - -fn read_workbook_relationships( - archive: &mut ZipArchive, -) -> Result> { - let Some(rels_xml) = read_zip_text(archive, "xl/_rels/workbook.xml.rels")? else { - return Ok(HashMap::new()); - }; - let rels_doc = roxmltree::Document::parse(&rels_xml)?; - let mut rels = HashMap::new(); - for rel in rels_doc - .descendants() - .filter(|node| node.has_tag_name("Relationship")) - { - let Some(id) = rel.attribute("Id") else { - continue; - }; - let Some(target) = rel.attribute("Target") else { - continue; - }; - rels.insert(id.to_owned(), target.to_owned()); - } - Ok(rels) -} - -fn normalize_xl_path(path: &str) -> String { - let path = path.replace('\\', "/"); - if let Some(stripped) = path.strip_prefix('/') { - stripped.to_owned() - } else if path.starts_with("xl/") { - path - } else { - format!("xl/{path}") - } -} - -fn read_sheet_rows( - sheet_xml: &str, - shared_strings: &[String], - styles: &XlsxStyles, -) -> Result> { - let xml = roxmltree::Document::parse(sheet_xml)?; - let default_row_height = read_default_row_height(sheet_xml)?; - let column_styles = xml - .descendants() - .filter(|node| node.has_tag_name("col")) - .filter_map(|column| { - let start = column - .attribute("min")? - .parse::() - .ok()? - .checked_sub(1)?; - let end = column - .attribute("max") - .and_then(|value| value.parse::().ok()) - .and_then(|value| value.checked_sub(1)) - .unwrap_or(start); - let style = column - .attribute("style") - .and_then(|value| value.parse::().ok()) - .and_then(|style_id| styles.cells.get(style_id).copied())?; - Some((start, end, style)) - }) - .collect::>(); - let column_style = |column: usize| { - column_styles - .iter() - .find(|(start, end, _)| column >= *start && column <= *end) - .map(|(_, _, style)| *style) - .unwrap_or_default() - }; - let implicit_cell = |column: usize| CellData { - style: column_style(column), - ..CellData::default() - }; - let mut rows = Vec::new(); - - for row in xml.descendants().filter(|node| node.has_tag_name("row")) { - let row_index = row - .attribute("r") - .and_then(|value| value.parse::().ok()) - .and_then(|value| value.checked_sub(1)) - .unwrap_or(rows.len()); - let is_hidden = matches!(row.attribute("hidden"), Some("1" | "true")); - let height = if is_hidden { - 0.0 - } else { - row.attribute("ht") - .and_then(|value| value.parse::().ok()) - .filter(|value| *value > 0.0) - .unwrap_or(default_row_height) - }; - let has_custom_height = row.attribute("ht").is_some(); - let mut cells: Vec<(usize, CellData)> = Vec::new(); - for cell in row.children().filter(|node| node.has_tag_name("c")) { - let col = cell - .attribute("r") - .and_then(column_index_from_ref) - .unwrap_or(cells.len()); - let mut value = read_cell_value(cell, shared_strings, styles, column_style(col)); - let formula = cell - .children() - .find(|node| node.has_tag_name("f")) - .and_then(|node| node.text()); - let should_evaluate = value.text.is_empty() - || formula.is_some_and(|formula| formula.trim().eq_ignore_ascii_case("TODAY()")); - if let Some(number) = should_evaluate - .then(|| formula.and_then(|formula| evaluate_simple_formula(formula, &rows))) - .flatten() - { - value.text = format_numeric_value(number, "", value.style.number_format); - value.is_numeric = true; - } - cells.push((col, value)); - } - - let width = cells - .iter() - .map(|(col, _)| *col) - .max() - .map(|col| col + 1) - .unwrap_or(0); - let mut row_values = (0..width).map(implicit_cell).collect::>(); - for (col, value) in cells { - if let Some(slot) = row_values.get_mut(col) { - *slot = value; - } - } - if is_hidden || has_custom_height || row_values.iter().any(cell_is_visible) { - rows.push(RowData { - index: row_index, - height, - cells: row_values, - }); - } - } - - let column_count = rows.iter().map(|row| row.cells.len()).max().unwrap_or(0); - for row in &mut rows { - while row.cells.len() < column_count { - row.cells.push(implicit_cell(row.cells.len())); - } - } - if column_styles - .iter() - .any(|(_, _, style)| style.fill_color.is_some() || style.borders.any()) - { - let last_row = rows.last().map(|row| row.index).unwrap_or(0); - let mut existing_rows = rows.into_iter().peekable(); - let mut completed_rows = Vec::with_capacity(last_row + 1); - for row_index in 0..=last_row { - if existing_rows - .peek() - .is_some_and(|row| row.index == row_index) - { - completed_rows.push(existing_rows.next().expect("peeked row exists")); - } else { - completed_rows.push(RowData { - index: row_index, - height: default_row_height, - cells: (0..column_count).map(implicit_cell).collect(), - }); - } - } - rows = completed_rows; - } - - Ok(rows) -} - -fn trim_trailing_empty_rows(rows: &mut Vec, images: &[SheetImage]) { - let last_image_row = images.iter().map(|image| image.row).max(); - while rows.last().is_some_and(|row| { - let has_visible_cell = row.cells.iter().any(cell_is_visible); - !has_visible_cell && last_image_row.is_none_or(|image_row| row.index > image_row) - }) { - rows.pop(); - } -} - -fn cell_is_visible(cell: &CellData) -> bool { - !cell.text.is_empty() || cell.style.fill_color.is_some() || cell.style.borders.any() -} - -fn read_cell_value( - cell: roxmltree::Node<'_, '_>, - shared_strings: &[String], - styles: &XlsxStyles, - default_style: CellStyle, -) -> CellData { - let cell_type = cell.attribute("t"); - let style = cell - .attribute("s") - .and_then(|value| value.parse::().ok()) - .and_then(|style_id| styles.cells.get(style_id).copied()) - .unwrap_or(default_style); - if cell_type == Some("inlineStr") { - let text = cell - .descendants() - .filter(|node| node.has_tag_name("t")) - .filter_map(|node| node.text()) - .collect::(); - return CellData { - text, - is_numeric: false, - style, - }; - } - - let value = cell - .children() - .find(|node| node.has_tag_name("v")) - .and_then(|node| node.text()) - .unwrap_or(""); - - if cell_type == Some("s") { - let text = value - .parse::() - .ok() - .and_then(|index| shared_strings.get(index).cloned()) - .unwrap_or_default(); - return CellData { - text, - is_numeric: false, - style, - }; - } - - let numeric_value = matches!(cell_type, None | Some("n")) - .then(|| value.parse::().ok()) - .flatten(); - CellData { - text: numeric_value.map_or_else( - || value.to_owned(), - |number| format_numeric_value(number, value, style.number_format), - ), - is_numeric: numeric_value.is_some(), - style, - } -} - -fn format_numeric_value(value: f64, source: &str, number_format: NumberFormat) -> String { - match number_format { - NumberFormat::DateMonthDayYear => format_excel_date(value), - NumberFormat::DateDayShortMonthYear => format_excel_date_day_short_month_year(value), - NumberFormat::DateYearMonthDay => format_excel_date_year_month_day(value), - NumberFormat::PercentageZeroDecimals => format!("{:.0}%", value * 100.0), - NumberFormat::PercentageTwoDecimals => format!("{:.2}%", value * 100.0), - NumberFormat::ThousandsZeroDecimals => format_thousands_zero_decimals(value), - NumberFormat::ThousandsTwoDecimals => format_thousands_two_decimals(value), - NumberFormat::DollarTwoDecimals => { - if value.is_sign_negative() { - format!("-${}", format_thousands_two_decimals(value.abs())) - } else { - format!("${}", format_thousands_two_decimals(value)) - } - } - NumberFormat::DollarAccounting => { - if value == 0.0 { - "$ -".to_owned() - } else if value.is_sign_negative() { - format!("$ ({})", format_thousands_two_decimals(value.abs())) - } else { - format!("$ {}", format_thousands_two_decimals(value)) - } - } - NumberFormat::General - if !source.contains(['e', 'E']) - && source - .split_once('.') - .is_some_and(|(_, fraction)| fraction.len() >= 15) => - { - value.to_string() - } - NumberFormat::General if source.is_empty() => value.to_string(), - NumberFormat::General => source.to_owned(), - } -} - -fn format_excel_date(value: f64) -> String { - let (year, month, day) = excel_date_parts(value); - format!("{month}/{day}/{year}") -} - -fn format_excel_date_day_short_month_year(value: f64) -> String { - const MONTHS: [&str; 12] = [ - "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec", - ]; - let (year, month, day) = excel_date_parts(value); - let month_name = MONTHS[(month - 1) as usize]; - format!("{day:02}-{month_name}-{year:04}") -} - -fn format_excel_date_year_month_day(value: f64) -> String { - let (year, month, day) = excel_date_parts(value); - format!("{year:04}-{month:02}-{day:02}") -} - -fn excel_date_parts(value: f64) -> (i64, i64, i64) { - let mut days = value.floor() as i64 - 25_569; - days += 719_468; - let era = if days >= 0 { days } else { days - 146_096 } / 146_097; - let day_of_era = days - era * 146_097; - let year_of_era = - (day_of_era - day_of_era / 1_460 + day_of_era / 36_524 - day_of_era / 146_096) / 365; - let mut year = year_of_era + era * 400; - let day_of_year = day_of_era - (365 * year_of_era + year_of_era / 4 - year_of_era / 100); - let month_part = (5 * day_of_year + 2) / 153; - let day = day_of_year - (153 * month_part + 2) / 5 + 1; - let month = month_part + if month_part < 10 { 3 } else { -9 }; - year += i64::from(month <= 2); - (year, month, day) -} - -fn format_thousands_zero_decimals(value: f64) -> String { - let rounded = value.round() as i64; - let digits = rounded.unsigned_abs().to_string(); - let mut formatted = String::with_capacity(digits.len() + digits.len() / 3); - for (index, character) in digits.chars().enumerate() { - if index > 0 && (digits.len() - index) % 3 == 0 { - formatted.push(','); - } - formatted.push(character); - } - if rounded < 0 { - formatted.insert(0, '-'); - } - formatted -} - -fn evaluate_simple_formula(formula: &str, rows: &[RowData]) -> Option { - let formula = formula.trim(); - if formula.eq_ignore_ascii_case("TODAY()") { - return Some(excel_today_serial()); - } - if formula.len() >= 5 && formula[..4].eq_ignore_ascii_case("SUM(") && formula.ends_with(')') { - let (start, end) = formula[4..formula.len() - 1].split_once(':')?; - let (start_col, start_row) = cell_position(start)?; - let (end_col, end_row) = cell_position(end)?; - let mut total = 0.0; - for row in start_row.min(end_row)..=start_row.max(end_row) { - for col in start_col.min(end_col)..=start_col.max(end_col) { - total += numeric_cell_value(rows, col, row)?; - } - } - return Some(total); - } - - formula - .split('+') - .map(|cell_ref| { - let (col, row) = cell_position(cell_ref.trim())?; - numeric_cell_value(rows, col, row) - }) - .try_fold(0.0, |total, value| value.map(|value| total + value)) -} - -fn excel_today_serial() -> f64 { - let today = chrono::Local::now().date_naive(); - let excel_epoch = - chrono::NaiveDate::from_ymd_opt(1899, 12, 30).expect("Excel epoch is a valid date"); - today.signed_duration_since(excel_epoch).num_days() as f64 -} - -fn numeric_cell_value(rows: &[RowData], col: usize, row: usize) -> Option { - rows.iter() - .find(|candidate| candidate.index == row)? - .cells - .get(col)? - .text - .replace(',', "") - .parse() - .ok() -} - -fn format_thousands_two_decimals(value: f64) -> String { - let rounded = (value.abs() * 100.0 + 1e-9).round() / 100.0; - let formatted = format!("{rounded:.2}"); - let (integer, fraction) = formatted.split_once('.').unwrap_or((&formatted, "00")); - let mut grouped = String::with_capacity(formatted.len() + integer.len() / 3); - if value.is_sign_negative() { - grouped.push('-'); - } - for (index, character) in integer.chars().enumerate() { - if index > 0 && (integer.len() - index) % 3 == 0 { - grouped.push(','); - } - grouped.push(character); - } - grouped.push('.'); - grouped.push_str(fraction); - grouped -} - -#[cfg(test)] -fn wrap_cell_text( - text: &str, - max_width: f32, - font_size: f32, - bold: bool, - italic: bool, -) -> Vec { - wrap_cell_text_with_font(text, max_width, font_size, bold, italic, None) -} - -fn wrap_cell_text_with_font( - text: &str, - max_width: f32, - font_size: f32, - bold: bool, - italic: bool, - preferred_font: Option<&str>, -) -> Vec { - let mut lines = Vec::new(); - for paragraph in text.replace("\r\n", "\n").replace('\r', "\n").split('\n') { - if paragraph.is_empty() { - lines.push(String::new()); - continue; - } - let mut line = String::new(); - for character in paragraph.chars() { - let mut candidate = line.clone(); - candidate.push(character); - if !line.is_empty() - && styled_text_width_with_font(&candidate, font_size, bold, italic, preferred_font) - > max_width - { - if let Some(split_index) = line.rfind(char::is_whitespace) { - let remainder = line[split_index..].trim_start().to_owned(); - line.truncate(split_index); - lines.push(line.trim_end().to_owned()); - line = remainder; - line.push(character); - } else { - lines.push(line); - line = character.to_string(); - } - } else { - line = candidate; - } - } - lines.push(line); - } - lines -} - -fn cell_position(cell_ref: &str) -> Option<(usize, usize)> { - let cell_ref = cell_ref.strip_prefix('$').unwrap_or(cell_ref); - let column_length = cell_ref - .chars() - .take_while(|ch| ch.is_ascii_alphabetic()) - .count(); - if !(1..=3).contains(&column_length) { - return None; - } - let (column_ref, row_ref) = cell_ref.split_at(column_length); - let row_ref = row_ref.strip_prefix('$').unwrap_or(row_ref); - if row_ref.is_empty() || !row_ref.chars().all(|ch| ch.is_ascii_digit()) { - return None; - } - let col = column_index_from_ref(column_ref)?; - let row = row_ref.parse::().ok()?.checked_sub(1)?; - Some((col, row)) -} - -fn column_index_from_ref(cell_ref: &str) -> Option { - let mut col = 0usize; - let mut seen_letter = false; - for ch in cell_ref.chars().filter(|ch| ch.is_ascii_alphabetic()) { - seen_letter = true; - col = col - .checked_mul(26)? - .checked_add(ch.to_ascii_uppercase() as usize - 'A' as usize + 1)?; - } - seen_letter.then_some(col.saturating_sub(1)) -} - -fn render_xlsx(doc: &mut PdfDocument, sheets: &[SheetData], page_size_override: Option) { - let mut footer_ranges = Vec::new(); - for sheet in sheets { - let first_page = doc.pages().len(); - let image_ids = sheet - .images - .iter() - .map(|image| match &image.data { - SheetImageData::Jpeg(data) => { - doc.add_jpeg_image(data.clone(), image.pixel_width, image.pixel_height) - } - SheetImageData::Rgba(data) => { - doc.add_rgba_image(data.clone(), image.pixel_width, image.pixel_height) - } - }) - .collect::>(); - render_sheet( - doc, - sheet, - &image_ids, - page_size_override.unwrap_or(sheet.page_setup.page_size), - ); - if sheet.footer.is_some() && doc.pages().len() > first_page { - footer_ranges.push((first_page, doc.pages().len(), sheet)); - } - } - let total_pages = doc.pages().len(); - for (first_page, end_page, sheet) in footer_ranges { - if let Some(footer) = &sheet.footer { - render_sheet_footer( - doc, - footer, - first_page, - end_page, - total_pages, - sheet.page_setup.margin_left, - sheet.page_setup.margin_right, - ); - } - } -} - -fn render_sheet_footer( - doc: &mut PdfDocument, - footer: &SheetFooter, - first_page: usize, - end_page: usize, - total_pages: usize, - margin_left: f32, - margin_right: f32, -) { - let (left, center, right) = parse_header_footer_sections(&footer.format); - for page_index in first_page..end_page { - let page_number = page_index + 1; - let page = doc.page_mut(page_index).expect("page index is valid"); - for (section, alignment) in [ - (&left, HorizontalAlignment::Left), - (¢er, HorizontalAlignment::Center), - (&right, HorizontalAlignment::Right), - ] { - let (content, font_size, preferred_font) = - expand_header_footer_fields(section, page_number, total_pages); - let lines = content.lines().collect::>(); - for (line_index, line) in lines.iter().rev().enumerate() { - let line = line.trim(); - if line.is_empty() { - continue; - } - let text_width = - styled_text_width_with_font(line, font_size, false, false, preferred_font); - let x = match alignment { - HorizontalAlignment::Left | HorizontalAlignment::General => margin_left, - HorizontalAlignment::Center => (page.width - text_width) / 2.0, - HorizontalAlignment::Right => page.width - margin_right - text_width, - }; - let y = footer.margin + line_index as f32 * font_size * 1.3; - page.add_styled_text( - line, - x, - y, - font_size, - PdfTextStyle { - color: PdfColor::BLACK, - bold: false, - italic: false, - preferred_font, - }, - ); - } - } - } -} - -fn parse_header_footer_sections(format: &str) -> (String, String, String) { - let mut sections = [String::new(), String::new(), String::new()]; - let mut current = None; - let mut characters = format.chars().peekable(); - while let Some(character) = characters.next() { - if character == '&' { - let section = match characters.peek().copied() { - Some('L') => Some(0), - Some('C') => Some(1), - Some('R') => Some(2), - _ => None, - }; - if let Some(section) = section { - characters.next(); - current = Some(section); - continue; - } - } - if let Some(section) = current { - sections[section].push(character); - } - } - let [left, center, right] = sections; - (left, center, right) -} - -fn expand_header_footer_fields( - section: &str, - page_number: usize, - total_pages: usize, -) -> (String, f32, Option<&'static str>) { - let mut text = String::new(); - let mut font_size = 6.0; - let mut preferred_font = None; - let mut characters = section.chars().peekable(); - while let Some(character) = characters.next() { - if character != '&' { - text.push(character); - continue; - } - let Some(field) = characters.next() else { - break; - }; - match field { - 'P' => text.push_str(&page_number.to_string()), - 'N' => text.push_str(&total_pages.to_string()), - 'A' | 'D' => {} - '&' => text.push('&'), - '"' => { - let font = characters - .by_ref() - .take_while(|character| *character != '"') - .collect::(); - if font.to_ascii_lowercase().starts_with("arial,") { - preferred_font = Some("arial"); - } - } - digit if digit.is_ascii_digit() => { - let mut size = digit.to_digit(10).unwrap_or(6); - if let Some(next) = characters.peek().copied().filter(char::is_ascii_digit) { - characters.next(); - size = size * 10 + next.to_digit(10).unwrap_or(0); - } - font_size = size as f32; - } - _ => {} - } - } - (text, font_size, preferred_font) -} - -fn render_sheet( - doc: &mut PdfDocument, - sheet: &SheetData, - image_ids: &[usize], - mut page_size: PageSize, -) { - let column_count = rendered_column_count(sheet); - let mut widths = sheet.column_widths.clone(); - widths.resize(column_count, COL_WIDTH); - widths.truncate(column_count); - let unscaled_width = widths.iter().sum::(); - if sheet.page_setup.page_size_from_printer - && sheet.page_setup.fit_to_width - && sheet.page_setup.fit_to_height - { - let last_row = sheet.rows.last().map(|row| row.index).unwrap_or(0); - let unscaled_height = (0..=last_row) - .map(|row_index| { - sheet - .rows - .iter() - .find(|row| row.index == row_index) - .map(|row| row.height) - .unwrap_or(sheet.default_row_height) - }) - .sum::(); - let required_width = unscaled_width * sheet.page_setup.print_scale - + sheet.page_setup.margin_left - + sheet.page_setup.margin_right; - let required_height = - unscaled_height * sheet.page_setup.print_scale * FIT_TO_PAGE_VERTICAL_SCALE - + sheet.page_setup.margin_top - + FIT_TO_PAGE_TOP_OFFSET - + sheet.page_setup.margin_bottom; - let media_scale = (required_width / page_size.width) - .max(required_height / page_size.height) - .max(1.0); - page_size.width *= media_scale; - page_size.height *= media_scale; - } - let usable_width = - page_size.width - sheet.page_setup.margin_left - sheet.page_setup.margin_right; - let mut content_scale = effective_content_scale( - unscaled_width, - usable_width, - sheet.page_setup.print_scale, - sheet.page_setup.fit_to_width, - ); - if sheet.page_setup.fit_to_height { - let last_row = sheet.rows.last().map(|row| row.index).unwrap_or(0); - let unscaled_height = (0..=last_row) - .map(|row_index| { - sheet - .rows - .iter() - .find(|row| row.index == row_index) - .map(|row| row.height) - .unwrap_or(sheet.default_row_height) - }) - .sum::(); - let vertical_scale = xlsx_vertical_scale(sheet, FIT_TO_PAGE_VERTICAL_SCALE); - let top_offset = if sheet.print_title_rows.is_some() { - 0.0 - } else { - FIT_TO_PAGE_TOP_OFFSET - }; - let usable_height = page_size.height - - sheet.page_setup.margin_top - - top_offset - - sheet.page_setup.margin_bottom; - if unscaled_height > 0.0 { - content_scale = - content_scale.min((usable_height / (unscaled_height * vertical_scale)).min(1.0)); - } - } - let horizontal_scale = xlsx_horizontal_scale(sheet); - let horizontal_geometry_scale = content_scale - * horizontal_scale - * if sheet.page_setup.horizontal_centered - && sheet.page_setup.vertical_centered - && sheet.page_setup.legacy_vml_drawing - { - CENTERED_VML_HORIZONTAL_SCALE - } else { - 1.0 - } - * if sheet.page_setup.o365_printer_fallback { - O365_PRINTER_FALLBACK_HORIZONTAL_SCALE - } else { - 1.0 - }; - for width in &mut widths { - *width *= horizontal_geometry_scale; - } - let content_width = widths.iter().sum::(); - let content_left = if sheet.page_setup.horizontal_centered && content_width < usable_width { - sheet.page_setup.margin_left + (usable_width - content_width) / 2.0 - - if sheet.print_title_rows.is_some() { - PRINT_TITLE_HORIZONTAL_OFFSET - } else if sheet.page_setup.fit_to_width { - FIT_TO_PAGE_HORIZONTAL_OFFSET - } else { - 0.0 - } - } else { - sheet.page_setup.margin_left + xlsx_left_offset(sheet) - }; - let vertical_scale = xlsx_vertical_scale( - sheet, - if sheet.page_setup.fit_to_width { - FIT_TO_PAGE_VERTICAL_SCALE - } else { - 1.0 - }, - ) * if sheet.page_setup.horizontal_centered - && sheet.page_setup.vertical_centered - && sheet.page_setup.legacy_vml_drawing - { - CENTERED_VML_VERTICAL_SCALE - } else { - 1.0 - } * if sheet.page_setup.o365_printer_fallback { - O365_PRINTER_FALLBACK_VERTICAL_SCALE - } else { - 1.0 - }; - let margin_top = if sheet.page_setup.o365_printer_fallback { - sheet - .page_setup - .margin_top - .max(O365_PRINTER_FALLBACK_TOP_MARGIN) - } else { - sheet.page_setup.margin_top - + if sheet.page_setup.fit_to_width { - FIT_TO_PAGE_TOP_OFFSET - } else { - 0.0 - } - }; - let margin_bottom = sheet.page_setup.margin_bottom; - let column_ranges = if sheet.page_setup.fit_to_width { - vec![(0, widths.len())] - } else { - column_groups(&widths, usable_width) - .into_iter() - .filter(|(start, end)| column_group_has_content(sheet, *start, *end)) - .collect() - }; - let layout = SheetRenderLayout { - page_size, - content_scale, - horizontal_geometry_scale, - content_left, - vertical_scale, - margin_top, - margin_bottom, - }; - - for (column_start, column_end) in column_ranges { - let horizontal_pages = single_column_text_pages( - sheet, - page_size.width - sheet.page_setup.margin_left, - content_scale, - ); - if horizontal_pages.is_empty() { - render_sheet_columns( - doc, - sheet, - image_ids, - &widths, - column_start, - column_end, - &layout, - ); - } else { - for horizontal_page in &horizontal_pages { - render_sheet_columns( - doc, - horizontal_page, - image_ids, - &widths, - column_start, - column_end, - &layout, - ); - } - } - } -} - -fn single_column_text_pages( - sheet: &SheetData, - page_clip_width: f32, - content_scale: f32, -) -> Vec { - if sheet.page_setup.fit_to_width - || rendered_column_count(sheet) != 1 - || !sheet.images.is_empty() - || !sheet.merges.is_empty() - || sheet.rows.iter().any(|row| { - row.cells.first().is_some_and(|cell| { - cell.is_numeric - || cell.style.wrap_text - || cell.style.stacked_text - || cell.style.horizontal_alignment == HorizontalAlignment::Right - || has_rtl_base_direction(&cell.text) - }) - }) - { - return Vec::new(); - } - - let chunks = sheet - .rows - .iter() - .map(|row| { - row.cells.first().map_or_else( - || vec![String::new()], - |cell| { - split_text_for_horizontal_pages( - &cell.text.replace(['\r', '\n'], " "), - page_clip_width, - cell.style.font_size * content_scale, - cell.style, - ) - }, - ) - }) - .collect::>(); - let page_count = chunks.iter().map(Vec::len).max().unwrap_or(1); - if page_count <= 1 { - return Vec::new(); - } - - (0..page_count) - .map(|page_index| { - let mut page = sheet.clone(); - for (row, row_chunks) in page.rows.iter_mut().zip(&chunks) { - if let Some(cell) = row.cells.first_mut() { - cell.text = row_chunks.get(page_index).cloned().unwrap_or_default(); - } - } - page - }) - .collect() -} - -fn split_text_for_horizontal_pages( - text: &str, - max_width: f32, - font_size: f32, - style: CellStyle, -) -> Vec { - if text.is_empty() { - return vec![String::new()]; - } - - let mut chunks = Vec::new(); - let mut chunk = String::new(); - for character in text.chars() { - chunk.push(character); - if chunk.chars().count() > 1 - && excel_fitting_text_width(&chunk, font_size, style.bold) > max_width - { - chunk.pop(); - chunks.push(std::mem::take(&mut chunk)); - chunk.push(character); - } - } - if !chunk.is_empty() { - chunks.push(chunk); - } - chunks -} - -fn excel_fitting_text_width(text: &str, font_size: f32, bold: bool) -> f32 { - text.chars() - .map(|character| helvetica_glyph_width(character, bold)) - .sum::() as f32 - * font_size - / 1000.0 - * CALIBRI_FITTING_SCALE -} - -fn rendered_column_count(sheet: &SheetData) -> usize { - let visible_cell_count = sheet - .rows - .iter() - .flat_map(|row| row.cells.iter().enumerate()) - .filter(|(_, cell)| cell_is_visible(cell)) - .map(|(column, _)| column + 1) - .max() - .unwrap_or(0); - let merged_column_count = sheet - .merges - .iter() - .filter(|merge| merge.start_col < visible_cell_count) - .map(|merge| merge.end_col + 1) - .max() - .unwrap_or(0); - let image_column_count = sheet - .images - .iter() - .map(|image| image.col + 1) - .max() - .unwrap_or(0); - visible_cell_count - .max(merged_column_count) - .max(image_column_count) - .max(1) -} - -fn column_group_has_content(sheet: &SheetData, column_start: usize, column_end: usize) -> bool { - sheet.rows.iter().any(|row| { - row.cells - .get(column_start..column_end.min(row.cells.len())) - .is_some_and(|cells| cells.iter().any(|cell| !cell.text.is_empty())) - }) || sheet - .images - .iter() - .any(|image| image.col >= column_start && image.col < column_end) -} - -fn xlsx_vertical_scale(sheet: &SheetData, fallback: f32) -> f32 { - if sheet.page_setup.fit_to_width && !sheet.page_setup.fit_to_height { - let calibration = if sheet.print_title_rows.is_some() { - PRINT_TITLE_WIDTH_ONLY_VERTICAL_SCALE - } else { - FIT_TO_WIDTH_ONLY_VERTICAL_SCALE - }; - let print_scale = if sheet.page_setup.print_scale < 1.0 { - sheet.page_setup.print_scale * FIT_TO_PAGE_VERTICAL_SCALE - } else { - sheet.page_setup.print_scale - }; - calibration * print_scale - } else if sheet.print_title_rows.is_some() { - if sheet.page_setup.page_size_from_printer || sheet.page_setup.print_scale < 1.0 { - 1.0 - } else { - PRINT_TITLE_VERTICAL_SCALE - } - } else if sheet.page_setup.page_size_from_printer && sheet.page_setup.fit_to_width { - 1.0 - } else { - fallback - } -} - -fn xlsx_horizontal_scale(sheet: &SheetData) -> f32 { - if sheet.print_title_rows.is_some() - && sheet.page_setup.print_scale < 1.0 - && !sheet.page_setup.fit_to_width - { - EXPLICIT_PRINT_TITLE_HORIZONTAL_SCALE - } else if sheet.print_title_rows.is_some() { - PRINT_TITLE_HORIZONTAL_SCALE - } else if sheet.page_setup.fit_to_width { - FIT_TO_PAGE_HORIZONTAL_SCALE - } else { - 1.0 - } -} - -fn xlsx_left_offset(sheet: &SheetData) -> f32 { - if sheet.print_title_rows.is_some() - && sheet.page_setup.print_scale < 1.0 - && !sheet.page_setup.fit_to_width - { - EXPLICIT_PRINT_TITLE_LEFT_OFFSET - } else if sheet.page_setup.o365_printer_fallback { - O365_PRINTER_FALLBACK_LEFT_OFFSET - } else { - 0.0 - } -} - -struct SheetRenderLayout { - page_size: PageSize, - content_scale: f32, - horizontal_geometry_scale: f32, - content_left: f32, - vertical_scale: f32, - margin_top: f32, - margin_bottom: f32, -} - -fn render_sheet_columns( - doc: &mut PdfDocument, - sheet: &SheetData, - image_ids: &[usize], - column_widths: &[f32], - column_start: usize, - column_end: usize, - layout: &SheetRenderLayout, -) { - let SheetRenderLayout { - page_size, - content_scale, - horizontal_geometry_scale, - content_left, - vertical_scale, - margin_top, - margin_bottom, - } = *layout; - let row_scale = content_scale * vertical_scale; - let automatic_breaks = automatic_row_breaks(sheet, page_size, row_scale); - let first_page_index = doc.pages().len(); - let mut page_index = first_page_index; - doc.add_page(page_size.width, page_size.height); - let mut y = page_size.height - margin_top; - let mut next_row_index = 0; - let mut page_ranges = Vec::new(); - let mut page_content_top = y; - let mut page_start_row = 0; - - for row in &sheet.rows { - let crossed_break = row_break_in_range( - &sheet.row_breaks, - &automatic_breaks, - next_row_index, - row.index, - ); - if let Some(break_index) = crossed_break.filter(|_| y < page_size.height - margin_top) { - page_ranges.push((page_index, page_content_top, y)); - page_index = doc.pages().len(); - doc.add_page(page_size.width, page_size.height); - y = page_size.height - margin_top; - page_content_top = y; - page_start_row = break_index; - repeat_print_title_rows( - doc, - sheet, - image_ids, - column_widths, - column_start, - column_end, - content_scale, - horizontal_geometry_scale, - content_left, - row_scale, - page_index, - &mut y, - break_index, - ); - for _ in break_index..row.index { - y -= sheet.default_row_height * row_scale; - } - } else { - for _ in next_row_index..row.index { - y -= sheet.default_row_height * row_scale; - } - } - - if row.height <= 0.0 { - next_row_index = row.index + 1; - continue; - } - - let row_height = row.height * row_scale; - - if sheet.print_title_rows.is_none() && y - row_height < margin_bottom { - page_ranges.push((page_index, page_content_top, y)); - page_index = doc.pages().len(); - doc.add_page(page_size.width, page_size.height); - y = page_size.height - margin_top; - page_content_top = y; - page_start_row = row.index; - repeat_print_title_rows( - doc, - sheet, - image_ids, - column_widths, - column_start, - column_end, - content_scale, - horizontal_geometry_scale, - content_left, - row_scale, - page_index, - &mut y, - row.index, - ); - } - y -= row_height; - - render_xlsx_row( - doc, - sheet, - image_ids, - column_widths, - column_start, - column_end, - content_scale, - horizontal_geometry_scale, - content_left, - row_scale, - page_index, - page_start_row, - y, - row, - ); - next_row_index = row.index + 1; - } - page_ranges.push((page_index, page_content_top, y)); - - let page = doc.page_mut(first_page_index).expect("page index is valid"); - for (image, image_id) in sheet.images.iter().zip(image_ids).filter(|(image, _)| { - image.foreground && image.col >= column_start && image.col < column_end - }) { - let centered_legacy_vml = image.legacy_vml - && sheet.page_setup.horizontal_centered - && sheet.page_setup.vertical_centered; - let image_anchor_horizontal_scale = if centered_legacy_vml { - horizontal_geometry_scale / CENTERED_VML_HORIZONTAL_SCALE - } else { - horizontal_geometry_scale - }; - let image_horizontal_scale = if centered_legacy_vml { - CENTERED_VML_IMAGE_HORIZONTAL_SCALE - } else { - 1.0 - }; - let image_width = image.width * image_anchor_horizontal_scale * image_horizontal_scale; - let x = content_left - + column_widths[column_start..image.col].iter().sum::() - * image_anchor_horizontal_scale - / horizontal_geometry_scale - + image.col_offset * image_anchor_horizontal_scale - - image.width * image_anchor_horizontal_scale * (image_horizontal_scale - 1.0) / 2.0; - let rows_above = (0..image.row) - .map(|row_index| { - sheet - .rows - .iter() - .find(|row| row.index == row_index) - .map(|row| row.height) - .unwrap_or(sheet.default_row_height) - }) - .sum::(); - let top = - page_size.height - margin_top - rows_above * row_scale - image.row_offset * row_scale - + GROUP_DRAWING_TOP_OFFSET; - let image_vertical_scale = if centered_legacy_vml { - CENTERED_VML_IMAGE_VERTICAL_SCALE - } else { - 1.0 - }; - let image_height = image.height * row_scale * image_vertical_scale; - let image_vertical_offset = if centered_legacy_vml { - CENTERED_VML_IMAGE_VERTICAL_OFFSET - + image.height * row_scale * (image_vertical_scale - 1.0) / 2.0 - } else { - 0.0 - }; - page.add_image( - *image_id, - x, - top - image.height * row_scale - image_vertical_offset, - image_width, - image_height, - ); - } - - if sheet.page_setup.vertical_centered { - let printable_top = page_size.height - margin_top; - for (page_index, content_top, content_bottom) in page_ranges { - let content_height = content_top - content_bottom; - let printable_height = printable_top - margin_bottom; - if content_height >= printable_height { - continue; - } - let offset = (margin_bottom + printable_top - content_bottom - content_top) / 2.0; - if offset.abs() >= 0.01 { - doc.page_mut(page_index) - .expect("page index is valid") - .translate_y(offset); - } - } - } -} - -fn row_break_in_range( - manual_breaks: &[usize], - automatic_breaks: &[usize], - start_row: usize, - end_row: usize, -) -> Option { - manual_breaks - .iter() - .chain(automatic_breaks) - .copied() - .filter(|row| *row >= start_row && *row <= end_row) - .min() -} - -fn automatic_row_breaks(sheet: &SheetData, page_size: PageSize, row_scale: f32) -> Vec { - const PRINT_BOTTOM_RESERVE: f32 = 1.0; - let Some((title_start, title_end)) = sheet.print_title_rows else { - return Vec::new(); - }; - let title_height = (title_start..=title_end) - .map(|row_index| { - sheet - .rows - .iter() - .find(|row| row.index == row_index) - .map(|row| row.height) - .unwrap_or(sheet.default_row_height) - * row_scale - }) - .sum::(); - let mut breaks = Vec::new(); - let mut y = page_size.height - sheet.page_setup.margin_top; - let last_row = sheet.rows.last().map(|row| row.index).unwrap_or(0); - for row_index in 0..=last_row { - if sheet.row_breaks.contains(&row_index) - && y < page_size.height - sheet.page_setup.margin_top - { - y = page_size.height - sheet.page_setup.margin_top - title_height; - } - let row_height = sheet - .rows - .iter() - .find(|row| row.index == row_index) - .map(|row| row.height) - .unwrap_or(sheet.default_row_height) - * row_scale; - if y - row_height < sheet.page_setup.margin_bottom + PRINT_BOTTOM_RESERVE { - breaks.push(row_index); - y = page_size.height - sheet.page_setup.margin_top - title_height; - } - y -= row_height; - } - breaks -} - -#[allow(clippy::too_many_arguments)] -fn repeat_print_title_rows( - doc: &mut PdfDocument, - sheet: &SheetData, - image_ids: &[usize], - column_widths: &[f32], - column_start: usize, - column_end: usize, - content_scale: f32, - horizontal_geometry_scale: f32, - content_left: f32, - row_scale: f32, - page_index: usize, - y: &mut f32, - current_row_index: usize, -) { - let Some((title_start, title_end)) = sheet.print_title_rows else { - return; - }; - if current_row_index <= title_end { - return; - } - for title_row_index in title_start..=title_end { - let row = sheet - .rows - .iter() - .find(|candidate| candidate.index == title_row_index); - let row_height = row - .map(|row| row.height) - .unwrap_or(sheet.default_row_height) - * row_scale; - *y -= row_height; - if let Some(row) = row { - render_xlsx_row( - doc, - sheet, - image_ids, - column_widths, - column_start, - column_end, - content_scale, - horizontal_geometry_scale, - content_left, - row_scale, - page_index, - title_start, - *y, - row, - ); - } - } -} - -#[allow(clippy::too_many_arguments)] -fn render_xlsx_row( - doc: &mut PdfDocument, - sheet: &SheetData, - image_ids: &[usize], - column_widths: &[f32], - column_start: usize, - column_end: usize, - content_scale: f32, - horizontal_geometry_scale: f32, - content_left: f32, - row_scale: f32, - page_index: usize, - page_start_row: usize, - y: f32, - row: &RowData, -) { - let row_height = row.height * row_scale; - - let page = doc.page_mut(page_index).expect("page index is valid"); - - struct PendingCellText { - cell_x: f32, - cell_y: f32, - cell_width: f32, - cell_height: f32, - clip_x: f32, - clip_width: f32, - should_clip: bool, - lines: Vec, - font_size: f32, - indent_width: f32, - style: CellStyle, - has_border: bool, - is_multi_row_merge: bool, - align_right: bool, - accounting_value: Option, - } - - for (image, image_id) in sheet.images.iter().zip(image_ids).filter(|(image, _)| { - !image.foreground - && image.row == row.index - && image.col >= column_start - && image.col < column_end - }) { - let x = content_left - + column_widths[column_start..image.col].iter().sum::() - + image.col_offset * horizontal_geometry_scale; - let image_height = image.height * row_scale; - let top = y + row_height - image.row_offset * row_scale; - page.add_image( - *image_id, - x, - top - image_height, - image.width * horizontal_geometry_scale, - image_height, - ); - } - - let mut cell_x = content_left; - let mut pending_text = Vec::new(); - let empty_cell = CellData::default(); - for column_index in column_start..column_end { - let merge = sheet.merges.iter().find(|merge| { - merge.start_row <= row.index - && merge.end_row >= row.index - && merge.start_col <= column_index - && merge.end_col >= column_index - }); - if merge - .is_some_and(|merge| merged_cell_render_row(merge, page_start_row) != Some(row.index)) - { - cell_x += column_widths[column_index]; - continue; - } - if merge.is_some_and(|merge| column_index > merge.start_col && column_index != column_start) - { - cell_x += column_widths[column_index]; - continue; - } - let source_column = merge.map(|merge| merge.start_col).unwrap_or(column_index); - let is_merge_continuation = merge.is_some_and(|merge| merge.start_row < page_start_row); - let source_row = merge - .filter(|_| is_merge_continuation) - .and_then(|merge| { - sheet - .rows - .iter() - .find(|candidate| candidate.index == merge.start_row) - }) - .unwrap_or(row); - let cell = source_row.cells.get(source_column).unwrap_or(&empty_cell); - if is_merge_continuation && cell.text.is_empty() && cell.style.fill_color.is_none() { - cell_x += column_widths[column_index]; - continue; - } - let merge_end = merge - .map(|merge| (merge.end_col + 1).min(column_end)) - .unwrap_or(column_index + 1); - let cell_width = column_widths[column_index..merge_end].iter().sum::(); - let cell_height = merge - .map(|merge| { - (merge.start_row.max(page_start_row)..=merge.end_row) - .map(|row_index| { - sheet - .rows - .iter() - .find(|candidate| candidate.index == row_index) - .map(|candidate| candidate.height) - .unwrap_or(sheet.default_row_height) - * row_scale - }) - .sum::() - }) - .unwrap_or(row_height); - let cell_y = y - (cell_height - row_height); - let cell_borders = merge - .map(|merge_range| merged_cell_borders(&sheet.rows, merge_range)) - .unwrap_or(cell.style.borders); - let border_scale = if sheet.page_setup.o365_printer_fallback { - O365_PRINTER_FALLBACK_BORDER_SCALE - } else { - 1.0 - }; - if let Some(fill) = cell.style.fill_color { - let previous_cell = column_index - .checked_sub(1) - .filter(|_| column_index > column_start) - .and_then(|index| row.cells.get(index)); - let next_cell = row.cells.get(merge_end); - let extend_left = cell_borders.left.is_none() - && previous_cell.is_some_and(|previous| { - previous.style.fill_color == Some(fill) - && previous.style.borders.right.is_none() - }); - let extend_fill = merge_end == column_end - || next_cell.is_some_and(|next| next.style.fill_color == Some(fill)); - page.add_rect( - cell_x - if extend_left { CELL_BORDER_WIDTH } else { 0.0 }, - cell_y, - cell_width - + if extend_left { CELL_BORDER_WIDTH } else { 0.0 } - + if extend_fill { CELL_BORDER_WIDTH } else { 0.0 }, - cell_height, - fill, - ); - } - if let Some(border) = cell_borders.bottom { - let border_width = cell_borders.bottom_width.max(0.1) * border_scale; - let position_offset = if border_width <= 0.5 { 0.6 } else { 0.0 }; - if cell_borders.bottom_dotted { - page.add_dashed_line( - cell_x, - cell_y, - cell_x + cell_width, - cell_y, - border, - border_width, - ); - } else { - page.add_rect( - cell_x, - cell_y - border_width / 2.0 + position_offset, - cell_width, - border_width, - border, - ); - } - } - if let Some(border) = cell_borders.top { - let border_width = cell_borders.top_width.max(0.1) * border_scale; - let position_offset = if border_width <= 0.5 { 0.6 } else { 0.0 }; - if cell_borders.top_dotted { - page.add_dashed_line( - cell_x, - cell_y + cell_height, - cell_x + cell_width, - cell_y + cell_height, - border, - border_width, - ); - } else { - page.add_rect( - cell_x, - cell_y + cell_height - border_width / 2.0 + position_offset, - cell_width, - border_width, - border, - ); - } - } - if let Some(border) = cell_borders.left { - let border_width = cell_borders.left_width.max(0.1) * border_scale; - let position_offset = if border_width <= 0.5 { 0.4 } else { 0.0 }; - if cell_borders.left_dotted { - page.add_dashed_line( - cell_x, - cell_y, - cell_x, - cell_y + cell_height, - border, - border_width, - ); - } else { - page.add_rect( - cell_x - border_width / 2.0 - position_offset, - cell_y, - border_width, - cell_height, - border, - ); - } - } - if let Some(border) = cell_borders.right { - let border_width = cell_borders.right_width.max(0.1) * border_scale; - let position_offset = if border_width <= 0.5 { 0.4 } else { 0.0 }; - if cell_borders.right_dotted { - page.add_dashed_line( - cell_x + cell_width, - cell_y, - cell_x + cell_width, - cell_y + cell_height, - border, - border_width, - ); - } else { - page.add_rect( - cell_x + cell_width - border_width / 2.0 - position_offset, - cell_y, - border_width, - cell_height, - border, - ); - } - } - let font_scale = if sheet.page_setup.o365_printer_fallback { - O365_PRINTER_FALLBACK_FONT_SCALE - } else { - 1.0 - }; - let mut text_style = cell.style; - let wrap_padding = if is_kaiti_slash_date(&cell.text, text_style) { - 0.0 - } else if text_style.preferred_font == Some("stkaiti") { - 3.0 - } else { - 6.0 - }; - if text_style.preferred_font == Some("simkai") - && !should_use_kaiti_fallback(&cell.text, text_style) - { - text_style.preferred_font = None; - } - let font_size = text_style.font_size * content_scale * font_scale; - let indent_width = styled_text_width_with_font( - &"000".repeat(text_style.indent as usize), - CELL_FONT_SIZE * content_scale * font_scale, - false, - false, - None, - ); - let rendered_text = if is_merge_continuation { - "" - } else { - &cell.text - }; - let text = if merge.is_some_and(|merge| merge.start_col < column_start) { - String::new() - } else { - rendered_text.replace(['\r', '\n'], " ") - }; - let align_right = cell.is_numeric || has_rtl_base_direction(rendered_text); - let overflows_left = text_style.horizontal_alignment == HorizontalAlignment::Right - || (text_style.horizontal_alignment == HorizontalAlignment::General && align_right); - let (clip_offset, clip_width, overflow_is_blocked) = if merge.is_none() { - text_overflow_region( - sheet, - row, - column_widths, - column_start, - column_index, - column_end, - overflows_left, - ) - } else { - (0.0, cell_width, false) - }; - let lines = if text_style.stacked_text { - rendered_text - .replace("\r\n", "\n") - .replace('\r', "\n") - .split('\n') - .map(str::to_owned) - .collect() - } else if text_style.wrap_text { - wrap_cell_text_with_font( - rendered_text, - (cell_width - wrap_padding - indent_width).max(1.0), - font_size, - text_style.bold, - text_style.italic, - text_style.preferred_font, - ) - } else { - vec![text] - }; - let max_text_width = if text_style.stacked_text { - font_size * 1.2 * lines.len() as f32 - } else { - lines - .iter() - .map(|line| { - styled_text_width_with_font( - line, - font_size, - text_style.bold, - text_style.italic, - text_style.preferred_font, - ) - }) - .fold(0.0, f32::max) - }; - let should_clip = - text_style.wrap_text || (max_text_width > clip_width && overflow_is_blocked); - pending_text.push(PendingCellText { - cell_x, - cell_y, - cell_width, - cell_height, - clip_x: if text_style.wrap_text { - cell_x - } else { - cell_x + clip_offset - }, - clip_width: if text_style.wrap_text { - cell_width - } else { - clip_width - }, - should_clip, - lines, - font_size, - indent_width, - style: text_style, - has_border: cell_borders.any(), - is_multi_row_merge: cell_height > row_height + 0.1, - align_right, - accounting_value: matches!(cell.style.number_format, NumberFormat::DollarAccounting) - .then(|| rendered_text.strip_prefix("$ ").map(str::to_owned)) - .flatten(), - }); - cell_x += column_widths[column_index]; - } - - for text in pending_text { - if text.should_clip { - page.push_clip(text.clip_x, text.cell_y, text.clip_width, text.cell_height); - } - let line_height = text.font_size * 1.2; - let line_count = text.lines.len(); - let block_height = if text.style.stacked_text { - text.lines - .iter() - .map(|line| line.chars().count()) - .max() - .unwrap_or(0) as f32 - * line_height - } else { - line_height * line_count as f32 - }; - let baseline_offset = text.font_size * 0.2; - let lowest_baseline = match text.style.vertical_alignment { - VerticalAlignment::Top => { - text.cell_y + (text.cell_height - block_height).max(0.0) + baseline_offset - } - VerticalAlignment::Center => { - text.cell_y + (text.cell_height - block_height).max(0.0) / 2.0 + baseline_offset - } - VerticalAlignment::Bottom => text.cell_y + baseline_offset.max(1.0), - } + match text.style.preferred_font { - Some("framd") => 0.9, - Some("grandview" | "grandviewdisplay") => 0.6, - _ => 0.0, - } + if sheet.page_setup.o365_printer_fallback && text.has_border { - match (text.style.vertical_alignment, text.is_multi_row_merge) { - (VerticalAlignment::Top, _) => 0.15, - (VerticalAlignment::Center, false) => 0.45, - (VerticalAlignment::Center, true) => 0.9, - (VerticalAlignment::Bottom, false) => 1.7, - (VerticalAlignment::Bottom, true) => 0.85, - } - } else { - 0.0 - }; - if let Some(value) = text.accounting_value { - let text_y = lowest_baseline; - page.add_styled_text( - "$", - text.cell_x + 3.0, - text_y, - text.font_size, - PdfTextStyle { - color: text.style.font_color, - bold: text.style.bold, - italic: text.style.italic, - preferred_font: text.style.preferred_font, - }, - ); - let value_width = styled_text_width_with_font( - &value, - text.font_size, - text.style.bold, - text.style.italic, - text.style.preferred_font, - ); - page.add_styled_text( - value, - text.cell_x + text.cell_width - value_width - 3.0, - text_y, - text.font_size, - PdfTextStyle { - color: text.style.font_color, - bold: text.style.bold, - italic: text.style.italic, - preferred_font: text.style.preferred_font, - }, - ); - if text.should_clip { - page.pop_clip(); - } - continue; - } - if text.style.stacked_text { - let column_count = text.lines.len(); - let block_width = line_height * column_count as f32; - let block_x = match text.style.horizontal_alignment { - HorizontalAlignment::Center | HorizontalAlignment::General => { - text.cell_x + (text.cell_width - block_width).max(0.0) / 2.0 - } - HorizontalAlignment::Right => text.cell_x + text.cell_width - block_width - 3.0, - HorizontalAlignment::Left => text.cell_x + 3.0, - }; - for (column_index, column) in text.lines.into_iter().enumerate() { - let characters = column.chars().collect::>(); - let column_height = line_height * characters.len() as f32; - let lowest_column_baseline = match text.style.vertical_alignment { - VerticalAlignment::Top => { - text.cell_y + (text.cell_height - column_height).max(0.0) + baseline_offset - } - VerticalAlignment::Center => { - text.cell_y - + (text.cell_height - column_height).max(0.0) / 2.0 - + baseline_offset - } - VerticalAlignment::Bottom => text.cell_y + baseline_offset.max(1.0), - }; - let column_x = block_x + (column_count - column_index - 1) as f32 * line_height; - for (character_index, character) in characters.iter().enumerate() { - let character = character.to_string(); - let character_width = styled_text_width_with_font( - &character, - text.font_size, - text.style.bold, - text.style.italic, - text.style.preferred_font, - ); - page.add_styled_text( - character, - column_x + (line_height - character_width).max(0.0) / 2.0, - lowest_column_baseline - + (characters.len() - character_index - 1) as f32 * line_height, - text.font_size, - PdfTextStyle { - color: text.style.font_color, - bold: text.style.bold, - italic: text.style.italic, - preferred_font: text.style.preferred_font, - }, - ); - } - } - if text.should_clip { - page.pop_clip(); - } - continue; - } - for (line_index, line) in text.lines.into_iter().enumerate() { - let text_width = styled_text_width_with_font( - &line, - text.font_size, - text.style.bold, - text.style.italic, - text.style.preferred_font, - ); - let x = match text.style.horizontal_alignment { - HorizontalAlignment::Center => { - text.cell_x + (text.cell_width - text_width).max(0.0) / 2.0 - } - HorizontalAlignment::Right => { - text.cell_x + text.cell_width - - text_width - - if text.indent_width > 0.0 { - text.indent_width - } else { - 3.0 - } - } - HorizontalAlignment::General if text.align_right => { - text.cell_x + text.cell_width - text_width - 3.0 - } - HorizontalAlignment::General | HorizontalAlignment::Left => { - text.cell_x - + if text.indent_width > 0.0 { - text.indent_width - } else { - 3.0 - } - } - }; - let text_y = lowest_baseline + (line_count - line_index - 1) as f32 * line_height; - page.add_styled_text( - &line, - x, - text_y, - text.font_size, - PdfTextStyle { - color: text.style.font_color, - bold: text.style.bold, - italic: text.style.italic, - preferred_font: text.style.preferred_font, - }, - ); - if text.style.strike && !line.is_empty() { - let strike_y = text_y + text.font_size * 0.32; - page.add_line( - x, - strike_y, - x + text_width, - strike_y, - text.style.font_color, - (text.font_size * 0.06).max(0.35), - ); - } - } - if text.should_clip { - page.pop_clip(); - } - } -} - -fn text_overflow_region( - sheet: &SheetData, - row: &RowData, - column_widths: &[f32], - column_start: usize, - column_index: usize, - column_end: usize, - overflows_left: bool, -) -> (f32, f32, bool) { - let mut offset = 0.0; - let mut width = column_widths[column_index]; - let columns: Box> = if overflows_left { - Box::new((column_start..column_index).rev()) - } else { - Box::new(column_index + 1..column_end) - }; - for adjacent_column in columns { - if cell_blocks_text_overflow(sheet, row, adjacent_column) { - return (offset, width, true); - } - let adjacent_width = column_widths[adjacent_column]; - width += adjacent_width; - if overflows_left { - offset -= adjacent_width; - } - } - (offset, width, false) -} - -fn cell_blocks_text_overflow(sheet: &SheetData, row: &RowData, column: usize) -> bool { - if row - .cells - .get(column) - .is_some_and(|cell| !cell.text.is_empty()) - { - return true; - } - sheet - .merges - .iter() - .find(|merge| { - merge.start_row <= row.index - && merge.end_row >= row.index - && merge.start_col <= column - && merge.end_col >= column - }) - .and_then(|merge| { - sheet - .rows - .iter() - .find(|candidate| candidate.index == merge.start_row) - .and_then(|origin| origin.cells.get(merge.start_col)) - }) - .is_some_and(|cell| !cell.text.is_empty()) -} - -fn has_rtl_base_direction(text: &str) -> bool { - text.chars() - .find_map(|character| match bidi_class(character) { - BidiClass::R | BidiClass::AL => Some(true), - BidiClass::L => Some(false), - _ => None, - }) - .unwrap_or(false) -} - -#[cfg(test)] -mod tests { - use std::collections::HashMap; - use std::io::{Cursor, Write}; - - use super::{ - apply_color_tint, apply_print_area, apply_sheet_conditional_formats, - apply_table_fill_layer, apply_table_font_layer, cell_position, column_group_has_content, - column_groups, column_index_from_ref, composite_rgba_background, effective_content_scale, - expand_header_footer_fields, font_name_is_emphasis, format_excel_date, - format_thousands_two_decimals, has_rtl_base_direction, indexed_color, jpeg_dimensions, - merged_cell_borders, parse_cell_borders, parse_conditional_text_search, - parse_header_footer_sections, parse_horizontal_alignment, parse_number_format, - parse_print_area, parse_rgb_color, parse_vertical_alignment, parse_vml_anchor, - parse_vml_crop, parse_vml_style_points, parse_windows_devmode_page_size, - read_column_widths, read_legacy_drawing_images, read_merge_ranges, read_page_setup, - read_row_breaks, read_sheet_footer, read_sheet_rows, read_two_cell_shape, relationship_id, - render_sheet, rendered_column_count, spreadsheet_theme_colors, text_overflow_region, - trim_trailing_empty_rows, wrap_cell_text, xlsx_horizontal_scale, xlsx_left_offset, - xlsx_vertical_scale, CellData, CellStyle, DifferentialFontStyle, HorizontalAlignment, - MergeRange, RowData, SheetData, SheetImage, SheetImageData, SheetPageSetup, - VerticalAlignment, XlsxStyles, COL_WIDTH, - }; - use crate::{PageSize, PdfColor, PdfDocument}; - use zip::write::SimpleFileOptions; - use zip::ZipArchive; - - #[test] - fn parses_excel_column_references() { - assert_eq!(column_index_from_ref("A1"), Some(0)); - assert_eq!(column_index_from_ref("Z9"), Some(25)); - assert_eq!(column_index_from_ref("AA10"), Some(26)); - } - - #[test] - fn rejects_non_a1_cell_references() { - assert_eq!(cell_position("$AA$10"), Some((26, 9))); - assert_eq!(cell_position("GroceryList[QTY]"), None); - assert_eq!(cell_position("SUM(A1:A2)"), None); - } - - #[test] - fn reads_legacy_vml_picture_geometry() { - let sheet_xml = r#""#; - let relationships_xml = r#""#; - let vml_xml = r#"1, 512, 2, 128, 3, 0, 4, 0"#; - let vml_relationships_xml = r#""#; - let image = image::RgbaImage::from_pixel(2, 1, image::Rgba([10, 20, 30, 255])); - let mut png = Cursor::new(Vec::new()); - image::DynamicImage::ImageRgba8(image) - .write_to(&mut png, image::ImageFormat::Png) - .unwrap(); - let mut output = Cursor::new(Vec::new()); - { - let mut writer = zip::ZipWriter::new(&mut output); - for (path, data) in [ - ( - "xl/worksheets/_rels/sheet1.xml.rels", - relationships_xml.as_bytes(), - ), - ("xl/drawings/vmlDrawing1.vml", vml_xml.as_bytes()), - ( - "xl/drawings/_rels/vmlDrawing1.vml.rels", - vml_relationships_xml.as_bytes(), - ), - ("xl/media/image1.png", png.get_ref()), - ] { - writer - .start_file(path, SimpleFileOptions::default()) - .unwrap(); - writer.write_all(data).unwrap(); - } - writer.finish().unwrap(); - } - let mut archive = ZipArchive::new(Cursor::new(output.into_inner())).unwrap(); - let sheet = roxmltree::Document::parse(sheet_xml).unwrap(); - - let images = read_legacy_drawing_images( - &mut archive, - "xl/worksheets/sheet1.xml", - &sheet, - &[10.0, 20.0], - &[RowData { - index: 2, - height: 30.0, - cells: Vec::new(), - }], - 15.0, - ) - .unwrap(); - - assert_eq!(images.len(), 1); - assert_eq!(images[0].col, 1); - assert_eq!(images[0].row, 2); - assert_eq!(images[0].col_offset, 10.0); - assert_eq!(images[0].row_offset, 15.0); - assert_eq!(images[0].width, 120.0); - assert_eq!(images[0].height, 60.0); - assert_eq!((images[0].pixel_width, images[0].pixel_height), (2, 1)); - } - - #[test] - fn parses_vml_anchor_and_point_sizes() { - assert_eq!( - parse_vml_anchor(" 0, 5, 29, 8, 24, 30, 38, 19 "), - Some([0, 5, 29, 8, 24, 30, 38, 19]) - ); - assert_eq!( - parse_vml_style_points("position:absolute; WIDTH:521.4PT; height:147pt", "width"), - Some(521.4) - ); - assert!((parse_vml_crop(Some("32768f")) - 0.5).abs() < f32::EPSILON); - } - - #[test] - fn parses_conditional_text_search() { - assert_eq!( - parse_conditional_text_search(r#"ISNUMBER(SEARCH("accept",$H$16))=TRUE"#), - Some((7, 15, "accept".to_owned())) - ); - } - - #[test] - fn parses_quoted_sheet_print_area() { - assert_eq!( - parse_print_area("'FRI report'!$A$2:$Y$310"), - Some(( - "FRI report".to_owned(), - MergeRange { - start_col: 0, - end_col: 24, - start_row: 1, - end_row: 309, - }, - )) - ); - } - - #[test] - fn clips_and_rebases_sheet_to_print_area() { - let mut rows = (0..3) - .map(|index| RowData { - index, - height: 15.0, - cells: vec![CellData::default(); 3], - }) - .collect(); - let mut images = Vec::new(); - let mut column_widths = vec![10.0, 20.0, 30.0]; - let mut merges = vec![MergeRange { - start_col: 0, - end_col: 2, - start_row: 0, - end_row: 2, - }]; - let mut row_breaks = vec![2]; - let mut print_title_rows = Some((0, 1)); - - apply_print_area( - &mut rows, - &mut images, - &mut column_widths, - &mut merges, - &mut row_breaks, - &mut print_title_rows, - MergeRange { - start_col: 1, - end_col: 2, - start_row: 1, - end_row: 2, - }, - ); - - assert_eq!(rows.iter().map(|row| row.index).collect::>(), [0, 1]); - assert!(rows.iter().all(|row| row.cells.len() == 2)); - assert_eq!(column_widths, [20.0, 30.0]); - assert_eq!( - merges, - [MergeRange { - start_col: 0, - end_col: 1, - start_row: 0, - end_row: 1, - }] - ); - assert_eq!(row_breaks, [1]); - assert_eq!(print_title_rows, Some((0, 0))); - } - - #[test] - fn defaults_unspecified_page_setup_to_a4() { - let page_setup = - read_page_setup("").expect("worksheet XML is valid"); - - assert_eq!(page_setup.page_size, PageSize::A4); - assert_eq!(page_setup.margin_left, super::MARGIN_X); - assert!(!page_setup.fit_to_width); - } - - #[test] - fn reads_letter_landscape_page_setup() { - let page_setup = read_page_setup( - r#""#, - ) - .expect("worksheet XML is valid"); - - assert_eq!(page_setup.page_size.width, PageSize::LETTER.height); - assert_eq!(page_setup.page_size.height, PageSize::LETTER.width); - } - - #[test] - fn reads_centered_legacy_vml_page_setup() { - let page_setup = read_page_setup( - r#""#, - ) - .expect("worksheet XML is valid"); - - assert!(page_setup.horizontal_centered); - assert!(page_setup.vertical_centered); - assert!(page_setup.legacy_vml_drawing); - } - - #[test] - fn reads_letter_landscape_from_windows_devmode() { - let mut devmode = vec![0_u8; 220]; - devmode[68..70].copy_from_slice(&220_u16.to_le_bytes()); - devmode[76..78].copy_from_slice(&2_u16.to_le_bytes()); - devmode[78..80].copy_from_slice(&1_u16.to_le_bytes()); - - let page_size = - parse_windows_devmode_page_size(&devmode).expect("DEVMODE contains a paper size"); - - assert_eq!(page_size.width, PageSize::LETTER.height); - assert_eq!(page_size.height, PageSize::LETTER.width); - } - - #[test] - fn ignores_trailing_columns_without_visible_content() { - let sheet = SheetData { - rows: vec![RowData { - index: 0, - height: 15.0, - cells: vec![ - CellData { - text: "Visible".to_owned(), - ..CellData::default() - }, - CellData::default(), - ], - }], - images: Vec::new(), - column_widths: vec![100.0, 500.0], - merges: Vec::new(), - row_breaks: Vec::new(), - default_row_height: 15.0, - print_title_rows: None, - page_setup: SheetPageSetup::default(), - footer: None, - }; - - assert_eq!(rendered_column_count(&sheet), 1); - } - - #[test] - fn keeps_printer_layout_rows_at_full_scale_with_print_titles() { - let mut sheet = SheetData { - rows: Vec::new(), - images: Vec::new(), - column_widths: Vec::new(), - merges: Vec::new(), - row_breaks: Vec::new(), - default_row_height: 15.0, - print_title_rows: Some((0, 3)), - page_setup: SheetPageSetup::default(), - footer: None, - }; - sheet.page_setup.page_size_from_printer = true; - - assert_eq!(xlsx_vertical_scale(&sheet, 0.75), 1.0); - } - - #[test] - fn keeps_explicit_print_scale_at_full_vertical_scale_with_print_titles() { - let mut sheet = SheetData { - rows: Vec::new(), - images: Vec::new(), - column_widths: Vec::new(), - merges: Vec::new(), - row_breaks: Vec::new(), - default_row_height: 15.0, - print_title_rows: Some((0, 9)), - page_setup: SheetPageSetup::default(), - footer: None, - }; - sheet.page_setup.print_scale = 0.95; - - assert_eq!(xlsx_vertical_scale(&sheet, 0.75), 1.0); - } - - #[test] - fn calibrates_horizontal_geometry_for_explicit_scale_with_print_titles() { - let mut sheet = SheetData { - rows: Vec::new(), - images: Vec::new(), - column_widths: Vec::new(), - merges: Vec::new(), - row_breaks: Vec::new(), - default_row_height: 15.0, - print_title_rows: Some((0, 9)), - page_setup: SheetPageSetup::default(), - footer: None, - }; - sheet.page_setup.print_scale = 0.95; - - assert_eq!(xlsx_horizontal_scale(&sheet), 0.9797); - assert_eq!(xlsx_left_offset(&sheet), 4.32); - - sheet.page_setup.fit_to_width = true; - - assert_eq!( - xlsx_horizontal_scale(&sheet), - super::PRINT_TITLE_HORIZONTAL_SCALE - ); - assert_eq!(xlsx_left_offset(&sheet), 0.0); - } - - #[test] - fn calibrates_width_only_fit_with_print_titles() { - let mut sheet = SheetData { - rows: Vec::new(), - images: Vec::new(), - column_widths: Vec::new(), - merges: Vec::new(), - row_breaks: Vec::new(), - default_row_height: 15.0, - print_title_rows: Some((12, 12)), - page_setup: SheetPageSetup::default(), - footer: None, - }; - sheet.page_setup.fit_to_width = true; - - assert_eq!( - xlsx_vertical_scale(&sheet, 0.75), - super::PRINT_TITLE_WIDTH_ONLY_VERTICAL_SCALE - ); - } - - #[test] - fn applies_explicit_print_scale_to_width_only_fit_rows() { - let mut sheet = SheetData { - rows: Vec::new(), - images: Vec::new(), - column_widths: Vec::new(), - merges: Vec::new(), - row_breaks: Vec::new(), - default_row_height: 15.0, - print_title_rows: None, - page_setup: SheetPageSetup::default(), - footer: None, - }; - sheet.page_setup.fit_to_width = true; - sheet.page_setup.print_scale = 0.85; - - assert_eq!( - xlsx_vertical_scale(&sheet, 0.75), - super::FIT_TO_WIDTH_ONLY_VERTICAL_SCALE * 0.85 * super::FIT_TO_PAGE_VERTICAL_SCALE - ); - } - - #[test] - fn renders_solid_preset_rectangle() { - let xml = r#"00002020"#; - let document = roxmltree::Document::parse(xml).expect("shape XML is valid"); - - let rows = vec![ - RowData { - index: 0, - height: 15.0, - cells: Vec::new(), - }, - RowData { - index: 1, - height: 25.0, - cells: Vec::new(), - }, - ]; - let shape = read_two_cell_shape(document.root_element(), &[], &[10.0, 20.0], &rows, 15.0) - .expect("solid rectangle should render"); - - assert_eq!(shape.col, 0); - assert_eq!(shape.row, 0); - assert_eq!(shape.width, 30.0); - assert_eq!(shape.height, 40.0); - assert!(matches!(shape.data, SheetImageData::Rgba(_))); - } - - #[test] - fn composites_transparent_picture_pixels_over_solid_background() { - let mut image = image::RgbaImage::from_pixel(1, 1, image::Rgba([255, 0, 0, 128])); - - composite_rgba_background(&mut image, PdfColor::new(1.0, 1.0, 1.0)); - - assert_eq!(image.get_pixel(0, 0).0, [255, 127, 127, 255]); - } - - #[test] - fn recognizes_custom_dollar_formats() { - let formats = HashMap::from([(164, "\"$\"#,##0.00".to_owned())]); - - assert!(matches!( - parse_number_format(Some("164"), &formats), - super::NumberFormat::DollarTwoDecimals - )); - assert_eq!( - super::format_numeric_value(111.0, "111", super::NumberFormat::DollarTwoDecimals), - "$111.00" - ); - assert_eq!( - super::format_numeric_value(0.0, "0", super::NumberFormat::DollarTwoDecimals), - "$0.00" - ); - } - - #[test] - fn recognizes_builtin_percentage_formats() { - assert!(matches!( - parse_number_format(Some("9"), &HashMap::new()), - super::NumberFormat::PercentageZeroDecimals - )); - assert!(matches!( - parse_number_format(Some("10"), &HashMap::new()), - super::NumberFormat::PercentageTwoDecimals - )); - assert_eq!( - super::format_numeric_value(0.06, "0.06", super::NumberFormat::PercentageTwoDecimals), - "6.00%" - ); - } - - #[test] - fn reads_fit_to_width_scale_and_margins() { - let page_setup = read_page_setup( - r#""#, - ) - .expect("worksheet XML is valid"); - - assert!(page_setup.fit_to_width); - assert!((page_setup.print_scale - 0.74).abs() < 0.001); - assert!(!page_setup.fit_to_height); - assert_eq!(page_setup.margin_left, 18.0); - assert_eq!(page_setup.margin_right, 36.0); - assert_eq!(page_setup.margin_top, 54.0); - assert_eq!(page_setup.margin_bottom, 72.0); - } - - #[test] - fn reads_and_expands_xlsx_footer_fields() { - let xml = r#"&L&6 Doc#: FIR-003.5 Effective: 20171109&C&"Arial,Regular"&6 Page &P of &N"#; - let footer = read_sheet_footer(xml) - .expect("worksheet XML is valid") - .expect("footer exists"); - let (left, center, right) = parse_header_footer_sections(&footer.format); - let (left_text, left_size, left_font) = expand_header_footer_fields(&left, 1, 9); - let (center_text, center_size, center_font) = expand_header_footer_fields(¢er, 1, 9); - - assert_eq!(footer.margin, 18.0); - assert_eq!(left_text, " Doc#: FIR-003.5\nEffective: 20171109"); - assert_eq!(left_size, 6.0); - assert_eq!(left_font, None); - assert_eq!(center_text, " Page 1 of 9"); - assert_eq!(center_size, 6.0); - assert_eq!(center_font, Some("arial")); - assert!(right.is_empty()); - } - - #[test] - fn defaults_fit_to_page_to_one_page_tall() { - let page_setup = read_page_setup( - r#""#, - ) - .expect("worksheet XML is valid"); - - assert!(page_setup.fit_to_width); - assert!(page_setup.fit_to_height); - } - - #[test] - fn ignores_printer_page_size_for_width_only_fit() { - let page_setup = read_page_setup( - r#""#, - ) - .expect("worksheet XML is valid"); - - assert!(!super::should_use_printer_page_size(page_setup, false)); - } - - #[test] - fn ignores_printer_page_size_for_ordinary_sheet() { - let page_setup = - read_page_setup(r#""#) - .expect("worksheet XML is valid"); - - assert!(!super::should_use_printer_page_size(page_setup, false)); - } - - #[test] - fn uses_printer_page_size_for_print_title_rows() { - let page_setup = - read_page_setup(r#""#) - .expect("worksheet XML is valid"); - - assert!(super::should_use_printer_page_size(page_setup, true)); - } - - #[test] - fn calibrates_ordinary_sheet_when_printer_paper_differs() { - let page_setup = - read_page_setup(r#""#) - .expect("worksheet XML is valid"); - - assert!(super::should_calibrate_ignored_printer_page_size( - page_setup, - PageSize::LETTER, - false, - )); - assert!(!super::should_calibrate_ignored_printer_page_size( - page_setup, - PageSize::A4, - false, - )); - } - - #[test] - fn formats_excel_date_serial_as_month_day_year() { - assert_eq!(format_excel_date(46_104.0), "3/23/2026"); - } - - #[test] - fn formats_custom_excel_date_and_thousands() { - let formats = HashMap::from([ - (164, r#"dd\-mmm\-yyyy"#.to_owned()), - (165, "#,##0".to_owned()), - (166, r#"yyyy\-mm\-dd;@"#.to_owned()), - ]); - - assert!(matches!( - parse_number_format(Some("164"), &formats), - super::NumberFormat::DateDayShortMonthYear - )); - assert!(matches!( - parse_number_format(Some("165"), &formats), - super::NumberFormat::ThousandsZeroDecimals - )); - assert!(matches!( - parse_number_format(Some("166"), &formats), - super::NumberFormat::DateYearMonthDay - )); - assert!(matches!( - parse_number_format(Some("3"), &formats), - super::NumberFormat::ThousandsZeroDecimals - )); - assert_eq!( - super::format_numeric_value( - 46_046.0, - "46046", - super::NumberFormat::DateDayShortMonthYear - ), - "24-Jan-2026" - ); - assert_eq!( - super::format_numeric_value(45_758.0, "45758", super::NumberFormat::DateYearMonthDay), - "2025-04-11" - ); - assert_eq!( - super::format_numeric_value( - 61_859.0, - "61859", - super::NumberFormat::ThousandsZeroDecimals - ), - "61,859" - ); - } - - #[test] - fn applies_equal_conditional_font_color() { - let xml = r#""✔""#; - let mut rows = vec![RowData { - index: 0, - height: 15.0, - cells: vec![ - CellData { - text: "✔".to_owned(), - ..CellData::default() - }, - CellData { - text: "✖".to_owned(), - ..CellData::default() - }, - ], - }]; - let styles = XlsxStyles { - differential_fonts: vec![DifferentialFontStyle { - color: Some(PdfColor::new(0.25, 0.46, 0.17)), - ..DifferentialFontStyle::default() - }], - ..XlsxStyles::default() - }; - - apply_sheet_conditional_formats(xml, &mut rows, &styles) - .expect("conditional formatting XML is valid"); - - assert_eq!( - rows[0].cells[0].style.font_color, - PdfColor::new(0.25, 0.46, 0.17) - ); - assert_eq!(rows[0].cells[1].style.font_color, PdfColor::BLACK); - } - - #[test] - fn applies_contains_text_conditional_fill() { - let xml = r#"NOT(ISERROR(SEARCH("Accept",H16)))"#; - let mut cells = vec![CellData::default(); 8]; - cells[7].text = "Accept".to_owned(); - let mut rows = vec![RowData { - index: 15, - height: 15.0, - cells, - }]; - let fill = PdfColor::new(0.57, 0.82, 0.32); - let styles = XlsxStyles { - differential_fills: vec![Some(fill)], - ..XlsxStyles::default() - }; - - apply_sheet_conditional_formats(xml, &mut rows, &styles) - .expect("conditional formatting XML is valid"); - - assert_eq!(rows[0].cells[7].style.fill_color, Some(fill)); - } - - #[test] - fn applies_relative_text_equality_conditional_style() { - let xml = r#"$A6="yes""#; - let mut rows = vec![ - RowData { - index: 5, - height: 15.0, - cells: vec![CellData { - text: "Yes".to_owned(), - ..CellData::default() - }], - }, - RowData { - index: 6, - height: 15.0, - cells: vec![CellData { - text: "No".to_owned(), - ..CellData::default() - }], - }, - ]; - let color = PdfColor::new(0.75, 0.2, 0.0); - let fill = PdfColor::new(0.9, 0.9, 0.85); - let styles = XlsxStyles { - differential_fonts: vec![DifferentialFontStyle { - bold: Some(true), - strike: Some(true), - color: Some(color), - ..DifferentialFontStyle::default() - }], - differential_fills: vec![Some(fill)], - ..XlsxStyles::default() - }; - - apply_sheet_conditional_formats(xml, &mut rows, &styles) - .expect("conditional formatting XML is valid"); - - assert!(rows[0].cells[2].style.bold); - assert!(rows[0].cells[2].style.strike); - assert_eq!(rows[0].cells[2].style.font_color, color); - assert_eq!(rows[0].cells[2].style.fill_color, Some(fill)); - assert!(!rows[1].cells[0].style.bold); - } - - #[test] - fn applies_table_font_style_only_within_table_range() { - let mut rows = vec![RowData { - index: 4, - height: 15.0, - cells: vec![CellData::default(); 4], - }]; - let color = PdfColor::new(0.12, 0.32, 0.58); - - apply_table_font_layer( - &mut rows, - 1, - 2, - 4, - 4, - DifferentialFontStyle { - bold: Some(true), - italic: Some(false), - strike: None, - color: Some(color), - }, - ); - - assert!(!rows[0].cells[0].style.bold); - assert_eq!(rows[0].cells[0].style.font_color, PdfColor::BLACK); - assert!(rows[0].cells[1].style.bold); - assert!(!rows[0].cells[1].style.italic); - assert_eq!(rows[0].cells[1].style.font_color, color); - assert!(rows[0].cells[2].style.bold); - assert_eq!(rows[0].cells[3].style.font_color, PdfColor::BLACK); - } - - #[test] - fn applies_table_fill_style_only_within_table_range() { - let fill = PdfColor::new(0.78, 0.81, 0.81); - let mut rows = vec![RowData { - index: 4, - height: 15.0, - cells: vec![CellData::default(); 4], - }]; - - apply_table_fill_layer(&mut rows, 1, 2, 4, 4, fill); - - assert_eq!(rows[0].cells[0].style.fill_color, None); - assert_eq!(rows[0].cells[1].style.fill_color, Some(fill)); - assert_eq!(rows[0].cells[2].style.fill_color, Some(fill)); - assert_eq!(rows[0].cells[3].style.fill_color, None); - } - - #[test] - fn applies_saved_start_date_conditional_fill() { - let xml = r#"StartDate+0=TODAY()"#; - let mut rows = vec![RowData { - index: 0, - height: 15.0, - cells: vec![CellData::default(), CellData::default()], - }]; - let fill = PdfColor::new(0.82, 0.93, 0.85); - let styles = XlsxStyles { - differential_fills: vec![Some(fill)], - ..XlsxStyles::default() - }; - - apply_sheet_conditional_formats(xml, &mut rows, &styles) - .expect("conditional formatting XML is valid"); - - assert_eq!(rows[0].cells[0].style.fill_color, Some(fill)); - assert_eq!(rows[0].cells[1].style.fill_color, Some(fill)); - } - - #[test] - fn reads_horizontal_print_centering() { - let page_setup = read_page_setup( - r#""#, - ) - .expect("worksheet XML is valid"); - - assert!(page_setup.horizontal_centered); - } - - #[test] - fn applies_excel_minimum_top_margin_when_fitting_to_pages() { - let page_setup = read_page_setup( - r#""#, - ) - .expect("worksheet XML is valid"); - - assert_eq!(page_setup.margin_top, 13.0); - } - - #[test] - fn preserves_sparse_row_indices() { - let xml = r#"FirstFifth"#; - let rows = - read_sheet_rows(xml, &[], &XlsxStyles::default()).expect("worksheet XML is valid"); - - assert_eq!(rows.len(), 2); - assert_eq!(rows[0].index, 0); - assert_eq!(rows[1].index, 4); - } - - #[test] - fn normalizes_general_numeric_values() { - let xml = r#"8.8599999999999996.022e+23"#; - let rows = - read_sheet_rows(xml, &[], &XlsxStyles::default()).expect("worksheet XML is valid"); - - assert_eq!(rows[0].cells[0].text, "8.86"); - assert!(rows[0].cells[0].is_numeric); - assert_eq!(rows[0].cells[1].text, "6.022e+23"); - assert!(rows[0].cells[1].is_numeric); - } - - #[test] - fn formats_excel_thousands_with_two_decimals() { - assert_eq!(format_thousands_two_decimals(42_000.0), "42,000.00"); - assert_eq!(format_thousands_two_decimals(-8.5), "-8.50"); - assert_eq!(format_thousands_two_decimals(1.125), "1.13"); - assert_eq!(format_thousands_two_decimals(270.505), "270.51"); - assert_eq!( - super::format_numeric_value(42_000.0, "42000", super::NumberFormat::DollarAccounting), - "$ 42,000.00" - ); - assert_eq!( - super::format_numeric_value(0.0, "0", super::NumberFormat::DollarAccounting), - "$ -" - ); - } - - #[test] - fn evaluates_empty_cached_sum_and_addition_formulas() { - let xml = r#" - 1000250 - 2000750 - SUM(A1:A2)SUM(B1:B2) - A3+B3 - "#; - let rows = - read_sheet_rows(xml, &[], &XlsxStyles::default()).expect("worksheet XML is valid"); - - assert_eq!(rows[2].cells[0].text, "3000"); - assert_eq!(rows[2].cells[1].text, "1000"); - assert_eq!(rows[3].cells[0].text, "4000"); - assert!(rows[3].cells[0].is_numeric); - } - - #[test] - fn recalculates_today_instead_of_using_stale_cached_value() { - let date_style = CellStyle { - number_format: super::NumberFormat::DateMonthDayYear, - ..CellStyle::default() - }; - let styles = XlsxStyles { - cells: vec![date_style], - ..XlsxStyles::default() - }; - let xml = r#"TODAY()1"#; - - let rows = read_sheet_rows(xml, &[], &styles).expect("worksheet XML is valid"); - - assert_eq!( - rows[0].cells[0].text, - format_excel_date(super::excel_today_serial()) - ); - } - - #[test] - fn recognizes_cjk_display_fonts_as_emphasis() { - assert!(font_name_is_emphasis(Some("黑体"))); - assert!(font_name_is_emphasis(Some("方正小标宋_GBK"))); - assert!(!font_name_is_emphasis(Some("仿宋_GB2312"))); - } - - #[test] - fn maps_franklin_gothic_medium_to_installed_font() { - assert_eq!( - super::xlsx_preferred_font(Some("Franklin Gothic Medium")), - Some("framd") - ); - } - - #[test] - fn maps_arial_to_installed_font() { - assert_eq!(super::xlsx_preferred_font(Some("Arial")), Some("arial")); - } - - #[test] - fn maps_kaiti_family_names_to_installed_font() { - assert_eq!( - super::xlsx_preferred_font(Some("华文楷体")), - Some("stkaiti") - ); - assert_eq!( - super::xlsx_preferred_font(Some("华文 楷体")), - Some("stkaiti") - ); - assert_eq!( - super::xlsx_preferred_font(Some("华 文楷体")), - Some("stkaiti") - ); - assert_eq!(super::xlsx_preferred_font(Some("STKaiti")), Some("stkaiti")); - assert_eq!(super::xlsx_preferred_font(Some("KaiTi")), Some("simkai")); - assert_eq!(super::xlsx_preferred_font(Some("楷体")), Some("simkai")); - } - - #[test] - fn recognizes_stacked_text_rotation() { - assert!(super::is_stacked_text(Some("255"))); - assert!(!super::is_stacked_text(Some("90"))); - assert!(!super::is_stacked_text(None)); - } - - #[test] - fn limits_kaiti_fallback_to_stacked_text() { - let style = CellStyle { - preferred_font: Some("simkai"), - ..CellStyle::default() - }; - assert!(!super::should_use_kaiti_fallback("2025/11/25", style)); - assert!(super::is_kaiti_slash_date("2025/11/25", style)); - assert!(!super::is_kaiti_slash_date("普通文字", style)); - assert!(!super::should_use_kaiti_fallback("普通文字", style)); - assert!(super::should_use_kaiti_fallback( - "研发工程\n审核", - CellStyle { - stacked_text: true, - ..style - } - )); - } - #[test] - fn maps_invoice_fonts_to_installed_fonts() { - assert_eq!(super::xlsx_preferred_font(Some("Garamond")), Some("gara")); - assert_eq!( - super::xlsx_preferred_font(Some("Tw Cen MT")), - Some("tcm_____") - ); - } - - #[test] - fn wraps_explicit_and_width_constrained_cell_text() { - let explicit = wrap_cell_text("Role\n(Rank)", 100.0, 10.0, false, false); - let constrained = wrap_cell_text("ABCD", 12.0, 10.0, false, false); - let words = wrap_cell_text("alpha beta", 30.0, 10.0, false, false); - - assert_eq!(explicit, vec!["Role", "(Rank)"]); - assert!(constrained.len() > 1); - assert_eq!(constrained.concat(), "ABCD"); - assert_eq!(words, vec!["alpha", "beta"]); - } - - #[test] - fn paginates_single_column_text_overflow_horizontally() { - let rows = [ - "Long Text Column".to_owned(), - "X".repeat(500), - format!("{} {}", "A".repeat(300), "B".repeat(200)), - "Short".to_owned(), - "Y".repeat(1000), - ] - .into_iter() - .enumerate() - .map(|(index, text)| RowData { - index, - height: 15.0, - cells: vec![CellData { - text, - ..CellData::default() - }], - }) - .collect(); - let sheet = SheetData { - rows, - images: Vec::new(), - column_widths: vec![COL_WIDTH], - merges: Vec::new(), - row_breaks: Vec::new(), - default_row_height: 15.0, - print_title_rows: None, - page_setup: SheetPageSetup::default(), - footer: None, - }; - let mut document = PdfDocument::new(); - - render_sheet(&mut document, &sheet, &[], PageSize::A4); - - assert_eq!(document.pages().len(), 12); - } - - #[test] - fn preserves_custom_row_height_and_bold_cell_style() { - let xml = r#"Product Name"#; - let styles = XlsxStyles { - cells: vec![ - CellStyle::default(), - CellStyle { - bold: true, - indent: 1.0, - ..CellStyle::default() - }, - ], - ..XlsxStyles::default() - }; - let rows = read_sheet_rows(xml, &[], &styles).expect("worksheet XML is valid"); - - assert_eq!(rows[0].height, 68.0); - assert!(rows[0].cells[3].style.bold); - assert_eq!(rows[0].cells[3].style.indent, 1.0); - } - - #[test] - fn preserves_hidden_row_values_without_layout_height() { - let xml = r#""#; - let rows = - read_sheet_rows(xml, &[], &XlsxStyles::default()).expect("worksheet XML is valid"); - - assert_eq!(rows.len(), 1); - assert_eq!(rows[0].index, 1); - assert_eq!(rows[0].height, 0.0); - assert_eq!(rows[0].cells[0].text, "42"); - } - - #[test] - fn preserves_empty_custom_height_rows_for_image_anchors() { - let xml = r#""#; - let rows = - read_sheet_rows(xml, &[], &XlsxStyles::default()).expect("worksheet XML is valid"); - - assert_eq!(rows.len(), 1); - assert_eq!(rows[0].index, 3); - assert_eq!(rows[0].height, 60.0); - assert!(rows[0].cells.is_empty()); - } - - #[test] - fn finds_page_break_on_sparse_row_before_next_content() { - assert_eq!(super::row_break_in_range(&[40], &[], 40, 41), Some(40)); - assert_eq!(super::row_break_in_range(&[40], &[], 41, 42), None); - } - - #[test] - fn preserves_rows_with_visible_styles_on_empty_cells() { - let xml = - r#""#; - let styles = XlsxStyles { - cells: vec![ - CellStyle::default(), - CellStyle { - fill_color: Some(PdfColor::new(1.0, 1.0, 0.0)), - ..CellStyle::default() - }, - ], - ..XlsxStyles::default() - }; - - let rows = read_sheet_rows(xml, &[], &styles).expect("worksheet XML is valid"); - - assert_eq!(rows.len(), 1); - assert_eq!(rows[0].index, 3); - assert!(rows[0].cells[0].style.fill_color.is_some()); - } - - #[test] - fn applies_column_styles_to_implicit_cells() { - let xml = r#" - value - value - "#; - let fill = PdfColor::new(0.9, 0.9, 0.9); - let styles = XlsxStyles { - cells: vec![ - CellStyle::default(), - CellStyle { - fill_color: Some(fill), - ..CellStyle::default() - }, - CellStyle { - bold: true, - ..CellStyle::default() - }, - ], - ..XlsxStyles::default() - }; - - let rows = read_sheet_rows(xml, &[], &styles).expect("worksheet XML is valid"); - - assert_eq!(rows.len(), 3); - assert_eq!(rows[1].index, 1); - assert_eq!(rows[0].cells.len(), 3); - assert_eq!(rows[0].cells[0].style.fill_color, Some(fill)); - assert_eq!(rows[0].cells[1].style.fill_color, Some(fill)); - assert_eq!(rows[0].cells[2].style.fill_color, None); - assert!(rows[0].cells[2].style.bold); - assert_eq!(rows[1].cells[0].style.fill_color, Some(fill)); - assert_eq!(rows[2].cells[2].style.fill_color, Some(fill)); - } - - #[test] - fn trims_only_trailing_empty_rows_after_image_anchors() { - let mut rows = vec![ - RowData { - index: 3, - height: 60.0, - cells: Vec::new(), - }, - RowData { - index: 8, - height: 60.0, - cells: vec![super::CellData::default()], - }, - ]; - let images = vec![SheetImage { - data: SheetImageData::Jpeg(Vec::new()), - pixel_width: 1, - pixel_height: 1, - legacy_vml: false, - col: 0, - row: 3, - col_offset: 0.0, - row_offset: 0.0, - width: 1.0, - height: 1.0, - foreground: false, - }]; - - trim_trailing_empty_rows(&mut rows, &images); - - assert_eq!(rows.len(), 1); - assert_eq!(rows[0].index, 3); - } - - #[test] - fn reads_jpeg_dimensions_from_start_of_frame() { - let jpeg = [ - 0xff, 0xd8, 0xff, 0xc0, 0x00, 0x11, 0x08, 0x00, 0x78, 0x00, 0xa0, 0x03, 0x01, 0x11, - 0x00, 0x02, 0x11, 0x00, 0x03, 0x11, 0x00, 0xff, 0xd9, - ]; - - assert_eq!(jpeg_dimensions(&jpeg), Some((160, 120))); - } - - #[test] - fn reads_drawing_relationship_ids_and_embeds() { - let xml = roxmltree::Document::parse( - r#""#, - ) - .expect("relationship XML is valid"); - let mut children = xml - .root_element() - .children() - .filter(|node| node.is_element()); - - assert_eq!( - relationship_id(children.next().unwrap()).as_deref(), - Some("rId1") - ); - assert_eq!( - relationship_id(children.next().unwrap()).as_deref(), - Some("rId2") - ); - } - - #[test] - fn uses_explicit_column_widths_for_horizontal_page_groups() { - let xml = r#""#; - let widths = read_column_widths(xml).expect("worksheet XML is valid"); - let groups = column_groups(&widths, 508.0); - - assert!((widths[0] - 78.75).abs() < 0.001); - assert_eq!(widths.len(), 14); - assert_eq!(groups, vec![(0, 5), (5, 11), (11, 14)]); - } - - #[test] - fn skips_style_only_horizontal_page_groups() { - let sheet = SheetData { - rows: vec![RowData { - index: 0, - height: 15.0, - cells: vec![ - CellData { - text: "Visible".to_owned(), - ..CellData::default() - }, - CellData::default(), - ], - }], - images: Vec::new(), - column_widths: vec![100.0, 100.0], - merges: Vec::new(), - row_breaks: Vec::new(), - default_row_height: 15.0, - print_title_rows: None, - page_setup: SheetPageSetup::default(), - footer: None, - }; - - assert!(column_group_has_content(&sheet, 0, 1)); - assert!(!column_group_has_content(&sheet, 1, 2)); - } - - #[test] - fn automatic_breaks_restart_after_manual_breaks() { - let sheet = SheetData { - rows: (0..4) - .map(|index| RowData { - index, - height: 25.0, - cells: Vec::new(), - }) - .collect(), - images: Vec::new(), - column_widths: Vec::new(), - merges: Vec::new(), - row_breaks: vec![2], - default_row_height: 25.0, - print_title_rows: Some((0, 0)), - page_setup: SheetPageSetup { - page_size: PageSize::new(100.0, 100.0).expect("valid page size"), - margin_top: 10.0, - margin_bottom: 10.0, - ..SheetPageSetup::default() - }, - footer: None, - }; - - assert!(super::automatic_row_breaks(&sheet, sheet.page_setup.page_size, 1.0).is_empty()); - } - - #[test] - fn uses_excel_digit_width_for_palatino_linotype() { - assert!( - (super::excel_max_digit_width(Some("Palatino Linotype"), 11.0) - 7.062).abs() < 0.01 - ); - } - - #[test] - fn uses_smaller_print_or_fit_to_width_scale() { - assert_eq!(effective_content_scale(1000.0, 800.0, 0.74, true), 0.8); - assert_eq!(effective_content_scale(1000.0, 700.0, 0.74, true), 0.7); - assert_eq!(effective_content_scale(1000.0, 700.0, 0.74, false), 0.74); - } - - #[test] - fn reads_merged_ranges_and_argb_colors() { - let xml = r#""#; - let merges = read_merge_ranges(xml).expect("worksheet XML is valid"); - let color = parse_rgb_color("004472C4").expect("ARGB color is valid"); - - assert_eq!(merges[0].start_col, 0); - assert_eq!(merges[0].end_col, 13); - assert_eq!(merges[0].start_row, 0); - assert_eq!(color.r, 68.0 / 255.0); - assert_eq!(color.g, 114.0 / 255.0); - assert_eq!(color.b, 196.0 / 255.0); - } - - #[test] - fn preserves_borders_from_merged_range_edges() { - let mut top_left = CellData::default(); - top_left.style.borders.left = Some(PdfColor::BLACK); - top_left.style.borders.top = Some(PdfColor::BLACK); - let mut top_right = CellData::default(); - top_right.style.borders.right = Some(PdfColor::BLACK); - let mut bottom_left = CellData::default(); - bottom_left.style.borders.bottom = Some(PdfColor::BLACK); - let mut bottom_right = CellData::default(); - bottom_right.style.borders.right = Some(PdfColor::BLACK); - let rows = vec![ - RowData { - index: 0, - height: 10.0, - cells: vec![top_left, top_right], - }, - RowData { - index: 1, - height: 10.0, - cells: vec![bottom_left, bottom_right], - }, - ]; - let borders = merged_cell_borders( - &rows, - &MergeRange { - start_col: 0, - end_col: 1, - start_row: 0, - end_row: 1, - }, - ); - - assert_eq!(borders.left, Some(PdfColor::BLACK)); - assert_eq!(borders.right, Some(PdfColor::BLACK)); - assert_eq!(borders.top, Some(PdfColor::BLACK)); - assert_eq!(borders.bottom, Some(PdfColor::BLACK)); - } - - #[test] - fn restarts_merged_cell_geometry_on_continuation_page() { - let merge = MergeRange { - start_col: 0, - end_col: 0, - start_row: 45, - end_row: 49, - }; - - assert_eq!(super::merged_cell_render_row(&merge, 0), Some(45)); - assert_eq!(super::merged_cell_render_row(&merge, 47), Some(47)); - assert_eq!(super::merged_cell_render_row(&merge, 50), None); - } - - #[test] - fn resolves_indexed_and_tinted_theme_colors() { - assert_eq!(indexed_color(9), Some(PdfColor::new(1.0, 1.0, 1.0))); - assert_eq!(indexed_color(10), Some(PdfColor::new(1.0, 0.0, 0.0))); - let scheme = [ - PdfColor::BLACK, - PdfColor::new(1.0, 1.0, 1.0), - PdfColor::new(0.1, 0.1, 0.1), - PdfColor::new(0.9, 0.9, 0.9), - ]; - let theme = spreadsheet_theme_colors(&scheme); - assert_eq!(theme[0], scheme[1]); - assert_eq!(theme[1], scheme[0]); - assert_eq!(theme[2], scheme[3]); - assert_eq!(theme[3], scheme[2]); - let tinted = apply_color_tint(PdfColor::new(0.647, 0.647, 0.647), 0.8); - assert!((tinted.r - 0.9294).abs() < 0.0001); - assert!((tinted.g - 0.9294).abs() < 0.0001); - assert!((tinted.b - 0.9294).abs() < 0.0001); - let accent = apply_color_tint( - PdfColor::new(247.0 / 255.0, 245.0 / 255.0, 228.0 / 255.0), - -0.7499924, - ); - assert!((accent.r - 92.0 / 255.0).abs() < 0.002); - assert!((accent.g - 85.0 / 255.0).abs() < 0.002); - assert!((accent.b - 27.0 / 255.0).abs() < 0.002); - let light_accent = apply_color_tint( - PdfColor::new(31.0 / 255.0, 72.0 / 255.0, 124.0 / 255.0), - 0.7999817, - ); - assert!((light_accent.r - 198.0 / 255.0).abs() < 0.002); - assert!((light_accent.g - 217.0 / 255.0).abs() < 0.002); - assert!((light_accent.b - 241.0 / 255.0).abs() < 0.002); - assert_eq!( - apply_color_tint(PdfColor::WHITE, -0.05), - PdfColor::new(0.946, 0.95, 0.946) - ); - assert_eq!( - apply_color_tint(PdfColor::WHITE, -0.15), - PdfColor::new(0.85, 0.851, 0.85) - ); - } - - #[test] - fn preserves_individual_border_sides() { - let xml = roxmltree::Document::parse( - r#""#, - ) - .expect("border XML is valid"); - - let borders = parse_cell_borders(xml.root_element(), &[]); - - assert!(borders.left.is_none()); - assert!(borders.right.is_none()); - assert!(borders.bottom.is_none()); - assert_eq!( - borders.top, - Some(PdfColor::new(17.0 / 255.0, 34.0 / 255.0, 51.0 / 255.0)) - ); - } - - #[test] - fn resolves_themed_border_colors() { - let xml = roxmltree::Document::parse( - r#""#, - ) - .expect("border XML is valid"); - let borders = parse_cell_borders(xml.root_element(), &[PdfColor::WHITE]); - - assert_eq!(borders.left, Some(PdfColor::new(0.946, 0.95, 0.946))); - } - - #[test] - fn reads_table_internal_border_widths() { - let xml = roxmltree::Document::parse( - r#""#, - ) - .expect("border XML is valid"); - - let borders = super::parse_table_borders(xml.root_element(), &[]); - - assert_eq!( - borders.vertical, - Some((PdfColor::new(17.0 / 255.0, 34.0 / 255.0, 51.0 / 255.0), 0.5)) - ); - assert_eq!( - borders.horizontal, - Some(( - PdfColor::new(68.0 / 255.0, 85.0 / 255.0, 102.0 / 255.0), - 1.0 - )) - ); - } - - #[test] - fn reads_zero_based_manual_row_breaks() { - let xml = r#""#; - - let row_breaks = read_row_breaks(xml).expect("worksheet XML is valid"); - - assert_eq!(row_breaks, vec![18, 35]); - } - - #[test] - fn distinguishes_top_center_and_bottom_alignment() { - assert_eq!( - parse_vertical_alignment(Some("top")), - VerticalAlignment::Top - ); - assert_eq!( - parse_vertical_alignment(Some("center")), - VerticalAlignment::Center - ); - assert_eq!( - parse_vertical_alignment(Some("bottom")), - VerticalAlignment::Bottom - ); - assert_eq!(parse_vertical_alignment(None), VerticalAlignment::Bottom); - } - - #[test] - fn distinguishes_horizontal_alignment_values() { - assert_eq!( - parse_horizontal_alignment(Some("left")), - HorizontalAlignment::Left - ); - assert_eq!( - parse_horizontal_alignment(Some("center")), - HorizontalAlignment::Center - ); - assert_eq!( - parse_horizontal_alignment(Some("right")), - HorizontalAlignment::Right - ); - assert_eq!( - parse_horizontal_alignment(None), - HorizontalAlignment::General - ); - } - - #[test] - fn detects_rtl_base_direction_for_general_alignment() { - assert!(has_rtl_base_direction("كتاب برمجة")); - assert!(has_rtl_base_direction("₪120 ספר קוד")); - assert!(!has_rtl_base_direction("Programming Book")); - assert!(!has_rtl_base_direction("50 SAR")); - } - - #[test] - fn expands_right_aligned_text_overflow_into_empty_left_cells() { - let sheet = SheetData { - rows: Vec::new(), - images: Vec::new(), - column_widths: vec![20.0, 20.0, 10.0, 10.0], - merges: Vec::new(), - row_breaks: Vec::new(), - default_row_height: 15.0, - print_title_rows: None, - page_setup: SheetPageSetup::default(), - footer: None, - }; - let row = RowData { - index: 0, - height: 15.0, - cells: vec![ - CellData::default(), - CellData::default(), - CellData { - text: "Re-inspection:".to_owned(), - ..CellData::default() - }, - CellData { - text: "No".to_owned(), - ..CellData::default() - }, - ], - }; - - assert_eq!( - text_overflow_region(&sheet, &row, &sheet.column_widths, 0, 2, 4, true), - (-40.0, 50.0, false) - ); - assert_eq!( - text_overflow_region(&sheet, &row, &sheet.column_widths, 0, 2, 4, false), - (0.0, 10.0, true) - ); - } -} diff --git a/scripts/Build-Python-Native.ps1 b/scripts/Build-Python-Native.ps1 deleted file mode 100644 index 33fd4a5a..00000000 --- a/scripts/Build-Python-Native.ps1 +++ /dev/null @@ -1,35 +0,0 @@ -param( - [switch]$SkipBuild -) - -$ErrorActionPreference = "Stop" -$RepoRoot = Split-Path -Parent $PSScriptRoot -$Manifest = Join-Path $RepoRoot "minipdf-python/native/Cargo.toml" -$Destination = Join-Path $RepoRoot "minipdf-python/src/minipdf/_native.pyd" - -if (-not $SkipBuild) { - $Cargo = Get-Command cargo | Select-Object -First 1 -ExpandProperty Source - $venvPython = Join-Path $RepoRoot ".venv/Scripts/python.exe" - if (Test-Path -LiteralPath $venvPython) { - $env:PYO3_PYTHON = $venvPython - } - & $Cargo build --release --manifest-path $Manifest - if ($LASTEXITCODE -ne 0) { throw "Python native module build failed" } -} - -$Source = Join-Path $RepoRoot "minipdf-python/native/target/release" -if ($IsWindows) { - $Source = Join-Path $Source "_native.dll" -} elseif ($IsMacOS) { - $Source = Join-Path $Source "lib_native.dylib" - $Destination = Join-Path $RepoRoot "minipdf-python/src/minipdf/_native.abi3.so" -} else { - $Source = Join-Path $Source "lib_native.so" - $Destination = Join-Path $RepoRoot "minipdf-python/src/minipdf/_native.abi3.so" -} - -if (-not (Test-Path -LiteralPath $Source)) { - throw "Python native module artifact was not found: $Source" -} -Copy-Item $Source $Destination -Force -Write-Host "Installed native extension: $Destination" diff --git a/scripts/Invoke-LanguageVisualBenchmark.ps1 b/scripts/Invoke-LanguageVisualBenchmark.ps1 index ffd1449a..1a66471e 100644 --- a/scripts/Invoke-LanguageVisualBenchmark.ps1 +++ b/scripts/Invoke-LanguageVisualBenchmark.ps1 @@ -1,20 +1,17 @@ <# .SYNOPSIS Runs one MiniPdf implementation against the repository's visual benchmark fixtures. - .DESCRIPTION Uses Microsoft 365 as the primary scored reference and LibreOffice as the required auxiliary reference. Outputs are isolated below artifacts/-benchmark//. - .EXAMPLE - .\scripts\Run-Java-VisualBenchmark.ps1 -Suite classic -Format xlsx -MaxCases 1 - .\scripts\Run-Python-VisualBenchmark.ps1 -Suite issue -Format pptx -Filter "Asian Pacific" + .\scripts\Run-DotNet-VisualBenchmark.ps1 -Suite classic -Format xlsx -MaxCases 1 + .\scripts\Run-DotNet-VisualBenchmark.ps1 -Suite issue -Format pptx -Filter "Asian Pacific" #> - param( [Parameter(Mandatory = $true)] - [ValidateSet("dotnet", "rust", "java", "go", "python", "node")] + [ValidateSet("dotnet")] [string]$Language, [ValidateSet("classic", "issue")] [string]$Suite = "classic", @@ -37,21 +34,17 @@ param( [switch]$SkipReference, [switch]$ForceReference ) - $ErrorActionPreference = "Stop" $RepoRoot = Split-Path -Parent $PSScriptRoot - if ($MaxCases -lt 0) { throw "MaxCases cannot be negative." } if ($MaxComparePages -lt 0) { throw "MaxComparePages cannot be negative." } if ($MinimumScore -lt 0.0 -or $MinimumScore -gt 1.0) { throw "MinimumScore must be between 0.0 and 1.0." } - function Resolve-RepoPath([string]$PathValue) { if ([System.IO.Path]::IsPathRooted($PathValue)) { return $PathValue } return Join-Path $RepoRoot $PathValue } - function Get-RepoRelativePath([string]$PathValue) { $FullRepoRoot = [System.IO.Path]::GetFullPath($RepoRoot).TrimEnd("\", "/") $FullPath = [System.IO.Path]::GetFullPath($PathValue) @@ -61,95 +54,27 @@ function Get-RepoRelativePath([string]$PathValue) { } return $FullPath.Substring($RepoPrefix.Length).Replace("\", "/") } - function Write-Json([object]$Value, [string]$Path) { $Json = $Value | ConvertTo-Json -Depth 8 [System.IO.File]::WriteAllText($Path, $Json, [System.Text.UTF8Encoding]::new($false)) } - function Assert-CommandSucceeded([string]$Description) { if ($LASTEXITCODE -ne 0) { throw "$Description failed with exit code $LASTEXITCODE." } } - function Find-Command([string]$Name) { return (Get-Command $Name -ErrorAction Stop).Source } - function Find-Python { $RelativePath = if ($IsWindows) { ".venv/Scripts/python.exe" } else { ".venv/bin/python" } $Candidate = Join-Path $RepoRoot $RelativePath if (Test-Path -LiteralPath $Candidate) { return $Candidate } return Find-Command "python" } - -function Find-Maven { - $Command = Get-Command mvn -ErrorAction SilentlyContinue - if ($Command) { return $Command.Source } - foreach ($MavenRoot in @($env:MAVEN_HOME, $env:M2_HOME)) { - if ($MavenRoot) { - $Candidate = Join-Path $MavenRoot $(if ($IsWindows) { "bin/mvn.cmd" } else { "bin/mvn" }) - if (Test-Path -LiteralPath $Candidate) { return $Candidate } - } - } - if ($IsWindows) { - $Candidate = Get-ChildItem (Join-Path $env:LOCALAPPDATA "Programs/Apache Maven") ` - -Recurse -Filter "mvn.cmd" -ErrorAction SilentlyContinue | - Sort-Object FullName -Descending | Select-Object -First 1 -ExpandProperty FullName - if ($Candidate) { return $Candidate } - } - throw "Maven was not found. Add mvn to PATH or set MAVEN_HOME." -} - -function Find-JavaExecutable { - $ExecutableName = if ($IsWindows) { "java.exe" } else { "java" } - if ($IsWindows) { - foreach ($JavaRoot in @( - (Join-Path $env:ProgramFiles "Eclipse Adoptium"), - (Join-Path $env:ProgramFiles "Java") - )) { - if (-not (Test-Path -LiteralPath $JavaRoot)) { continue } - $Candidate = Get-ChildItem -LiteralPath $JavaRoot -Directory -Filter "jdk*" | - Sort-Object Name -Descending | - ForEach-Object { Join-Path $_.FullName "bin/java.exe" } | - Where-Object { Test-Path -LiteralPath $_ } | - Select-Object -First 1 - if ($Candidate) { return $Candidate } - } - } - if ($env:JAVA_HOME) { - $Candidate = Join-Path $env:JAVA_HOME "bin/$ExecutableName" - if (Test-Path -LiteralPath $Candidate) { return $Candidate } - } - $Command = Get-Command java -ErrorAction SilentlyContinue - if ($Command) { return $Command.Source } - throw "Java was not found. Install JDK 17 or newer, or set JAVA_HOME." -} - -function Find-Go { - $ExecutableName = if ($IsWindows) { "go.exe" } else { "go" } - if ($env:GOROOT) { - $Candidate = Join-Path $env:GOROOT "bin/$ExecutableName" - if (Test-Path -LiteralPath $Candidate) { return $Candidate } - } - if ($IsWindows) { - foreach ($Candidate in @( - (Join-Path $env:ProgramFiles "Go/bin/go.exe"), - (Join-Path $env:LOCALAPPDATA "Programs/Go/bin/go.exe") - )) { - if (Test-Path -LiteralPath $Candidate) { return $Candidate } - } - } - $Command = Get-Command go -ErrorAction SilentlyContinue - if ($Command) { return $Command.Source } - throw "Go was not found. Install Go 1.22 or newer, or set GOROOT." -} - function Test-Pdf([string]$Path) { if (-not (Test-Path -LiteralPath $Path -PathType Leaf)) { return $false } $Bytes = [System.IO.File]::ReadAllBytes($Path) return $Bytes.Length -ge 5 -and [System.Text.Encoding]::ASCII.GetString($Bytes, 0, 5) -eq "%PDF-" } - $Defaults = @{ "classic:xlsx" = @{ Source = "tests/MiniPdf.Scripts/output" @@ -197,7 +122,6 @@ $Defaults = @{ OfficeLabel = "Microsoft 365 PowerPoint Reference" } } - $Config = $Defaults["$Suite`:$Format"] if (-not $Config) { throw "No $Language benchmark fixtures are configured for suite=$Suite format=$Format." @@ -205,7 +129,6 @@ if (-not $Config) { if ($Engine -eq "libre") { Write-Warning "-Engine libre is retained for compatibility. Microsoft 365 remains the primary scored reference; LibreOffice is auxiliary." } - $SourceDir = Resolve-RepoPath $(if ($SourceDir) { $SourceDir } else { $Config.Source }) $ReferenceDir = Resolve-RepoPath $(if ($ReferenceDir) { $ReferenceDir } else { $Config.OfficeReference }) $AuxiliaryReferenceDir = Resolve-RepoPath $(if ($AuxiliaryReferenceDir) { $AuxiliaryReferenceDir } else { $Config.LibreReference }) @@ -214,7 +137,6 @@ $CandidateDir = Resolve-RepoPath $(if ($CandidateDir) { $CandidateDir } else { J $ReportDir = Resolve-RepoPath $(if ($ReportDir) { $ReportDir } else { Join-Path $ArtifactRoot "report" }) $ComparisonManifest = Join-Path $ReportDir "comparison_manifest.json" $CoverageManifest = Join-Path $ReportDir "benchmark_coverage.json" - $SourceFiles = @(Get-ChildItem -LiteralPath $SourceDir -File -Filter "*.$Format" | Where-Object { -not $Filter -or $_.BaseName -like "*$Filter*" } | Sort-Object Name) @@ -224,12 +146,10 @@ if ($MaxCases -gt 0) { if ($SourceFiles.Count -eq 0) { throw "No .$Format files matched '$Filter' in $SourceDir" } - if (Test-Path -LiteralPath $ReportDir) { Remove-Item -LiteralPath $ReportDir -Recurse -Force } New-Item -ItemType Directory -Force -Path $CandidateDir, $ReferenceDir, $AuxiliaryReferenceDir, $ReportDir | Out-Null - $SelectedCases = @($SourceFiles | ForEach-Object { [pscustomobject]@{ name = $_.BaseName @@ -249,7 +169,6 @@ for ($Index = 0; $Index -lt $SelectedCases.Count; $Index++) { $CaseSources[$SelectedCases[$Index].case_id] = $SourceFiles[$Index].FullName } Write-Json ([pscustomobject]@{ cases = $SelectedCases }) $ComparisonManifest - $Tools = @{} if (-not $SkipCandidate -and -not $SkipBuild) { switch ($Language) { @@ -258,43 +177,8 @@ if (-not $SkipCandidate -and -not $SkipBuild) { & $Tools.dotnet build (Join-Path $RepoRoot "src/MiniPdf.Cli/MiniPdf.Cli.csproj") -c Release Assert-CommandSucceeded ".NET CLI build" } - "rust" { - $Tools.cargo = Find-Command "cargo" - & $Tools.cargo build --release --manifest-path (Join-Path $RepoRoot "minipdf-rs/Cargo.toml") -p minipdf-cli - Assert-CommandSucceeded "Rust CLI build" - } - "java" { - $Tools.java = Find-JavaExecutable - $env:JAVA_HOME = Split-Path -Parent (Split-Path -Parent $Tools.java) - $Tools.maven = Find-Maven - & $Tools.maven -B -ntp -f (Join-Path $RepoRoot "minipdf-java/pom.xml") package -DskipTests - Assert-CommandSucceeded "Java CLI build" - } - "go" { - $Tools.go = Find-Go - $GoOutput = Join-Path $ArtifactRoot $(if ($IsWindows) { "minipdf-go.exe" } else { "minipdf-go" }) - Push-Location (Join-Path $RepoRoot "minipdf-go") - try { & $Tools.go build -o $GoOutput ./cmd/minipdf } finally { Pop-Location } - Assert-CommandSucceeded "Go CLI build" - } - "python" { - $Tools.python = Find-Python - & (Join-Path $RepoRoot "scripts/Build-Python-Native.ps1") - Assert-CommandSucceeded "Python native module build" - } - "node" { - $Tools.npm = Find-Command "npm" - Push-Location (Join-Path $RepoRoot "minipdf-node") - try { - if (Test-Path "package-lock.json") { & $Tools.npm ci } else { & $Tools.npm install } - Assert-CommandSucceeded "Node dependency install" - & $Tools.npm run build - Assert-CommandSucceeded "Node native module build" - } finally { Pop-Location } - } } } - if (-not $SkipCandidate) { switch ($Language) { "dotnet" { @@ -302,44 +186,16 @@ if (-not $SkipCandidate) { $Tools.cli = Get-ChildItem (Join-Path $RepoRoot "src/MiniPdf.Cli/bin/Release") -Recurse -Filter "MiniPdf.Cli.dll" | Where-Object FullName -Match 'net9\.0' | Select-Object -First 1 -ExpandProperty FullName } - "rust" { - $RustName = if ($IsWindows) { "minipdf.exe" } else { "minipdf" } - $Tools.cli = Join-Path $RepoRoot "minipdf-rs/target/release/$RustName" - } - "java" { - if (-not $Tools.java) { $Tools.java = Find-JavaExecutable } - $Tools.cli = Get-ChildItem (Join-Path $RepoRoot "minipdf-java/minipdf-cli/target") -Filter "minipdf-cli-*.jar" | - Where-Object { $_.Name -notmatch '(sources|javadoc|original)' } | - Sort-Object LastWriteTime -Descending | Select-Object -First 1 -ExpandProperty FullName - } - "go" { - $Tools.cli = Join-Path $ArtifactRoot $(if ($IsWindows) { "minipdf-go.exe" } else { "minipdf-go" }) - } - "python" { - if (-not $Tools.python) { $Tools.python = Find-Python } - $env:PYTHONPATH = Join-Path $RepoRoot "minipdf-python/src" - } - "node" { $Tools.node = Find-Command "node" } } - - if ($Language -notin @("python", "node") -and (-not $Tools.cli -or -not (Test-Path -LiteralPath $Tools.cli))) { + if ((-not $Tools.cli -or -not (Test-Path -LiteralPath $Tools.cli))) { throw "$Language CLI artifact was not found. Run without -SkipBuild first." } - foreach ($Case in $SelectedCases) { $InputPath = $CaseSources[$Case.case_id] $OutputPath = Join-Path $CandidateDir ($Case.name + ".pdf") if (Test-Path -LiteralPath $OutputPath) { Remove-Item -LiteralPath $OutputPath -Force } switch ($Language) { "dotnet" { & $Tools.dotnet $Tools.cli $InputPath -o $OutputPath } - "rust" { & $Tools.cli $InputPath -o $OutputPath } - "java" { & $Tools.java -jar $Tools.cli $InputPath -o $OutputPath } - "go" { & $Tools.cli $InputPath -o $OutputPath } - "python" { & $Tools.python -m minipdf $InputPath -o $OutputPath } - "node" { - & $Tools.node -e "require(process.argv[1]).convertToPdf(process.argv[2], process.argv[3])" ` - (Join-Path $RepoRoot "minipdf-node") $InputPath $OutputPath - } } $Case.conversion_exit_code = $LASTEXITCODE $Case.candidate_exists = Test-Pdf $OutputPath @@ -352,7 +208,6 @@ if (-not $SkipCandidate) { $Case.conversion_status = if ($Case.candidate_exists) { "passed" } else { "failed" } } } - if (-not $SkipReference) { $Python = Find-Python $OfficeReferenceScript = Resolve-RepoPath $Config.OfficeReferenceScript @@ -372,12 +227,10 @@ if (-not $SkipReference) { } } } - foreach ($Case in $SelectedCases) { $Case.reference_exists = Test-Pdf (Join-Path $ReferenceDir ($Case.name + ".pdf")) $Case.auxiliary_reference_exists = Test-Pdf (Join-Path $AuxiliaryReferenceDir ($Case.name + ".pdf")) } - $PassedConversions = @($SelectedCases | Where-Object conversion_status -eq "passed").Count $MissingReferences = @($SelectedCases | Where-Object reference_exists -eq $false).Count $MissingAuxiliaryReferences = @($SelectedCases | Where-Object auxiliary_reference_exists -eq $false).Count @@ -403,7 +256,6 @@ $Coverage = [pscustomobject]@{ cases = $SelectedCases } Write-Json $Coverage $CoverageManifest - $Python = Find-Python $CompareArgs = @( (Join-Path $RepoRoot "tests/MiniPdf.Benchmark/compare_pdfs.py"), @@ -435,11 +287,9 @@ $Coverage.average_score = if ($Scores.Count -gt 0) { } else { $null } Write-Json $Coverage $CoverageManifest $BelowThreshold = @($Results | Where-Object { $null -eq $_.overall_score -or $_.overall_score -lt $MinimumScore }) - Write-Host "$Language benchmark: suite=$Suite format=$Format selected=$($SelectedCases.Count), converted=$PassedConversions, missing O365 references=$MissingReferences, missing LibreOffice references=$MissingAuxiliaryReferences" Write-Host "Coverage: $CoverageManifest" Write-Host "Report: $(Join-Path $ReportDir 'comparison_report.md')" - if ($PassedConversions -ne $SelectedCases.Count -or $MissingReferences -gt 0 -or $MissingAuxiliaryReferences -gt 0 -or $BelowThreshold.Count -gt 0) { throw "$Language benchmark failed: conversion failures=$($SelectedCases.Count - $PassedConversions), missing O365 references=$MissingReferences, missing LibreOffice references=$MissingAuxiliaryReferences, below MinimumScore=$($BelowThreshold.Count)." } diff --git a/scripts/Invoke-NpmStageRelease.ps1 b/scripts/Invoke-NpmStageRelease.ps1 deleted file mode 100644 index 4f298689..00000000 --- a/scripts/Invoke-NpmStageRelease.ps1 +++ /dev/null @@ -1,140 +0,0 @@ -<# -.SYNOPSIS - Approve staged npm packages and verify their publication on the public registry. - -.DESCRIPTION - npm >= 11.15 publishes via two-phase "staged publishing": CI stages packages with - `npm stage publish` and a maintainer must approve each staged package with - `npm stage approve ` (browser-based 2FA is required for every approval). - - This script: - 1. Lists staged packages (`npm stage list --json`). - 2. Approves platform packages first and the main `minipdf` package last. - 3. Verifies the registry: checks `latest` and every optionalDependency of the - main package for the expected version. - -.PARAMETER NpmCli - npm version spec run through npx (default: npm@11.15.0). - -.PARAMETER Version - Expected release version for verification. Defaults to the version of staged - entries, or the current `latest` on the registry when nothing is staged. - -.PARAMETER ListOnly - Only list staged packages. - -.PARAMETER ApproveOnly - Approve staged packages without registry verification. - -.PARAMETER VerifyOnly - Only verify the registry without listing or approving. -#> -[CmdletBinding()] -param( - [string]$NpmCli = 'npm@11.15.0', - [string]$Version, - [switch]$ListOnly, - [switch]$ApproveOnly, - [switch]$VerifyOnly -) - -$ErrorActionPreference = 'Stop' - -function Invoke-Npm { - param([string[]]$NpmArgs) - & npx -y $NpmCli @NpmArgs - if ($LASTEXITCODE -ne 0) { - throw "npx $NpmCli $($NpmArgs -join ' ') failed with exit code $LASTEXITCODE" - } -} - -function Get-StagedEntries { - $raw = & npx -y $NpmCli stage list --json 2>$null - if ($LASTEXITCODE -ne 0) { - throw "npx $NpmCli stage list failed with exit code $LASTEXITCODE" - } - if ([string]::IsNullOrWhiteSpace($raw)) { return @() } - $parsed = $raw | ConvertFrom-Json - if ($null -eq $parsed) { return @() } - if ($parsed -is [System.Array]) { return @($parsed) } - return @($parsed) -} - -function Get-RegistryPackage { - param([string]$PackageName) - $encoded = $PackageName -replace '/', '%2f' - $uri = "https://registry.npmjs.org/$encoded" - $response = Invoke-WebRequest -Uri $uri -UseBasicParsing -TimeoutSec 30 - if ($response.StatusCode -ne 200) { - throw "GET $uri returned $($response.StatusCode)" - } - return $response.Content | ConvertFrom-Json -} - -function Show-StagedEntries { - param([object[]]$Entries) - if ($Entries.Count -eq 0) { - Write-Host 'No staged packages.' - return - } - $Entries | - Select-Object id, name, version, tag, status | - Format-Table -AutoSize -} - -# Stage 1: list -$entries = @(Get-StagedEntries) -$expectedVersion = if ($Version) { - $Version -} elseif ($entries.Count -gt 0) { - $entries[0].version -} else { - (Get-RegistryPackage 'minipdf').'dist-tags'.latest -} - -if ($ListOnly) { - Show-StagedEntries -Entries $entries - return -} - -# Stage 2: approve platform packages first, main package last -if (-not $VerifyOnly -and $entries.Count -gt 0) { - $ordered = @($entries | Where-Object { $_.name -ne 'minipdf' }) + - @($entries | Where-Object { $_.name -eq 'minipdf' }) - foreach ($entry in $ordered) { - Write-Host "Approving $($entry.name)@$($entry.version) ($($entry.id)) ..." - Invoke-Npm @('stage', 'approve', $entry.id) - Write-Host "Approved $($entry.name)@$($entry.version)." - } - if ($ApproveOnly) { return } -} - -# Stage 3: verify the registry -if (-not $ApproveOnly -or $VerifyOnly) { - $main = Get-RegistryPackage 'minipdf' - $latest = $main.'dist-tags'.latest - $failed = $false - - Write-Host "Expected version: $expectedVersion" - Write-Host ('minipdf {0} latest={1}' -f - ($(if ($latest -eq $expectedVersion) { 'OK ' } else { 'FAIL' })), - $latest) - if ($latest -ne $expectedVersion) { $failed = $true } - - $optional = $main.versions.$latest.optionalDependencies - if ($null -ne $optional) { - foreach ($name in $optional.PSObject.Properties.Name) { - $pkg = Get-RegistryPackage $name - $hasVersion = $pkg.versions.PSObject.Properties.Name -contains $expectedVersion - $status = if ($hasVersion) { 'OK ' } else { 'FAIL' } - Write-Host ('{0} {1}={2}' -f $name, $expectedVersion, $status) - if (-not $hasVersion) { $failed = $true } - } - } - - if ($failed) { - Write-Error "Verification failed for version $expectedVersion." - exit 1 - } - Write-Host "Verification passed for version $expectedVersion." -} diff --git a/scripts/Run-All-Language-VisualBenchmarks.ps1 b/scripts/Run-All-Language-VisualBenchmarks.ps1 deleted file mode 100644 index 1523e4b1..00000000 --- a/scripts/Run-All-Language-VisualBenchmarks.ps1 +++ /dev/null @@ -1,44 +0,0 @@ -[CmdletBinding()] -param( - [switch]$Publish, - [string]$PagesRepository = (Join-Path (Split-Path (Split-Path $PSScriptRoot -Parent) -Parent) "minipdf-web-page"), - [ValidateSet("classic", "issue")] - [string]$Suite, - [ValidateSet("xlsx", "docx", "pptx")] - [string]$Format, - [ValidateSet("o365", "office", "libre")] - [string]$Engine, - [string]$Filter, - [int]$MaxCases, - [int]$MaxComparePages, - [double]$MinimumScore, - [string]$SourceDir, - [string]$CandidateDir, - [string]$ReferenceDir, - [string]$AuxiliaryReferenceDir, - [string]$ReportDir, - [string]$ArtifactRoot, - [switch]$SkipCandidate, - [switch]$SkipBuild, - [switch]$SkipReference, - [switch]$ForceReference -) - -$ErrorActionPreference = "Stop" -$BenchmarkParameters = @{} -foreach ($Entry in $PSBoundParameters.GetEnumerator()) { - if ($Entry.Key -notin @("Publish", "PagesRepository")) { - $BenchmarkParameters[$Entry.Key] = $Entry.Value - } -} - -foreach ($Language in @("dotnet", "rust", "java", "go", "python", "node")) { - Write-Host "`n=== $Language visual benchmark ===" - & (Join-Path $PSScriptRoot "Invoke-LanguageVisualBenchmark.ps1") -Language $Language @BenchmarkParameters - if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } -} - -if ($Publish) { - Write-Host "`n=== Publish visual benchmark dashboard ===" - & (Join-Path $PSScriptRoot "Publish-VisualBenchmarkPages.ps1") -DestinationRoot $PagesRepository -Clean -} diff --git a/scripts/Run-Go-VisualBenchmark.ps1 b/scripts/Run-Go-VisualBenchmark.ps1 deleted file mode 100644 index e4e60c55..00000000 --- a/scripts/Run-Go-VisualBenchmark.ps1 +++ /dev/null @@ -1,2 +0,0 @@ -param() -& (Join-Path $PSScriptRoot "Invoke-LanguageVisualBenchmark.ps1") -Language go @args \ No newline at end of file diff --git a/scripts/Run-Java-VisualBenchmark.ps1 b/scripts/Run-Java-VisualBenchmark.ps1 deleted file mode 100644 index caea1875..00000000 --- a/scripts/Run-Java-VisualBenchmark.ps1 +++ /dev/null @@ -1,2 +0,0 @@ -param() -& (Join-Path $PSScriptRoot "Invoke-LanguageVisualBenchmark.ps1") -Language java @args \ No newline at end of file diff --git a/scripts/Run-Node-VisualBenchmark.ps1 b/scripts/Run-Node-VisualBenchmark.ps1 deleted file mode 100644 index ba0fcd66..00000000 --- a/scripts/Run-Node-VisualBenchmark.ps1 +++ /dev/null @@ -1,2 +0,0 @@ -param() -& (Join-Path $PSScriptRoot "Invoke-LanguageVisualBenchmark.ps1") -Language node @args \ No newline at end of file diff --git a/scripts/Run-Python-VisualBenchmark.ps1 b/scripts/Run-Python-VisualBenchmark.ps1 deleted file mode 100644 index 4c1559a7..00000000 --- a/scripts/Run-Python-VisualBenchmark.ps1 +++ /dev/null @@ -1,2 +0,0 @@ -param() -& (Join-Path $PSScriptRoot "Invoke-LanguageVisualBenchmark.ps1") -Language python @args \ No newline at end of file diff --git a/scripts/Run-Rust-Benchmark-Matrix.ps1 b/scripts/Run-Rust-Benchmark-Matrix.ps1 deleted file mode 100644 index c7fe6d12..00000000 --- a/scripts/Run-Rust-Benchmark-Matrix.ps1 +++ /dev/null @@ -1,120 +0,0 @@ -<# -.SYNOPSIS - Run and summarize every Rust-supported shared visual benchmark suite. - -.DESCRIPTION - Covers classic/issue XLSX and DOCX fixtures plus issue PPTX fixtures. This - does not execute C# xUnit tests. -#> - -param( - [int]$MaxComparePages = 1, - [double]$MinimumScore = 0.95, - [ValidateSet("o365", "office", "libre")] - [string]$Engine = "o365", - [switch]$SkipReference, - [switch]$ForceReference, - [switch]$ReportOnly -) - -$ErrorActionPreference = "Stop" -$RepoRoot = Split-Path -Parent $PSScriptRoot -$Runner = Join-Path $PSScriptRoot "Run-Rust-Benchmark.ps1" -$ArtifactRoot = Join-Path $RepoRoot "artifacts/rust-benchmark" -$MatrixJson = Join-Path $ArtifactRoot "benchmark_matrix.json" -$MatrixMarkdown = Join-Path $ArtifactRoot "benchmark_matrix.md" -$Targets = @( - [pscustomobject]@{ Suite = "classic"; Format = "xlsx" }, - [pscustomobject]@{ Suite = "classic"; Format = "docx" }, - [pscustomobject]@{ Suite = "issue"; Format = "xlsx" }, - [pscustomobject]@{ Suite = "issue"; Format = "docx" }, - [pscustomobject]@{ Suite = "issue"; Format = "pptx" } -) - -if (-not $ReportOnly) { - foreach ($Target in $Targets) { - $Arguments = @{ - Suite = $Target.Suite - Format = $Target.Format - Engine = $Engine - MaxComparePages = $MaxComparePages - MinimumScore = $MinimumScore - } - if ($SkipReference) { $Arguments.SkipReference = $true } - if ($ForceReference) { $Arguments.ForceReference = $true } - & $Runner @Arguments - } -} - -$Rows = foreach ($Target in $Targets) { - $CoveragePath = Join-Path $ArtifactRoot "$($Target.Suite)/$($Target.Format)/report/benchmark_coverage.json" - if (-not (Test-Path $CoveragePath)) { - throw "Missing coverage manifest: $CoveragePath" - } - $Coverage = Get-Content $CoveragePath -Raw | ConvertFrom-Json - [pscustomobject]@{ - suite = $Coverage.suite - format = $Coverage.format - reference_engine = $Coverage.reference_engine - auxiliary_reference_engine = $Coverage.auxiliary_reference_engine - report = "$($Coverage.suite)/$($Coverage.format)/report/comparison_report.md" - selected_cases = $Coverage.selected_cases - passed_conversions = $Coverage.passed_conversions - failed_conversions = $Coverage.failed_conversions - missing_references = $Coverage.missing_references - missing_auxiliary_references = $Coverage.missing_auxiliary_references - comparison_completed = $Coverage.comparison_completed - comparison_results = $Coverage.comparison_results - max_compare_pages = $Coverage.max_compare_pages - average_score = $Coverage.average_score - coverage_manifest = [System.IO.Path]::GetRelativePath($RepoRoot, $CoveragePath).Replace("\", "/") - } -} - -$Summary = [pscustomobject]@{ - fixture_scope = "shared-on-disk-fixtures" - executes_dotnet_xunit = $false - rust_supported_formats = @("xlsx", "docx", "pptx") - reference_engine = "o365" - auxiliary_reference_engine = "libreoffice" - unsupported_formats = @() - selected_cases = ($Rows | Measure-Object selected_cases -Sum).Sum - passed_conversions = ($Rows | Measure-Object passed_conversions -Sum).Sum - failed_conversions = ($Rows | Measure-Object failed_conversions -Sum).Sum - missing_references = ($Rows | Measure-Object missing_references -Sum).Sum - missing_auxiliary_references = ($Rows | Measure-Object missing_auxiliary_references -Sum).Sum - comparison_results = ($Rows | Measure-Object comparison_results -Sum).Sum - comparison_completed = @($Rows | Where-Object { -not $_.comparison_completed }).Count -eq 0 - suites = @($Rows) -} - -New-Item -ItemType Directory -Force -Path $ArtifactRoot | Out-Null -$Summary | ConvertTo-Json -Depth 5 | Set-Content $MatrixJson -Encoding UTF8 - -$Markdown = @( - "# Rust Shared Visual Benchmark Matrix", - "", - "> This matrix reuses the repository's on-disk fixtures and visual comparison pipeline. It does not execute C# xUnit tests or assertions.", - "", - "| Suite | Format | Report | Selected | Converted | Compared | Missing refs | First pages | Average score | Complete |", - "|---|---:|---|---:|---:|---:|---:|---:|---:|---:|" -) -foreach ($Row in $Rows) { - $Score = if ($null -eq $Row.average_score) { "N/A" } else { "{0:N4}" -f $Row.average_score } - $ReportLink = if ($Row.report) { "[View comparison]($($Row.report))" } else { "Local artifact" } - $Markdown += "| $($Row.suite) | $($Row.format) | $ReportLink | $($Row.selected_cases) | $($Row.passed_conversions) | $($Row.comparison_results) | $($Row.missing_references) | $($Row.max_compare_pages) | $Score | $($Row.comparison_completed) |" -} -$Markdown += @( - "", - "Total shared fixtures: **$($Summary.selected_cases)**", - "", - "Rust-supported formats: XLSX, DOCX, PPTX." -) -$Markdown | Set-Content $MatrixMarkdown -Encoding UTF8 - -Write-Host "Rust shared visual matrix: selected=$($Summary.selected_cases), converted=$($Summary.passed_conversions), compared=$($Summary.comparison_results), complete=$($Summary.comparison_completed)" -Write-Host "Matrix report: $MatrixMarkdown" - -if (-not $Summary.comparison_completed -or $Summary.failed_conversions -gt 0 -or $Summary.missing_references -gt 0 -or $Summary.missing_auxiliary_references -gt 0) { - throw "Rust shared visual benchmark matrix is incomplete." -} \ No newline at end of file diff --git a/scripts/Run-Rust-Benchmark.ps1 b/scripts/Run-Rust-Benchmark.ps1 deleted file mode 100644 index bdd5e07c..00000000 --- a/scripts/Run-Rust-Benchmark.ps1 +++ /dev/null @@ -1,2 +0,0 @@ -param() -& (Join-Path $PSScriptRoot "Invoke-LanguageVisualBenchmark.ps1") -Language rust @args \ No newline at end of file diff --git a/scripts/Run-Rust-VisualBenchmark.ps1 b/scripts/Run-Rust-VisualBenchmark.ps1 deleted file mode 100644 index bdd5e07c..00000000 --- a/scripts/Run-Rust-VisualBenchmark.ps1 +++ /dev/null @@ -1,2 +0,0 @@ -param() -& (Join-Path $PSScriptRoot "Invoke-LanguageVisualBenchmark.ps1") -Language rust @args \ No newline at end of file