Convert PDF to Markdown in Go
A typed, dependency-free way to turn PDFs into Markdown from Go. The example uses only net/http and encoding/json from the standard library, decodes the job into a struct, and compiles to a single static binary you can drop into a service.
Check the output, then use it
Use the live OpenAPI contract. Check HTTP failures, queued/processing/ready/error, a polling deadline and truncated before downloading. Keep API keys server-side.
Server processing; temporary results. Review numbers and OCR mistakes against the original.
One struct, three requests
Model the job as a Go struct with json tags, then make three net/http calls: POST the PDF to /api/v2/jobs to get a job_id, poll /api/v2/jobs/{job_id} until Status is ready, and GET /api/v2/jobs/{job_id}/download for the Markdown. No SDK, no cgo, no GPU – the conversion, OCR and table work all happen server-side.
The full program
Save as convert.go and run go run convert.go. Standard library only.
// Go 1.21+. Set P2M_API_KEY and optionally PDF_URL in the server environment.
package main
import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"strings"
"time"
)
const api = "https://pdf2md.dev/api/v2"
type job struct {
JobID string `json:"job_id"`
Status string `json:"status"`
Truncated bool `json:"truncated"`
ErrorCode string `json:"error_code"`
}
var client = &http.Client{Timeout: 30 * time.Second}
func request(ctx context.Context, method, path, body string) ([]byte, error) {
req, err := http.NewRequestWithContext(ctx, method, api+path, strings.NewReader(body))
if err != nil {
return nil, err
}
req.Header.Set("Authorization", "Bearer "+os.Getenv("P2M_API_KEY"))
if body != "" {
req.Header.Set("Content-Type", "application/json")
}
res, err := client.Do(req)
if err != nil {
return nil, err
}
defer res.Body.Close()
if res.StatusCode == 429 {
return nil, fmt.Errorf("rate limited; retry after %s seconds", res.Header.Get("Retry-After"))
}
if res.StatusCode < 200 || res.StatusCode >= 300 {
return nil, fmt.Errorf("HTTP %d", res.StatusCode)
}
return io.ReadAll(res.Body)
}
func convertOne(ctx context.Context, input string) error {
payload, err := json.Marshal(map[string]any{"url": input, "options": map[string]string{"image_mode": "placeholder", "ocr_lang": "en"}})
if err != nil {
return err
}
data, err := request(ctx, "POST", "/jobs", string(payload))
if err != nil {
return err
}
var j job
if err = json.Unmarshal(data, &j); err != nil {
return err
}
if j.JobID == "" {
return fmt.Errorf("missing job_id")
}
id := j.JobID
for {
data, err = request(ctx, "GET", "/jobs/"+id, "")
if err != nil {
return err
}
if err = json.Unmarshal(data, &j); err != nil {
return err
}
if j.Status == "ready" {
break
}
if j.Status == "error" || j.Status == "canceled" || j.Status == "deleted" {
return fmt.Errorf("job ended: %s %s", j.Status, j.ErrorCode)
}
select {
case <-ctx.Done():
return ctx.Err()
case <-time.After(3 * time.Second):
}
}
md, err := request(ctx, "GET", "/jobs/"+id+"/download", "")
if err != nil {
return err
}
if j.Truncated {
fmt.Fprintln(os.Stderr, "Partial result; verify missing pages")
}
return os.WriteFile("document.md", md, 0600)
}
func main() {
if os.Getenv("P2M_API_KEY") == "" {
fmt.Fprintln(os.Stderr, "Set P2M_API_KEY")
os.Exit(1)
}
input := os.Getenv("PDF_URL")
if input == "" {
input = "https://example.com/document.pdf"
}
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Minute)
defer cancel()
if err := convertOne(ctx, input); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
}
Why a struct: decoding into a typed job gives you compile-time safety on Status, ErrorCode and Truncated, and the decoder simply ignores any response fields you do not model.
Convert many PDFs at once
Where Go shines is fan-out. To convert a batch, run each file's create-poll-download sequence in a goroutine and bound them with a semaphore so you stay friendly to the API.
Bounded worker pool
Use a buffered channel as a semaphore: sem := make(chan struct{}, 5). Each goroutine takes a slot before it starts and releases it when done, so at most five conversions run concurrently. Collect results with a sync.WaitGroup.
Context and timeouts
NewRequestWithContext cancels a stuck request cleanly.processing_timeout or conversion_failed tells you why a job failed; truncated flags a partial result.Prefer another language? See the Node.js tutorial, the Python tutorial, or the cURL recipe.
Wiring it into a service?
The conversion is also a hosted MCP endpoint, so a Go-based agent can call it as a tool. The full reference and the OpenAPI spec are on the developer hub.
A bounded worker pool
Wrap the single-file flow from above in convertOne, then fan out over a list of PDFs with a semaphore that caps how many run at once.
// convertOne runs the create -> poll -> download flow for one URL.
func convertAll(ctx context.Context, urls []string) {
sem := make(chan struct{}, 5) // at most 5 conversions in flight
var wg sync.WaitGroup
for _, u := range urls {
wg.Add(1)
go func(url string) {
defer wg.Done()
sem <- struct{}{} // take a slot (blocks if full)
defer func() { <-sem }() // release it
if err := convertOne(ctx, url); err != nil {
log.Printf("skip %s: %v", url, err)
}
}(u)
}
wg.Wait()
}
The buffered channel is the entire rate limiter: a goroutine cannot start real work until it has pushed into sem, and only five tokens exist. Increase the buffer for more throughput on a higher tier, decrease it to be gentle on the free tier. Pair this with a per-file Idempotency-Key so a rerun after a crash does not reconvert what already finished, and the same pool handles a folder of ten PDFs or ten thousand.
Common questions
Does the Go example need any dependencies?
No. It uses only the standard library (net/http and encoding/json), so go run convert.go works with no modules to add and compiles to a single static binary.
How do I map the JSON response in Go?
Define a struct with json tags for job_id, status, error_code, error_message and truncated, then decode with json.NewDecoder. Fields you do not list are simply ignored.
How do I convert many PDFs concurrently in Go?
Run the create, poll and download sequence inside goroutines and bound them with a buffered channel used as a semaphore, so you convert several files at once without flooding the API.
How do I add a timeout or cancellation?
Use context.WithTimeout with http.NewRequestWithContext so a stuck request is cancelled. The server also enforces its own time budget and returns error_code processing_timeout when a document is too large.
How do I upload a local PDF file in Go?
Build a multipart/form-data body with mime/multipart, write the PDF into a file field, set the Content-Type to the multipart boundary, and POST it to /api/v2/jobs instead of the JSON url body.