summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorDan Meyers <daniel_meyers@brown.edu>2017-06-10 09:32:55 -0400
committerKurt Jung <kurt.w.jung@gmail.com>2017-06-10 09:32:55 -0400
commit78cae719840c4fd9cdd4a1247842c06dde6db36e (patch)
treedc1933566d57622c16194b2813a5144a75c9ddc5
parent14c1db30737a138f8d9797cffea58783892b2fae (diff)
add the ability to include JavaScript in PDFs (#117)
-rw-r--r--def.go2
-rw-r--r--fpdf.go29
-rw-r--r--fpdf_test.go14
3 files changed, 45 insertions, 0 deletions
diff --git a/def.go b/def.go
index 54abbd1..c80eb37 100644
--- a/def.go
+++ b/def.go
@@ -247,6 +247,8 @@ type Fpdf struct {
protect protectType // document protection structure
layer layerRecType // manages optional layers in document
catalogSort bool // sort resource catalogs in document
+ nJs int // JavaScript object number
+ javascript *string // JavaScript code to include in the PDF
colorFlag bool // indicates whether fill and text colors are different
color struct {
// Composite values of colors
diff --git a/fpdf.go b/fpdf.go
index 8ab2339..78a7c65 100644
--- a/fpdf.go
+++ b/fpdf.go
@@ -3028,6 +3028,11 @@ func (f *Fpdf) SetCreationDate(tm time.Time) {
f.creationDate = tm
}
+// SetJavascript adds Adobe JavaScript to the document.
+func (f *Fpdf) SetJavascript(script string) {
+ f.javascript = &script
+}
+
func (f *Fpdf) putpages() {
var wPt, hPt float64
var pageSize SizeType
@@ -3475,6 +3480,25 @@ func (f *Fpdf) putGradients() {
}
}
+func (f *Fpdf) putjavascript() {
+ if f.javascript == nil {
+ return
+ }
+
+ f.newobj()
+ f.nJs = f.n
+ f.out("<<")
+ f.outf("/Names [(EmbeddedJS) %d 0 R]", f.n+1)
+ f.out(">>")
+ f.out("endobj")
+ f.newobj()
+ f.out("<<")
+ f.out("/S /JavaScript")
+ f.outf("/JS %s", f.textstring(*f.javascript))
+ f.out(">>")
+ f.out("endobj")
+}
+
func (f *Fpdf) putresources() {
if f.err != nil {
return
@@ -3495,6 +3519,7 @@ func (f *Fpdf) putresources() {
f.putresourcedict()
f.out(">>")
f.out("endobj")
+ f.putjavascript()
if f.protect.encrypted {
f.newobj()
f.protect.objNum = f.n
@@ -3572,6 +3597,10 @@ func (f *Fpdf) putcatalog() {
}
// Layers
f.layerPutCatalog()
+ // JavaScript
+ if f.javascript != nil {
+ f.outf("/Names <</JavaScript %d 0 R>>", f.nJs)
+ }
}
func (f *Fpdf) putheader() {
diff --git a/fpdf_test.go b/fpdf_test.go
index 456295c..5781ad6 100644
--- a/fpdf_test.go
+++ b/fpdf_test.go
@@ -1857,3 +1857,17 @@ func ExampleFpdf_Rect() {
// Output:
// Successfully generated pdf/Fpdf_WrappedTableCells.pdf
}
+
+// This example demonstrates including JavaScript in the document.
+func ExampleFpdf_SetJavascript() {
+ pdf := gofpdf.New("P", "mm", "A4", "")
+ pdf.SetJavascript("print(true);")
+ pdf.AddPage()
+ pdf.SetFont("Arial", "", 12)
+ pdf.Write(10, "Auto-print.")
+ fileStr := example.Filename("Fpdf_SetJavascript")
+ err := pdf.OutputFileAndClose(fileStr)
+ example.Summary(err, fileStr)
+ // Output:
+ // Successfully generated pdf/Fpdf_SetJavascript.pdf
+}