-
Notifications
You must be signed in to change notification settings - Fork 104
/
Copy pathpdf_images_to_pdf.go
71 lines (58 loc) · 1.67 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
61
62
63
64
65
66
67
68
69
70
71
/*
* 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"
"github.com/unidoc/unipdf/v3/common"
"github.com/unidoc/unipdf/v3/common/license"
"github.com/unidoc/unipdf/v3/creator"
)
func init() {
// Make sure to load your metered License API key prior to using the library.
// If you need a key, you can sign up and create a free one at https://cloud.unidoc.io
err := license.SetMeteredKey(os.Getenv(`UNIDOC_LICENSE_API_KEY`))
if err != nil {
panic(err)
}
}
func main() {
if len(os.Args) < 3 {
fmt.Printf("Usage: go run pdf_images_to_pdf.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 {
common.Log.Debug("Image: %s", imgPath)
img, err := c.NewImageFromFile(imgPath)
if err != nil {
common.Log.Debug("Error loading image: %v", err)
return err
}
// 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"
pageWidth := 612.0
img.ScaleToWidth(pageWidth)
pageHeight := pageWidth * img.Height() / img.Width()
c.SetPageSize(creator.PageSize{pageWidth, pageHeight})
c.NewPage()
img.SetPos(0, 0)
_ = c.Draw(img)
}
err := c.WriteToFile(outputPath)
return err
}