Go处理PDF的实现代码

2020-01-28 14:14:18于丽

二、PDF加水印

我了解到的支持pdf加水印的工具有:

unidoc/unipdf pdfcpu

1.unidoc/unipdf

unidoc平台开发的unipdf是一款用Go语言编写的PDF库,提供API和CLI使用模式,支持以下功能:


$ unipdf -h
...
Available Commands:
 decrypt   Decrypt PDF files
 encrypt   Encrypt PDF files
 explode   Explodes the input file into separate single page PDF files
 extract   Extract PDF resources
 form    PDF form operations
 grayscale  Convert PDF to grayscale
 help    Help about any command
 info    Output PDF information
 merge    Merge PDF files
 optimize  Optimize PDF files
 passwd   Change PDF passwords
 rotate   Rotate PDF file pages
 search   Search text in PDF files
 split    Split PDF files
 version   Output version information and exit
 watermark  Add watermark to PDF files
...

CLI模式添加水印


$ unipdf watermark in.pdf watermark.png -o out.pdf

Watermark successfully applied to in.pdf
Output file saved to out.pdf

使用API添加水印,可以直接参考unipdf github example

注意:unidoc的产品需要付费购买license使用

2.pdfcpu

pdfcpu 是一个用Go语言编写的PDF处理库,提供API和CLI模式使用

支持以下功能:


$ pdfcpu help
...
The commands are:

  attachments list, add, remove, extract embedded file attachments
  changeopw  change owner password
  changeupw  change user password
  decrypt   remove password protection
  encrypt   set password protection
  extract   extract images, fonts, content, pages, metadata
  fonts    install, list supported fonts
  grid    rearrange pages or images for enhanced browsing experience
  import   import/convert images to PDF
  info    print file info
  merge    concatenate 2 or more PDFs
  nup     rearrange pages or images for reduced number of pages
  optimize  optimize PDF by getting rid of redundant page resources
  pages    insert, remove selected pages
  paper    print list of supported paper sizes
  permissions list, set user access permissions
  rotate   rotate pages
  split    split multi-page PDF into several PDFs according to split span
  stamp    add, remove, update text, image or PDF stamps for selected pages
  trim    create trimmed version of selected pages
  validate  validate PDF against PDF 32000-1:2008 (PDF 1.7)
  version   print version
  watermark  add, remove, update text, image or PDF watermarks for selected pages
...

使用CLI工具以图片形式添加水印:


$ pdfcpu watermark add -mode image 'voucher_watermark.png' 's:1 abs, rot:0' in.pdf out.pdf

调用api添加水印


package main

import (
  "github.com/pdfcpu/pdfcpu/pkg/api"
  "github.com/pdfcpu/pdfcpu/pkg/pdfcpu"
)

func main() {
  onTop := false
  wm, _ := pdfcpu.ParseImageWatermarkDetails("watermark.png", "s:1 abs, rot:0", onTop)
  api.AddWatermarksFile("in.pdf", "out.pdf", nil, wm, nil)
}