Emacs打印缓冲区的自动换行到PDF

时间:2011-09-09 13:48:00

标签: emacs pdf-generation elisp emacs23

我使用此功能将缓冲区的内容打印为PDF

(来自我的.emacs文件:)

(defun print-to-pdf ()
  (interactive)
  (ps-spool-buffer-with-faces)
  (switch-to-buffer "*PostScript*")
  (write-file "/tmp/tmp.ps")
  (kill-buffer "tmp.ps")
  (setq cmd (concat "ps2pdf14 /tmp/tmp.ps /home/user/" (buffer-name) ".pdf"))
  (shell-command cmd)
  (shell-command "rm /tmp/tmp.ps")
  (message (concat "Saved to:  /home/user/" (buffer-name) ".pdf"))  
  )

但是,我无法在将 PostScript 缓冲区写入磁盘之前找到启用或应用可视行次要模式的方法,以便在输出中启用自动换行。

1 个答案:

答案 0 :(得分:5)

获得视线模式的问题在于它插入了“软换行符”(PS渲染器会忽略它)。解决方案是用硬换行替换这些。我想,下面的代码可以满足您的需求。请注意,我们在临时缓冲区中调用harden-newlines,以免弄乱当前文档。此外,我已将输出目标更改为始终位于/tmp/print.pdf。在没有任何警告的情况下覆盖/home中的文档似乎是不明智的!您随后可以随后移动PDF。

无论如何,你走了。这是你想要的吗?

(defun harden-newlines ()
  (interactive)
  "Make all the newlines in the buffer hard."
  (save-excursion
    (goto-char (point-min))
    (while (search-forward "\n" nil t)
      (backward-char)
      (put-text-property (point) (1+ (point)) 'hard t)
      (forward-char))))

(defun spool-buffer-given-name (name)
  (load "ps-print")
  (let ((tmp ps-left-header))
    (unwind-protect
        (progn
          (setq ps-left-header
                (list (lambda () name) 'ps-header-dirpart))
          (ps-spool-buffer-with-faces))
      (setf ps-left-header tmp))))

(defun print-to-pdf ()
  "Print the current file to /tmp/print.pdf"
  (interactive)
  (let ((wbuf (generate-new-buffer "*Wrapped*"))
        (sbuf (current-buffer)))
    (jit-lock-fontify-now)
    (save-current-buffer
      (set-buffer wbuf)
      (insert-buffer sbuf)
      (longlines-mode t)
      (harden-newlines)
      (spool-buffer-given-name (buffer-name sbuf))
      (kill-buffer wbuf)
      (switch-to-buffer "*PostScript*")
      (write-file "/tmp/print.ps")
      (kill-buffer (current-buffer)))
    (call-process "ps2pdf14" nil nil nil
                  "/tmp/print.ps" "/tmp/print.pdf")
    (delete-file "/tmp/print.ps")
    (message "PDF saved to /tmp/print.pdf")))