61 lines
1.2 KiB
Go
61 lines
1.2 KiB
Go
package main
|
|
|
|
import (
|
|
"bytes"
|
|
"fmt"
|
|
"io"
|
|
"net/http"
|
|
"time"
|
|
|
|
"github.com/pdfcpu/pdfcpu/pkg/api"
|
|
)
|
|
|
|
var httpClient = &http.Client{Timeout: 25 * time.Second}
|
|
|
|
type fetchError struct {
|
|
URL string
|
|
HTTPStatus int // 0 = network/timeout
|
|
}
|
|
|
|
func (e *fetchError) Error() string {
|
|
if e.HTTPStatus != 0 {
|
|
return fmt.Sprintf("source %s returned HTTP %d", e.URL, e.HTTPStatus)
|
|
}
|
|
return fmt.Sprintf("failed to fetch source %s", e.URL)
|
|
}
|
|
|
|
func fetchPDF(url string) ([]byte, error) {
|
|
resp, err := httpClient.Get(url)
|
|
if err != nil {
|
|
return nil, &fetchError{URL: url, HTTPStatus: 0}
|
|
}
|
|
defer resp.Body.Close()
|
|
|
|
if resp.StatusCode != http.StatusOK {
|
|
return nil, &fetchError{URL: url, HTTPStatus: resp.StatusCode}
|
|
}
|
|
|
|
data, err := io.ReadAll(resp.Body)
|
|
if err != nil {
|
|
return nil, &fetchError{URL: url, HTTPStatus: 0}
|
|
}
|
|
return data, nil
|
|
}
|
|
|
|
func mergePDFs(urls []string) ([]byte, error) {
|
|
readers := make([]io.ReadSeeker, 0, len(urls))
|
|
for _, url := range urls {
|
|
data, err := fetchPDF(url)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
readers = append(readers, bytes.NewReader(data))
|
|
}
|
|
|
|
var buf bytes.Buffer
|
|
if err := api.MergeRaw(readers, &buf, false, nil); err != nil {
|
|
return nil, fmt.Errorf("PDF merge error: %w", err)
|
|
}
|
|
return buf.Bytes(), nil
|
|
}
|