cpdf-source/cpdftexttopdf.ml

45 lines
1.3 KiB
OCaml
Raw Normal View History

2021-12-07 00:55:46 +01:00
open Pdfutil
let of_utf8 (f, fontsize) t =
Pdftext.codepoints_of_utf8 t
|> option_map (Pdftext.charcode_extractor_of_font_real f)
|> map char_of_int
|> implode
let of_pdfdocencoding (f, fontsize) t =
of_utf8 (f, fontsize) (Pdftext.utf8_of_pdfdocstring t)
let rec of_utf8_with_newlines t =
let items = ref [] in
let buf = Buffer.create 256 in
String.iter
(function
| '\n' ->
let c = Buffer.contents buf in
if c <> "" then items := Cpdftype.Text (explode c)::!items;
items := Cpdftype.NewLine::!items;
Buffer.clear buf
2021-12-11 14:17:44 +01:00
| '\r' -> ()
2021-12-07 00:55:46 +01:00
| x ->
Buffer.add_char buf x)
t;
(* Do last one *)
let c = Buffer.contents buf in
if c <> "" then items := Text (explode c)::!items;
rev !items
2021-12-29 16:58:03 +01:00
let typeset ~papersize ~font ~fontsize text =
2021-12-07 00:55:46 +01:00
let pdf = Pdf.empty () in
2021-12-29 16:58:03 +01:00
let margin =
2022-09-13 18:59:13 +02:00
Pdfunits.convert
72. (Pdfpaper.unit papersize) (Pdfunits.PdfPoint) (Pdfpaper.width papersize) /. 15.
2021-12-29 16:58:03 +01:00
in
2021-12-07 00:55:46 +01:00
let pages =
Cpdftype.typeset
2021-12-29 16:58:03 +01:00
margin margin margin margin papersize pdf
2022-09-13 18:59:13 +02:00
([Cpdftype.Font (font, fontsize); Cpdftype.BeginDocument] @
of_utf8_with_newlines (Pdfio.string_of_bytes text))
2021-12-07 00:55:46 +01:00
in
let pdf, pageroot = Pdfpage.add_pagetree pages pdf in
Pdfpage.add_root pageroot [] pdf