#!/bin/bash
# -*- scheme -*-
exec guile --debug -e main -s "$0" "$@"
!#

;;; Commentary:
;;
;; @section Overview
;;
;; @code{org-to-pdf-presentation} is a command-line script offered by
;; Guile-Lib that can transform a file written in Emacs' Org Mode and
;; directly produce a PDF file, suitable for presenting with a PDF
;; viewer.
;;
;; @code{org-to-pdf-presentation} works by rendering each slide as an
;; SVG, then using @code{librsvg} to convert the SVGs to one PDF of many
;; pages. You will need the tool, @code{rsvg-convert}, provided under
;; Debian as @code{librsvg2-bin}.
;;
;; @section Usage
;;
;; @deffn Command org-to-pdf-presentation in-org-file out-pdf-file
;;
;; Convert the Org Mode file @var{in-org-file} into a PDF suitable for
;; presentations.
;;
;; This command is subject to the limitations of
;; @code{org->presentation}. Namely, only a subset of all Org Mode
;; constructs are supported. @xref{present org-mode
;; org->presentation,,org->presentation}, for more information.
;; @end deffn
;;
;;; Code:

(use-modules (present org-mode)
             (present svg)
             (rsvg)
             (cairo)
             (sxml simple))

(define *pdf-width* 1024)
(define *pdf-height* 768)

(define (org->pdf in out)
  (let* ((presentation (call-with-input-file in org->presentation))
         (org-params (cdr (assq 'org-params (cdadr presentation))))
         (svg (presentation->svg presentation))
         (surf (cairo-pdf-surface-create *pdf-width* *pdf-height* out))
         (ctx (cairo-create surf)))
    (define paint-background
      (let ((bg-handle (and=> (assq-ref org-params 'SVG-BACKGROUND)
                              rsvg-handle-new-from-file)))
        (lambda ()
          (if bg-handle
              (rsvg-handle-render-cairo bg-handle ctx)))))
    (for-each
     (lambda (slide)
       (let ((handle (rsvg-handle-new-from-data
                      (with-output-to-string
                        (lambda ()
                          (sxml->xml
                           `(,(car svg) ,(cadr svg) ,slide)))))))
         (paint-background)
         (rsvg-handle-render-cairo handle ctx)
         (cairo-show-page ctx)))
     (cddr svg))
    (cairo-surface-finish surf)))

(define (main args)
  (or (= (length args) 3)
      (begin
        (format (current-error-port) "usage: ~A ORG-FILE OUTPUT-PDF-FILE\n"
                (car args))
        (exit 1)))
  (setlocale LC_ALL "")
  (apply org->pdf (cdr args)))
