Created
November 5, 2019 18:57
-
-
Save grafov/1254daedfa827f1478db230475814e1e to your computer and use it in GitHub Desktop.
Split PDF and merge pages back in a reverse order.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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("", "pdf2reverse-") | |
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 := pcount; p >= 1; p-- { | |
infiles = append(infiles, path.Join(tmp, fmt.Sprintf("%s_%d%s", base, p, ext))) | |
} | |
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