ghostscript.go 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. package main
  2. // This command demonstrates the use of ghotscript to reduce the size
  3. // of generated PDFs. This is based on a comment made by farkerhaiku:
  4. // https://github.com/jung-kurt/gofpdf/issues/57#issuecomment-185843315
  5. import (
  6. "fmt"
  7. "os"
  8. "os/exec"
  9. "github.com/jung-kurt/gofpdf"
  10. )
  11. func report(fileStr string, err error) {
  12. if err == nil {
  13. var info os.FileInfo
  14. info, err = os.Stat(fileStr)
  15. if err == nil {
  16. fmt.Printf("%s: OK, size %d\n", fileStr, info.Size())
  17. } else {
  18. fmt.Printf("%s: bad stat\n", fileStr)
  19. }
  20. } else {
  21. fmt.Printf("%s: %s\n", fileStr, err)
  22. }
  23. }
  24. func newPdf() (pdf *gofpdf.Fpdf) {
  25. pdf = gofpdf.New("P", "mm", "A4", "../../font")
  26. pdf.SetCompression(false)
  27. pdf.AddFont("Calligrapher", "", "calligra.json")
  28. pdf.AddPage()
  29. pdf.SetFont("Calligrapher", "", 35)
  30. pdf.Cell(0, 10, "Enjoy new fonts with FPDF!")
  31. return
  32. }
  33. func full(name string) {
  34. report(name, newPdf().OutputFileAndClose(name))
  35. }
  36. func min(name string) {
  37. cmd := exec.Command("gs", "-sDEVICE=pdfwrite",
  38. "-dCompatibilityLevel=1.4",
  39. "-dPDFSETTINGS=/screen", "-dNOPAUSE", "-dQUIET",
  40. "-dBATCH", "-sOutputFile="+name, "-")
  41. inPipe, err := cmd.StdinPipe()
  42. if err == nil {
  43. errChan := make(chan error, 1)
  44. go func() {
  45. errChan <- cmd.Start()
  46. }()
  47. err = newPdf().Output(inPipe)
  48. if err == nil {
  49. report(name, <-errChan)
  50. } else {
  51. report(name, err)
  52. }
  53. } else {
  54. report(name, err)
  55. }
  56. }
  57. func main() {
  58. full("full.pdf")
  59. min("min.pdf")
  60. }