Skip to content

Commit

Permalink
Add text watermark with template (#22)
Browse files Browse the repository at this point in the history
Added text watermark with template: {{.Page}} {{.Pages}} {{.Filename}} variable can be used

Co-authored-by: Claudio Mola <[email protected]>
  • Loading branch information
AnkurGel and Clouz authored Dec 11, 2022
1 parent c22d471 commit d64b5c4
Show file tree
Hide file tree
Showing 3 changed files with 53 additions and 6 deletions.
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -14,4 +14,5 @@
# Project specific
builds/
tmp/
markpdf
markpdf
*.pdf
34 changes: 30 additions & 4 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,13 @@ package main

import (
"fmt"
"os"

flag "github.com/ogier/pflag"
unicommon "github.com/unidoc/unidoc/common"
"github.com/unidoc/unidoc/pdf/creator"
pdf "github.com/unidoc/unidoc/pdf/model"
"os"
"path/filepath"
"text/template"
)

var offsetX, offsetY, scaleImage, fontSize float64
Expand Down Expand Up @@ -42,12 +43,22 @@ func init() {
flag.Usage = func() {
fmt.Println("markpdf <source> <watermark> <output> [options...]")
fmt.Println("<source> and <output> should be path to a PDF file and <watermark> can be a text or path of an image.")
fmt.Println("text <watermark> can be used with the following variable:")
fmt.Println("{{.Page}} current page number")
fmt.Println("{{.Pages}} total page numbers")
fmt.Println("{{.Filename}} source file name")
fmt.Println("Example: markpdf \"path/to/083.pdf\" \"img/logo.png\" \"path/to/voucher_083.pdf\" --position=10,-10 --opacity=0.4")
fmt.Println("Example: markpdf \"path/to/083.pdf\" \"File: {{.Filename}} Page {{.Page}} of {{.Pages}}\" \"path/to/voucher_083.pdf\" --position=10,-10 --opacity=0.4")
fmt.Println("Available Options: ")
flag.PrintDefaults()
}
}

type Recipient struct {
Page, Pages int
Filename string
}

func main() {
flag.Parse()
if version {
Expand All @@ -70,7 +81,6 @@ func main() {
outputPath := args[2]
markPDF(sourcePath, outputPath, watermark)

fmt.Printf("SUCCESS: Output generated at : %s \n", outputPath)
os.Exit(0)
}

Expand All @@ -82,6 +92,7 @@ func markPDF(inputPath string, outputPath string, watermark string) error {
var para *creator.Paragraph

isImageMark := isImageMark(watermark)
watermarkIsATemplate := isWatermarkATemplate(watermark)

// Read the input pdf file.
f, err := os.Open(inputPath)
Expand All @@ -94,8 +105,19 @@ func markPDF(inputPath string, outputPath string, watermark string) error {
numPages, err := pdfReader.GetNumPages()
fatalIfError(err, fmt.Sprintf("Failed to get PageCount of the source file. [%s]", err))

// Prepare data to insert into the template.
rec := Recipient{
Pages: numPages,
Filename: filepath.Base(inputPath[:len(inputPath)-len(filepath.Ext(inputPath))]),
}
var t *template.Template
if !isImageMark && watermarkIsATemplate {
t = template.Must(template.New("watermark").Parse(watermark))
}

for i := 0; i < numPages; i++ {
pageNum := i + 1
rec.Page = pageNum

// Read the page.
page, err := pdfReader.GetPage(pageNum)
Expand All @@ -120,14 +142,18 @@ func markPDF(inputPath string, outputPath string, watermark string) error {
drawImage(watermarkImg, c)

} else {

if pageNum == 1 {
para = creator.NewParagraph(watermark)
adjustTextPosition(para, c)
}

if watermarkIsATemplate {
applyTemplate(t, &rec, para)
}

drawText(para, c)
}

}

err = c.WriteToFile(outputPath)
Expand Down
22 changes: 21 additions & 1 deletion text_watermark.go
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
package main

import (
"bytes"
"fmt"
"math"
"text/template"

"github.com/unidoc/unidoc/pdf/creator"
"github.com/unidoc/unidoc/pdf/model/fonts"
Expand Down Expand Up @@ -49,7 +51,8 @@ func adjustTextPosition(p *creator.Paragraph, c *creator.Creator) {
}

debugInfo(fmt.Sprintf("Paragraph width: %f", p.Width()))
debugInfo(fmt.Sprintf("Paragrapg height: %f", p.Height()))
debugInfo(fmt.Sprintf("Paragraph height: %f", p.Height()))
debugInfo(fmt.Sprintf("Offsets x: %f, y: %f", offsetX, offsetY))
}

func getFontByName(fontName string) fonts.Font {
Expand Down Expand Up @@ -85,3 +88,20 @@ func getFontByName(fontName string) fonts.Font {

return fonts.NewFontHelveticaBold()
}

func isWatermarkATemplate(watermark string) bool {
t := template.Must(template.New("watermark").Parse(watermark))
buf := new(bytes.Buffer)
err := t.Execute(buf, Recipient{0, 0, "out.pdf"})
if err != nil {
fatalIfError(err, fmt.Sprintf("Error parsing the template. [%s]", err))
}
return buf.String() != watermark
}

func applyTemplate(t *template.Template, rec *Recipient, para *creator.Paragraph) {
buf := new(bytes.Buffer)
err := t.Execute(buf, rec)
fatalIfError(err, fmt.Sprintf("Failed to execute watermark template: [%s]", err))
para.SetText(buf.String())
}

0 comments on commit d64b5c4

Please sign in to comment.