package main
import (
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"time"
)
const apiURL = "https://api.markpdf.tech"
const apiKey = "TU_API_KEY"
type AcceptedJob struct {
JobID string `json:"job_id"`
RetryAfterSeconds int `json:"retry_after_seconds"`
}
type JobStatus struct {
Status string `json:"status"`
Body string `json:"body"`
Error string `json:"error"`
}
func convert(pdfPath string) (string, error) {
f, err := os.Open(pdfPath)
if err != nil {
return "", err
}
defer f.Close()
req, _ := http.NewRequest("POST", apiURL+"/convert/raw?filename="+pdfPath+"&mode=fast", f)
req.Header.Set("x-api-key", apiKey)
req.Header.Set("content-type", "application/pdf")
res, err := http.DefaultClient.Do(req)
if err != nil {
return "", err
}
defer res.Body.Close()
if res.StatusCode == 200 {
body, _ := io.ReadAll(res.Body)
return string(body), nil
}
if res.StatusCode == 202 {
var job AcceptedJob
json.NewDecoder(res.Body).Decode(&job)
delay := time.Duration(job.RetryAfterSeconds) * time.Second
if delay == 0 {
delay = 5 * time.Second
}
for {
time.Sleep(delay)
pollReq, _ := http.NewRequest("GET", fmt.Sprintf("%s/jobs/%s", apiURL, job.JobID), nil)
pollReq.Header.Set("x-api-key", apiKey)
pollRes, err := http.DefaultClient.Do(pollReq)
if err != nil {
return "", err
}
var status JobStatus
json.NewDecoder(pollRes.Body).Decode(&status)
pollRes.Body.Close()
switch status.Status {
case "completed":
return status.Body, nil
case "failed":
return "", fmt.Errorf("job %s failed: %s", job.JobID, status.Error)
}
}
}
body, _ := io.ReadAll(res.Body)
return "", fmt.Errorf("HTTP %d: %s", res.StatusCode, body)
}
func main() {
md, err := convert("informe.pdf")
if err != nil {
panic(err)
}
fmt.Println(md)
}