Skip to content

Instantly share code, notes, and snippets.

@grafov
Last active October 12, 2019 22:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save grafov/ba136262bcc469335eade27e72a7ac64 to your computer and use it in GitHub Desktop.
Save grafov/ba136262bcc469335eade27e72a7ac64 to your computer and use it in GitHub Desktop.
Very specific utility for my workflow with Kyocera MFU, it reorders the pages of a two-sided document scanned from two sides in two batches. MFU creates PDF with pages for example 1,2,3,6,5,4 and the utility reorders them to 1,2,3,4,5,6. The example of manipulating PDF in native Go without external utilities.
package main
import (
"fmt"
"io/ioutil"
"os"
"path"
"path/filepath"
"strings"
pdf "github.com/pdfcpu/pdfcpu/pkg/api"
)
func main() {
if len(os.Args) < 3 {
os.Exit(1)
}
in := os.Args[1]
out := os.Args[2]
var (
tmp string
err error
)
var pcount int
if pcount, err = pdf.PageCount(in); err != nil {
fmt.Printf("%v\n", err)
}
if pcount < 1 {
fmt.Printf("error: document has %d pages\n", pcount)
os.Exit(1)
}
tmp, err = ioutil.TempDir("", "pdf2sides-")
if err != nil {
os.Exit(1)
}
defer os.RemoveAll(tmp)
// Create single page PDFs for in.pdf in outDir using the default configuration.
pdf.SplitFile(in, tmp, 1, nil)
var (
ext = filepath.Ext(in)
base = filepath.Base(strings.TrimRight(in, ext))
infiles []string
)
for p := 1; p <= pcount/2; p++ {
lname := path.Join(tmp, fmt.Sprintf("%s_%d%s", base, p, ext))
infiles = append(infiles, lname)
if pcount-p+1 == p {
break
}
rname := path.Join(tmp, fmt.Sprintf("%s_%d%s", base, pcount-p+1, ext))
infiles = append(infiles, rname)
}
if err = pdf.MergeFile(infiles, out, nil); err != nil {
fmt.Printf("%v\n", err)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment