|
| 1 | +/* |
| 2 | + * An example of adding text watermark to pdf pages. |
| 3 | + * |
| 4 | + * Run as: go run pdf_add_text_watermark.go <input.pdf> <watermark text> <output.pdf> |
| 5 | + */ |
| 6 | +package main |
| 7 | + |
| 8 | +import ( |
| 9 | + "fmt" |
| 10 | + "image/color" |
| 11 | + "os" |
| 12 | + |
| 13 | + "github.com/unidoc/unipdf/v3/common/license" |
| 14 | + "github.com/unidoc/unipdf/v3/creator" |
| 15 | + "github.com/unidoc/unipdf/v3/model" |
| 16 | +) |
| 17 | + |
| 18 | +func init() { |
| 19 | + // Make sure to load your metered License API key prior to using the library. |
| 20 | + // If you need a key, you can sign up and create a free one at https://cloud.unidoc.io |
| 21 | + err := license.SetMeteredKey(os.Getenv(`UNIDOC_LICENSE_API_KEY`)) |
| 22 | + if err != nil { |
| 23 | + panic(err) |
| 24 | + } |
| 25 | +} |
| 26 | + |
| 27 | +func main() { |
| 28 | + if len(os.Args) < 4 { |
| 29 | + fmt.Printf("Usage: go run pdf_add_text_watermark.go input.pdf watermark output.pdf\n") |
| 30 | + os.Exit(1) |
| 31 | + } |
| 32 | + |
| 33 | + inputPath := os.Args[1] |
| 34 | + watermark := os.Args[2] |
| 35 | + outputPath := os.Args[3] |
| 36 | + |
| 37 | + file, err := os.Open(inputPath) |
| 38 | + if err != nil { |
| 39 | + fmt.Printf("Error: %v\n", err) |
| 40 | + os.Exit(1) |
| 41 | + } |
| 42 | + defer file.Close() |
| 43 | + |
| 44 | + pdfReader, err := model.NewPdfReader(file) |
| 45 | + if err != nil { |
| 46 | + fmt.Printf("Error: %v\n", err) |
| 47 | + os.Exit(1) |
| 48 | + } |
| 49 | + |
| 50 | + c := creator.New() |
| 51 | + |
| 52 | + totalPageNumb, err := pdfReader.GetNumPages() |
| 53 | + if err != nil { |
| 54 | + fmt.Printf("Error: %v\n", err) |
| 55 | + os.Exit(1) |
| 56 | + } |
| 57 | + |
| 58 | + for i := 1; i <= totalPageNumb; i++ { |
| 59 | + page, err := pdfReader.GetPage(i) |
| 60 | + if err != nil { |
| 61 | + fmt.Printf("Error: failed to get page %d. %v\n", i, err) |
| 62 | + os.Exit(1) |
| 63 | + } |
| 64 | + options := model.WatermarkTextOptions{ |
| 65 | + Alpha: 0.3, |
| 66 | + FontSize: 40, |
| 67 | + FontPath: "Roboto-Regular.ttf", |
| 68 | + FontColor: color.RGBA{R: 255, G: 0, B: 0, A: 1}, |
| 69 | + Angle: 30, |
| 70 | + } |
| 71 | + |
| 72 | + err = page.AddWatermarkText(watermark, options) |
| 73 | + if err != nil { |
| 74 | + fmt.Printf("Error: failed to add watermark on page %d. %v\n", i, err) |
| 75 | + } |
| 76 | + |
| 77 | + c.AddPage(page) |
| 78 | + } |
| 79 | + |
| 80 | + c.WriteToFile(outputPath) |
| 81 | + fmt.Print("Watermark added successfully.\n") |
| 82 | +} |
0 commit comments