-
Notifications
You must be signed in to change notification settings - Fork 102
/
pdf_images_to_pdf.go
60 lines (48 loc) · 1.31 KB
/
pdf_images_to_pdf.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
/*
* Add images to a PDF file, one image per page.
*
* Run as: go run pdf_images_to_pdf.go output.pdf img1.jpg img2.jpg img3.png ...
*/
package main
import (
"fmt"
"os"
unicommon "github.com/unidoc/unipdf/v3/common"
"github.com/unidoc/unipdf/v3/creator"
)
func main() {
if len(os.Args) < 3 {
fmt.Printf("Usage: go run pdf_add_images.go output.pdf img1.jpg img2.jpg ...\n")
os.Exit(1)
}
outputPath := os.Args[1]
inputPaths := os.Args[2:len(os.Args)]
err := imagesToPdf(inputPaths, outputPath)
if err != nil {
fmt.Printf("Error: %v\n", err)
os.Exit(1)
}
fmt.Printf("Complete, see output file: %s\n", outputPath)
}
// Images to PDF.
func imagesToPdf(inputPaths []string, outputPath string) error {
c := creator.New()
for _, imgPath := range inputPaths {
unicommon.Log.Debug("Image: %s", imgPath)
img, err := c.NewImageFromFile(imgPath)
if err != nil {
unicommon.Log.Debug("Error loading image: %v", err)
return err
}
img.ScaleToWidth(612.0)
// Use page width of 612 points, and calculate the height proportionally based on the image.
// Standard PPI is 72 points per inch, thus a width of 8.5"
height := 612.0 * img.Height() / img.Width()
c.SetPageSize(creator.PageSize{612, height})
c.NewPage()
img.SetPos(0, 0)
_ = c.Draw(img)
}
err := c.WriteToFile(outputPath)
return err
}