x2md is a pure Go library and CLI for converting documents to Markdown. No CGO dependencies, making it easy to cross-compile for any platform.
The intent of this library is to provide markdown for consumption by LLMs, not pretty rendering. As such, the focus is on extracting structured text content with minimal formatting.
git clone https://github.com/tenebris-tech/x2md.git
cd x2md
go build -o x2md ./cli# Convert a file (outputs to same name with .md extension)
x2md document.pdf
x2md document.docx
x2md document.xlsx
# Specify output file
x2md -output out.md document.pdf
# Batch convert a directory recursively
x2md -r ./documents
# Verbose mode
x2md -v document.pdf| Option | Description |
|---|---|
-r |
Recursively process directories |
-output |
Specify output file path (single file mode only) |
-output-dir |
Output directory for all converted files (flat structure) |
-skip-existing |
Skip files where .md already exists (default: true) |
-v |
Verbose mode with progress output |
-no-images |
Disable image extraction |
-no-formatting |
Disable bold/italic formatting |
-no-formulas |
Show only values, hide formulas (XLSX only) |
-compact |
Remove excessive blank lines from output |
-strip-headers |
Remove repetitive headers/footers (PDF only) |
-strip-page-numbers |
Remove page numbers (PDF only) |
-strip-toc |
Remove table of contents (PDF only) |
-strip-footnotes |
Remove footnotes (PDF only) |
-strip-blank-pages |
Remove blank pages (PDF only) |
-no-lists |
Disable list detection (PDF only) |
-no-headings |
Disable heading detection (PDF only) |
-no-location-markers |
Do not emit <!-- page N --> (PDF) or <!-- para N --> (DOCX) markers |
-no-scan-mode |
Disable automatic scanned page detection (PDF only) |
The convert package provides a unified API for document conversion. It handles format detection and delegates to the appropriate format-specific converter.
import "github.com/tenebris-tech/x2md/convert"
// Convert a single file - output placed next to source
c := convert.New()
result, err := c.Convert("document.pdf")// Convert all documents in a directory recursively
c := convert.New(convert.WithRecursion(true))
result, err := c.Convert("./documents")
fmt.Printf("Converted: %d, Skipped: %d, Failed: %d\n",
result.Converted, result.Skipped, result.Failed)c := convert.New(
convert.WithRecursion(true), // Process directories recursively
convert.WithSkipExisting(false), // Don't skip existing .md files
convert.WithOutputDirectory("./output"), // Write all output to one directory
convert.WithExtensions([]string{".pdf"}), // Only convert PDF files
)Pass options to the underlying format converters:
import (
"github.com/tenebris-tech/x2md/convert"
"github.com/tenebris-tech/x2md/pdf2md"
"github.com/tenebris-tech/x2md/docx2md"
"github.com/tenebris-tech/x2md/xlsx2md"
)
c := convert.New(
convert.WithRecursion(true),
convert.WithPDFOptions(
pdf2md.WithScanMode(false),
pdf2md.WithStrip(pdf2md.HeadersFooters, pdf2md.BlankPages),
),
convert.WithDOCXOptions(
docx2md.WithPreserveImages(false),
),
convert.WithXLSXOptions(
xlsx2md.WithIncludeSheetNames(false),
),
)c := convert.New(
convert.WithOnFileStart(func(path string) {
fmt.Printf("Converting: %s\n", path)
}),
convert.WithOnFileComplete(func(path, outputPath string, err error) {
if err != nil {
fmt.Printf(" Failed: %v\n", err)
} else {
fmt.Printf(" Created: %s\n", outputPath)
}
}),
)type Result struct {
Converted int // Files successfully converted
Skipped int // Files skipped (already exist)
Failed int // Files that failed
Errors []error // Details of failures
}When converting from a file (ConvertFile, ConvertFileToFile, the CLI and the convert package), the first line of the Markdown is a comment with the absolute path of the original file, as it was at conversion time:
<!-- source: /home/user/docs/report.pdf -->Conversions from in-memory data (Convert, ConvertWithImages) have no path and no such line.
x2md supports multiple document formats. Each format has its own package that can be used directly for more control, or through the unified convert package.
- PDF - Text-based and scanned PDF documents (
pdf2md) - DOCX - Microsoft Word documents (
docx2md) - XLSX - Microsoft Excel spreadsheets (
xlsx2md)
The pdf2md package converts PDF documents to Markdown.
- Text extraction with structure detection (headings, lists, tables)
- Automatic scanned page detection - extracts page images for OCR/LLM processing
- Image extraction (JPEG and PNG)
- Multi-page table handling with header deduplication
- Page markers so content can be traced back to its physical PDF page
- Footnote detection
- Bold/italic text formatting
- Encrypted PDF detection with clear error message
import "github.com/tenebris-tech/x2md/pdf2md"
converter := pdf2md.New()
err := converter.ConvertFileToFile("input.pdf", "output.md")converter := pdf2md.New(
pdf2md.WithScanMode(false), // Disable scanned page detection
pdf2md.WithExtractImages(false), // Skip image extraction
pdf2md.WithStrip(pdf2md.HeadersFooters, pdf2md.PageNumbers),
)
markdown, err := converter.ConvertFile("input.pdf")data, _ := os.ReadFile("input.pdf")
markdown, images, err := converter.ConvertWithImages(data)
// images is []*models.ImageItem with ID, Data, Format fields| Option | Description | Default |
|---|---|---|
WithScanMode(bool) |
Auto-detect scanned pages and extract as images | true |
WithStrip(...StripOption) |
Content to strip (HeadersFooters, PageNumbers, TOC, Footnotes, BlankPages) | HeadersFooters, BlankPages |
WithDetectLists(bool) |
Enable list detection | true |
WithDetectHeadings(bool) |
Enable heading detection | true |
WithPreserveFormatting(bool) |
Preserve bold/italic | true |
WithExtractImages(bool) |
Extract images | true |
WithCompact(bool) |
Remove excessive blank lines | false |
WithPageMarkers(bool) |
Emit <!-- page N --> before each page's content |
true |
So that a reader of the Markdown (typically an LLM) can cite where a passage came from, each page's content is preceded by a marker:
<!-- page 12 -->
Text that starts on page 12...Nis the 1-based physical page of the PDF (the number a viewer's "go to page" or afile.pdf#page=Nlink uses), not the number printed on the page. Stripped blank pages do not shift the numbering.- To find the page of a passage, look upward for the nearest marker.
- A table that continues across pages is preceded by
<!-- pages 3-5 -->, because a comment between table rows would break the table. The marker for the last page follows the table. - The output starts with a one-line comment describing this convention (after the source path line).
Disable with WithPageMarkers(false) or -no-location-markers.
Scanned pages are automatically detected and extracted as images:
scanned.pdf → scanned.md + scanned_images/page_001.jpg, page_002.jpg, ...
The markdown contains image references ready for OCR or LLM processing:

Detection criteria: pages with <100 characters of text and large images (>50% of page size or >500×500 pixels). Mixed documents (some scanned, some text) are handled automatically.
Images are extracted and saved to a subdirectory:
input.pdf → input.md + input_images/image_001.png, image_002.jpg, ...
- Non-standard font encodings may cause character issues
- Mathematical formulas are converted as plain text
- Encrypted PDFs are not supported
Note: 2-column page layouts are automatically detected and processed with correct reading order (left column first, then right column).
The docx2md package converts Microsoft Word documents to Markdown.
- Heading detection from Word styles (Heading 1-6)
- List support (bulleted, numbered, lettered, roman numerals) with nesting, including numbering set by paragraph styles
- Numbered headings and multi-level numbers ("1.1", "(a)", "Article 1") as Word shows them
- Text in text boxes
- Optional header and footer text
- Table extraction with markdown formatting
- Bold/italic text formatting
- Hyperlink conversion to markdown syntax
- Footnotes and endnotes
- Image extraction from embedded media
- Paragraph markers so content can be traced back to its place in the document
import "github.com/tenebris-tech/x2md/docx2md"
converter := docx2md.New()
err := converter.ConvertFileToFile("input.docx", "output.md")converter := docx2md.New(
docx2md.WithPreserveFormatting(false), // Skip bold/italic
docx2md.WithPreserveImages(false), // Skip image extraction
)
markdown, err := converter.ConvertFile("input.docx")data, _ := os.ReadFile("input.docx")
markdown, images, err := converter.ConvertWithImages(data)| Option | Description | Default |
|---|---|---|
WithPreserveFormatting(bool) |
Preserve bold/italic | true |
WithPreserveImages(bool) |
Extract and include images | true |
WithExtractHeadersFooters(bool) |
Include header text before the body and footer text after it (library only, no CLI flag) | false |
WithCompact(bool) |
Remove excessive blank lines | false |
WithParagraphMarkers(bool) |
Emit <!-- para N --> location markers |
true |
A DOCX has no fixed pages, so content is located by paragraph number instead:
<!-- para 57 -->
## 3.2 ScopeNis the 1-based position of a paragraph in the document body, counting every paragraph (w:p) in order, including paragraphs inside table cells and empty ones. Text box content stored twice for compatibility (mc:Fallback) is counted once.- The content after a marker starts at paragraph N. A marker precedes every heading and table, and appears at least every ten paragraphs elsewhere.
- To locate a passage, take the nearest marker above it and search for the passage's text from that paragraph on. A viewer that renders the DOCX to HTML one element per paragraph can scroll to the Nth paragraph directly.
- The output starts with a one-line comment describing this convention (after the source path line).
Disable with WithParagraphMarkers(false) or -no-location-markers.
Images are extracted from the DOCX media folder:
input.docx → input.md + input_images/image_001.png, image_002.jpg, ...
- Complex nested tables may not render perfectly
- Advanced formatting (text boxes, shapes, SmartArt) is ignored
- Comments and tracked changes are not included
The xlsx2md package converts Microsoft Excel spreadsheets to Markdown tables.
- Converts each worksheet to structured Markdown with range/table headings
- Emits explicit row/column indices for LLM-friendly references
- Extracts table ranges from sheet table definitions when present
- Supports shared strings, inline strings, formulas, and error values
- Formats Excel date serials and common numeric formats using sheet styles
import "github.com/tenebris-tech/x2md/xlsx2md"
converter := xlsx2md.New()
err := converter.ConvertFileToFile("input.xlsx", "output.md")| Option | Description | Default |
|---|---|---|
WithIncludeSheetNames(bool) |
Add sheet heading before each table | true |
WithSheetSeparator(string) |
Separator between sheets | "\n\n" |
WithSkipEmptyRows(bool) |
Skip empty rows | true |
WithIncludeHidden(bool) |
Include hidden rows/columns | true |
WithMarkHidden(bool) |
Mark hidden rows/columns | true |
WithShowFormulas(bool) |
Show formulas alongside cell values | true |
WithCompact(bool) |
Remove excessive blank lines | false |
- Encrypted XLSX files are not supported
make # run the full test suite, then build bin/x2md if it passed
make test # run the full test suite (the gate for developers and the build system)
make build # build bin/x2md without running tests
make clean # remove build output and drop the Go test cache
make fmt # rewrite Go files with gofmt (make test only verifies)make test runs test.sh, which verifies formatting, runs go vet, runs go test -race -count=1 ./..., then drives the compiled CLI against the documents in testdata/ and checks its output, exit codes and error messages. It ends with a summary and exits non-zero if anything failed. It needs Go and a C compiler (for the race detector) and nothing else. ./test.sh -k keeps the work directory for debugging; -n or NO_COLOR turns colour off.
make test-private runs the tests that need the private document corpus in private/, which is not in the repository. It fails, naming the file, if a document is missing.
make score converts every distinct PDF in private/ twice and scores its reading order against pdftotext. It fails if a file converts differently twice, newly fails to convert, or scores worse than the baseline; make score-accept records the run as the new baseline. Results are kept in private/.score/.
GOOS=linux GOARCH=amd64 go build -o x2md-linux ./cli
GOOS=darwin GOARCH=amd64 go build -o x2md-macos ./cli
GOOS=darwin GOARCH=arm64 go build -o x2md-macos-arm ./cli
GOOS=windows GOARCH=amd64 go build -o x2md.exe ./cliTo add a new format (e.g., RTF):
- Create package
rtf2md/withconverter.gousing functional options pattern - Implement parser in
rtf2md/rtf/ - Implement transformations in
rtf2md/transform/ - Add format detection to
convert/converter.go - Add CLI flags to
cli/main.go
This software was written in pure Go with the assistance of Claude Code.
Inspiration from:
- https://github.com/opendocsg/pdf2md (MIT License)
- https://github.com/mozilla/pdf.js (Apache 2.0 License)
Copyright (c) 2025-2026 by Tenebris Technologies Inc. This software is licensed under the MIT License. Please see LICENSE for details.
THIS SOFTWARE IS PROVIDED “AS IS,” WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Made in Canada