4 * (c) 2018--2022 Martin Mares <mj@ucw.cz>
16 class null_cmd : public cmd_exec {
18 null_cmd(cmd *c UNUSED) { }
19 vector<page *> process(vector<page *> &pages) override { return pages; }
22 static const arg_def no_args[] = {
26 /*** Generic routines ***/
28 // Commands acting on individual pages
30 class cmd_exec_simple : public cmd_exec {
31 virtual page *process_page(page *p) = 0;
32 vector<page *> process(vector<page *> &pages) override;
35 vector<page *> cmd_exec_simple::process(vector<page *> &pages)
39 out.push_back(process_page(p));
43 // Paper specifications
48 paper_spec(cmd *c, bool maybe=true)
50 arg_val *aname = c->arg("paper");
51 arg_val *aw = c->arg("w");
52 arg_val *ah = c->arg("h");
53 if (!aname->given() && !aw->given() && !ah->given() && maybe)
58 if (aw->given() != ah->given() || aname->given() == aw->given())
59 err("Either paper format name or width and height must be given");
62 const char *name = aname->as_string("").c_str();
63 const paper *pap = paperinfo(name);
65 err("No paper called \"%s\" is known", name);
66 w = paperpswidth(pap);
67 h = paperpsheight(pap);
78 { "paper", AT_STRING | AT_POSITIONAL, "Paper format name (e.g., a4)" }, \
79 { "w", AT_DIMEN, "Paper width" }, \
80 { "h", AT_DIMEN, "Paper height" }
82 // Position specification
87 pos_spec() { v = h = 0; }
91 err("Value of pos must have two characters");
99 err("First character of pos must be t/c/b");
102 else if (s[1] == 'c')
104 else if (s[1] == 'r')
107 err("Second character of pos must be l/c/r");
109 pos_spec(cmd *c) : pos_spec(c->arg("pos")->as_string("cc")) { }
110 pdf_matrix place(BBox &inner, BBox &outer)
113 m.shift(-inner.x_min, -inner.y_min);
119 m.shift((outer.width() - inner.width()) / 2, 0);
122 m.shift(outer.width() - inner.width(), 0);
132 m.shift(0, (outer.height() - inner.height()) / 2);
135 m.shift(0, outer.height() - inner.height());
140 m.shift(outer.x_min, outer.y_min);
146 { "pos", AT_STRING, "Position on the page: (t|c|b)(l|c|r)" }
153 margin_spec(cmd *c, string basic, string sx)
156 m = c->arg(basic)->as_double(0);
157 h = c->arg("h" + sx)->as_double(m);
158 v = c->arg("v" + sx)->as_double(m);
159 l = c->arg("l" + sx)->as_double(h);
160 r = c->arg("r" + sx)->as_double(h);
161 t = c->arg("t" + sx)->as_double(v);
162 b = c->arg("b" + sx)->as_double(v);
164 bool may_shrink(BBox *bb)
166 return (bb->width() > l+r && bb->height() > t+b);
168 void shrink_box(BBox *bb)
174 if (bb->x_min >= bb->x_max || bb->y_min >= bb->y_max)
175 err("Margins cannot be larger than the whole page");
177 void expand_box(BBox *bb)
186 #define MARGIN_ARGS1_NAMED(name) \
187 { name, AT_DIMEN, "Size of all margins (default: 0)" }
189 #define MARGIN_ARGS1_POSNL(name) \
190 { name, AT_DIMEN | AT_POSITIONAL, "Size of all margins (default: 0)" }
192 #define MARGIN_ARGS2(sx) \
193 { "h" sx, AT_DIMEN, "Size of horizontal margins" }, \
194 { "v" sx, AT_DIMEN, "Size of vertical margins" }, \
195 { "l" sx, AT_DIMEN, "Size of left margin" }, \
196 { "r" sx, AT_DIMEN, "Size of right margin" }, \
197 { "t" sx, AT_DIMEN, "Size of top margin" }, \
198 { "b" sx, AT_DIMEN, "Size of bottom margin" }
207 rgb[0] = rgb[1] = rgb[2] = 0;
212 err("Invalid color specification \"%s\": expecting 6 hex digits", s.c_str());
213 for (int i=0; i<3; i++)
216 for (int j=0; j<2; j++)
219 if (c >= '0' && c <= '9')
220 x = (x << 4) | (c - '0');
221 else if (c >= 'a' && c <= 'f')
222 x = (x << 4) | (c - 'a' + 10);
223 else if (c >= 'A' && c <= 'F')
224 x = (x << 4) | (c - 'A' + 10);
231 return pdf_coord(rgb[0]) + " " + pdf_coord(rgb[1]) + " " + pdf_coord(rgb[2]);
237 class cropmark_spec {
257 egstate = QPDFObjectHandle::newNull();
259 cropmark_spec(cmd *c, const string prefix="", const string def_type="cross") : color(c->arg(prefix + "color")->as_string("000000"))
261 string t = c->arg(prefix + "mark")->as_string(def_type);
266 else if (t == "cross")
275 err("Invalid cropmark type %s", t.c_str());
277 pen_width = c->arg(prefix + "pen")->as_double(0.2);
278 arm_length = c->arg(prefix + "len")->as_double(5*mm);
279 offset = c->arg(prefix + "offset")->as_double(0);
280 egstate = QPDFObjectHandle::newNull();
282 bool is_bg() { return (type == MARK_BG); }
283 string pdf_stream(out_context *out, BBox &box, pdf_matrix &xform);
285 string crop_cross(double x, double y, uint mask);
286 QPDFObjectHandle egstate;
289 string cropmark_spec::crop_cross(double x, double y, uint mask)
293 for (uint i=0; i<4; i++)
294 if (mask & (1U << i))
296 double x2 = x, y2 = y;
299 case 3: x2 -= arm_length; break;
300 case 2: x2 += arm_length; break;
301 case 1: y2 += arm_length; break;
302 case 0: y2 -= arm_length; break;
304 s += pdf_coord(x) + " " + pdf_coord(y) + " m " + pdf_coord(x2) + " " + pdf_coord(y2) + " l S ";
310 string cropmark_spec::pdf_stream(out_context *out, BBox &box, pdf_matrix &xform)
312 if (type == MARK_NONE)
316 s += color.to_string() + (type == MARK_BG ? " rg " : " RG ");
317 s += xform.to_string() + " cm ";
319 if (egstate.isNull())
321 auto egs = QPDFObjectHandle::newDictionary();
322 egs.replaceKey("/Type", QPDFObjectHandle::newName("/ExtGState"));
323 egs.replaceKey("/LW", QPDFObjectHandle::newReal(pen_width, 1));
324 egs.replaceKey("/LC", QPDFObjectHandle::newInteger(2));
325 egs.replaceKey("/LJ", QPDFObjectHandle::newInteger(0));
326 egstate = out->pdf->makeIndirectObject(egs);
329 string egs_res = out->new_resource("GS");
330 out->egstates.replaceKey(egs_res, egstate);
331 s += egs_res + " gs ";
333 BBox b = box.enlarged(offset);
340 s += b.to_rect() + " re S ";
343 s += crop_cross(b.x_min, b.y_min, 0b1111);
344 s += crop_cross(b.x_max, b.y_min, 0b1111);
345 s += crop_cross(b.x_max, b.y_max, 0b1111);
346 s += crop_cross(b.x_min, b.y_max, 0b1111);
349 s += crop_cross(b.x_min, b.y_min, 0b0110);
350 s += crop_cross(b.x_max, b.y_min, 0b1010);
351 s += crop_cross(b.x_max, b.y_max, 0b1001);
352 s += crop_cross(b.x_min, b.y_max, 0b0101);
355 s += crop_cross(b.x_min, b.y_min, 0b1001);
356 s += crop_cross(b.x_max, b.y_min, 0b0101);
357 s += crop_cross(b.x_max, b.y_max, 0b0110);
358 s += crop_cross(b.x_min, b.y_max, 0b1010);
361 s += b.to_rect() + " re f ";
369 #define CROPMARK_ARGS(px) \
370 { px "mark", AT_STRING, "Cropmark style: box/cross/in/out/bg" }, \
371 { px "pen", AT_DIMEN, "Cropmark pen width (default: 0.2pt)" }, \
372 { px "len", AT_DIMEN, "Cropmark arm length (default: 5mm)" }, \
373 { px "offset",AT_DIMEN, "Cropmark offset outside the box (default: 0)" }, \
374 { px "color", AT_STRING, "Cropmark color (RRGGBB, default: 000000)" }
376 // Scaling preserving aspect ratio
378 double scale_to_fit(BBox &from, BBox &to)
380 double fw = from.width(), fh = from.height();
381 double tw = to.width(), th = to.height();
382 if (is_zero(fw) || is_zero(fh) || is_zero(tw) || is_zero(th))
385 return min(tw/fw, th/fh);
390 class move_cmd : public cmd_exec_simple {
395 x = c->arg("x")->as_double(0);
396 y = c->arg("y")->as_double(0);
398 page *process_page(page *p) override
402 return new xform_page(p, "move", m);
406 static const arg_def move_args[] = {
407 { "x", AT_DIMEN | AT_MANDATORY | AT_POSITIONAL, "Move right by this distance" },
408 { "y", AT_DIMEN | AT_MANDATORY | AT_POSITIONAL, "Move up by this distance" },
414 class scale_cmd : public cmd_exec_simple {
415 double x_factor, y_factor;
419 x_factor = c->arg("x")->as_double(1);
420 y_factor = c->arg("y")->as_double(x_factor);
422 page *process_page(page *p) override
425 m.scale(x_factor, y_factor);
426 return new xform_page(p, "scale", m);
430 static const arg_def scale_args[] = {
431 { "x", AT_DOUBLE | AT_MANDATORY | AT_POSITIONAL, "Scale horizontally by this fraction" },
432 { "y", AT_DOUBLE | AT_POSITIONAL, "Scale vertically by this fraction (default: x)" },
438 class rotate_cmd : public cmd_exec_simple {
443 deg = c->arg("angle")->as_int(0) % 360;
447 err("The angle must be a multiple of 90 degrees");
449 page *process_page(page *p) override
451 return new xform_page(p, "rotate", pdf_rotation_matrix(deg, p->width, p->height));
455 static const arg_def rotate_args[] = {
456 { "angle", AT_INT | AT_MANDATORY | AT_POSITIONAL, "Rotate clockwise by this angle" },
462 class flip_cmd : public cmd_exec_simple {
468 horizontal = c->arg("h")->as_int(0);
469 vertical = c->arg("v")->as_int(0);
470 if (!horizontal && !vertical)
471 err("No direction specified");
473 page *process_page(page *p) override
479 m.shift(0, p->height);
484 m.shift(p->width, 0);
486 return new xform_page(p, "flip", m);
490 static const arg_def flip_args[] = {
491 { "h", AT_SWITCH, "Flip horizontally" },
492 { "v", AT_SWITCH, "Flip vertically" },
498 class select_cmd : public cmd_exec {
505 vector<page *> process(vector<page *> &pages) override;
508 static int validate_page_index(vector<page *> &pages, int idx)
510 if (idx >= 1 && idx <= (int) pages.size())
512 if (idx <= -1 && idx >= (int) -pages.size())
513 return idx + pages.size();
514 err("Page index %d out of range", idx);
517 vector<page *> select_cmd::process(vector<page *> &pages)
520 for (auto pb: pipe->branches)
522 vector<page *> selected;
523 for (auto ps: pb->selectors)
525 int f = validate_page_index(pages, ps.from);
526 int t = validate_page_index(pages, ps.to);
527 int step = (f <= t) ? 1 : -1;
528 for (int i=f; i != t + step; i += step)
529 selected.push_back(pages[i]);
531 auto processed = run_command_list(pb->commands, selected);
532 for (auto p: processed)
540 class apply_cmd : public cmd_exec {
547 vector<page *> process(vector<page *> &pages) override;
550 static pipeline_branch *find_branch(pipeline *pipe, vector <page *> &pages, int idx)
552 for (auto pb: pipe->branches)
553 for (auto ps: pb->selectors)
555 int f = validate_page_index(pages, ps.from);
556 int t = validate_page_index(pages, ps.to);
557 if (f <= idx && idx <= t || t <= idx && idx <= f)
563 vector<page *> apply_cmd::process(vector<page *> &pages)
570 pipeline_branch *pb = find_branch(pipe, pages, cnt);
575 auto processed = run_command_list(pb->commands, tmp);
576 for (auto q: processed)
589 class modulo_cmd : public cmd_exec {
596 n = c->arg("n")->as_int(0);
598 err("Modulo must have n > 0");
599 half = c->arg("half")->as_int(0);
602 vector<page *> process(vector<page *> &pages) override;
605 vector<page *> modulo_cmd::process(vector<page *> &pages)
608 int tuples = ((int) pages.size() + n - 1) / n;
609 int use_tuples = half ? tuples/2 : tuples;
611 for (int tuple=0; tuple < use_tuples; tuple++)
613 debug("# Tuple %d", tuple);
615 for (auto pb: pipe->branches)
618 for (auto ps: pb->selectors)
622 int step = (f <= t) ? 1 : -1;
623 for (int i=f; i<=t; i += step)
628 else if (i < 0 && i >= -n)
629 j = (tuples-1-tuple)*n + (-i) - 1;
631 err("Invalid index %d", i);
632 if (j < (int) pages.size())
633 tmp.push_back(pages[j]);
636 page *ref_page = pages[tuple*n];
637 tmp.push_back(new empty_page(ref_page->width, ref_page->height));
641 auto processed = run_command_list(pb->commands, tmp);
642 for (auto q: processed)
651 static const arg_def modulo_args[] = {
652 { "n", AT_INT | AT_MANDATORY | AT_POSITIONAL, "Number of pages in a single tuple" },
653 { "half", AT_SWITCH, "Process only the first half of n-tuples" },
659 class debug_page : public page {
661 cropmark_spec *page_cm, *image_cm;
663 debug_page(page *p, cropmark_spec *page_cms, cropmark_spec *image_cms) : page(p), orig_page(p), page_cm(page_cms), image_cm(image_cms) { }
664 void render(out_context *out, pdf_matrix xform) override
666 orig_page->render(out, xform);
667 BBox page_bbox = BBox(0, 0, width, height);
668 out->contents += page_cm->pdf_stream(out, page_bbox, xform);
669 out->contents += image_cm->pdf_stream(out, image_box, xform);
671 void debug_dump() override
673 debug("Draw debugging boxes");
674 orig_page->debug_dump();
678 class debug_cmd : public cmd_exec_simple {
679 cropmark_spec page_cmarks;
680 cropmark_spec image_cmarks;
682 debug_cmd(cmd *c UNUSED)
684 page_cmarks.type = cropmark_spec::MARK_BOX;
685 page_cmarks.color.rgb[0] = 1;
686 page_cmarks.color.rgb[1] = 0;
687 page_cmarks.color.rgb[2] = 0;
688 image_cmarks.type = cropmark_spec::MARK_BOX;
689 image_cmarks.color.rgb[0] = 0;
690 image_cmarks.color.rgb[1] = 1;
691 image_cmarks.color.rgb[2] = 0;
693 page *process_page(page *p) override
695 return new debug_page(p, &page_cmarks, &image_cmarks);
701 class merge_cmd : public cmd_exec {
703 merge_cmd(cmd *c UNUSED) { }
704 vector<page *> process(vector<page *> &pages) override;
707 class merge_page : public page {
708 vector<page *> orig_pages;
710 merge_page(vector<page *> &orig) : page(0, 0)
720 image_box = p->image_box;
725 if (!is_equal(width, p->width) || !is_equal(height, p->height))
726 err("All pages must have the same dimensions");
727 image_box.join(p->image_box);
731 void render(out_context *out, pdf_matrix xform) override
733 for (auto p: orig_pages)
734 p->render(out, xform);
736 void debug_dump() override
738 debug("Merge pages");
740 for (auto p: orig_pages)
746 vector<page *> merge_cmd::process(vector<page *> &pages)
750 out.push_back(new merge_page(pages));
756 class paper_cmd : public cmd_exec_simple {
760 paper_cmd(cmd *c) : paper(c), pos(c) { }
761 page *process_page(page *p) override
763 BBox paper_box = BBox(paper.w, paper.h);
764 pdf_matrix xf = pos.place(p->image_box, paper_box);
765 page *q = new xform_page(p, "paper", xf);
772 static const arg_def paper_args[] = {
780 class scaleto_cmd : public cmd_exec_simple {
784 scaleto_cmd(cmd *c) : paper(c), pos(c) { }
785 page *process_page(page *p) override
787 BBox orig_box = BBox(p->width, p->height);
788 BBox paper_box = BBox(paper.w, paper.h);
790 xf.scale(scale_to_fit(orig_box, paper_box));
791 orig_box.transform(xf);
792 xf.concat(pos.place(orig_box, paper_box));
793 page *q = new xform_page(p, "scaleto", xf);
800 static const arg_def scaleto_args[] = {
808 class fit_cmd : public cmd_exec_simple {
813 fit_cmd(cmd *c) : paper(c, true), pos(c), marg(c, "margin", "margin") { }
814 page *process_page(page *p) override
819 if (!is_zero(paper.w) && !is_zero(paper.h))
821 // Paper given: scale image to fit paper
822 BBox orig_box = p->image_box;
823 BBox paper_box = BBox(paper.w, paper.h);
824 marg.shrink_box(&paper_box);
825 xf.scale(scale_to_fit(orig_box, paper_box));
826 orig_box.transform(xf);
827 xf.concat(pos.place(orig_box, paper_box));
828 q = new xform_page(p, "fit", xf);
834 // No paper given: adjust paper to fit image
835 xf.shift(-p->image_box.x_min, -p->image_box.y_min);
836 xf.shift(marg.l, marg.b);
837 q = new xform_page(p, "fit", xf);
838 q->width = p->image_box.width() + marg.l + marg.r;
839 q->height = p->image_box.height() + marg.t + marg.b;
845 static const arg_def fit_args[] = {
848 MARGIN_ARGS1_NAMED("margin"),
849 MARGIN_ARGS2("margin"),
855 class expand_cmd : public cmd_exec_simple {
858 expand_cmd(cmd *c) : marg(c, "by", "") { }
859 page *process_page(page *p) override
862 xf.shift(marg.l, marg.b);
863 page *q = new xform_page(p, "expand", xf);
864 q->width = p->width + marg.l + marg.r;
865 q->height = p->height + marg.t + marg.b;
866 if (q->width < 0.001 || q->height < 0.001)
867 err("Expansion must result in positive page dimensions");
872 static const arg_def expand_args[] = {
873 MARGIN_ARGS1_POSNL("by"),
880 class margins_cmd : public cmd_exec_simple {
883 margins_cmd(cmd *c) : marg(c, "size", "") { }
884 page *process_page(page *p) override
886 page *q = new xform_page(p, "margins", pdf_matrix());
887 q->image_box = BBox(marg.l, marg.t, p->width - marg.r, p->height - marg.b);
888 if (q->image_box.width() < 0.001 || q->image_box.height() < 0.001)
889 err("Margins must result in positive image dimensions");
894 static const arg_def margins_args[] = {
895 MARGIN_ARGS1_POSNL("size"),
902 class add_blank_cmd : public cmd_exec {
906 add_blank_cmd(cmd *c) : paper(c, true)
908 n = c->arg("n")->as_int(1);
910 vector<page *> process(vector<page *> &pages) override;
913 vector<page *> add_blank_cmd::process(vector<page *> &pages)
920 for (int i=0; i<n; i++)
922 double w = paper.w, h = paper.h;
923 if (is_zero(w) || is_zero(h))
924 w = p->width, h = p->height;
925 out.push_back(new empty_page(w, h));
932 static const arg_def add_blank_args[] = {
933 { "n", AT_INT | AT_POSITIONAL, "Number of blank pages to add (default: 1)" },
940 class book_cmd : public cmd_exec {
945 n = c->arg("n")->as_int(0);
947 err("Number of pages per signature must be divisible by 4");
949 vector<page *> process(vector<page *> &pages) override;
952 vector<page *> book_cmd::process(vector<page *> &pages)
954 vector<page *> in, out;
957 while (in.size() % 4)
958 in.push_back(new empty_page(in[0]->width, in[0]->height));
961 while (i < (int) in.size())
963 int sig = in.size() - i;
966 for (int j=0; j<sig/2; j+=2)
968 out.push_back(in[i + sig-1-j]);
969 out.push_back(in[i + j]);
970 out.push_back(in[i + j+1]);
971 out.push_back(in[i + sig-2-j]);
979 static const arg_def book_args[] = {
980 { "n", AT_INT | AT_POSITIONAL, "Number of pages in a single booklet" },
988 double tile_w, tile_h;
989 double paper_w, paper_h;
994 class nup_cmd : public cmd_exec {
996 int grid_n, grid_m, num_tiles;
1010 double hspace, vspace;
1011 cropmark_spec cmarks;
1014 page *process_single(vector<page *> &in);
1015 void find_config(vector<page *> &in, BBox *page_boxes);
1016 void try_config(nup_state &st);
1018 bool found_solution;
1019 BBox common_page_box;
1022 nup_cmd(cmd *c) : paper(c), marg(c, "margin", "margin"), pos(c), tpos(c->arg("tpos")->as_string("tl")), cmarks(c, "c", "none")
1024 grid_n = c->arg("n")->as_int(0);
1025 grid_m = c->arg("m")->as_int(0);
1026 if (grid_n > 0 && grid_m > 0)
1027 num_tiles = grid_n * grid_m;
1028 else if (grid_n > 0 && !grid_m)
1031 err("Grid size must be at least 1x1");
1033 const string by = c->arg("by")->as_string("rows");
1034 if (by == "rows" || by == "row" || by == "r")
1036 else if (by == "cols" || by == "cols" || by == "c")
1038 else if (by == "tile" || by == "t")
1041 err("Argument \"by\" must be rows/cols/tile");
1043 crop = c->arg("crop")->as_int(0);
1044 mixed = c->arg("mixed")->as_int(0);
1045 rotate = c->arg("rotate")->as_int(-1);
1046 scale = c->arg("scale")->as_double(0);
1048 double space = c->arg("space")->as_double(0);
1049 hspace = c->arg("hspace")->as_double(space);
1050 vspace = c->arg("vspace")->as_double(space);
1052 if (!is_zero(scale) && (!is_zero(paper.w) || rotate >= 0))
1053 err("When used with explicit scaling, paper size nor rotation may be given");
1054 if (!is_zero(scale) && !grid_m)
1055 err("When used with explicit scaling, both grid sizes must be given");
1058 vector<page *> process(vector<page *> &pages) override;
1061 vector<page *> nup_cmd::process(vector<page *> &pages)
1065 // Unless mixed is given, find the common page size
1068 for (int i=0; i < (int) pages.size(); i++)
1071 BBox pb = crop ? p->image_box : BBox(p->width, p->height);
1073 common_page_box = pb;
1075 common_page_box.join(pb);
1077 debug("NUP: Common page box [%.3f %.3f]-[%.3f %.3f]",
1078 common_page_box.x_min, common_page_box.y_min, common_page_box.x_max, common_page_box.y_max);
1081 // Process one tile set after another
1083 while (i < (int) pages.size())
1086 if (fill_by == BY_TILE)
1088 for (int j=0; j<num_tiles; j++)
1089 in.push_back(pages[i]);
1094 for (int j=0; j<num_tiles; j++)
1096 if (i < (int) pages.size())
1097 in.push_back(pages[i]);
1099 in.push_back(new empty_page(in[0]->width, in[0]->height));
1103 out.push_back(process_single(in));
1109 void nup_cmd::try_config(nup_state &st)
1111 BBox window(st.paper_w, st.paper_h);
1112 if (!marg.may_shrink(&window))
1114 marg.shrink_box(&window);
1115 window.x_max -= (st.cols - 1) * hspace;
1116 window.y_max -= (st.rows - 1) * vspace;
1117 if (window.width() < 0 || window.height() < 0)
1120 BBox image(st.cols * st.tile_w, st.rows * st.tile_h);
1121 st.scale = scale_to_fit(image, window);
1122 st.fill_factor = (st.scale*image.width() * st.scale*image.height()) / (st.paper_w * st.paper_h);
1124 if (debug_level > 1)
1125 debug("Try: %dx%d on %.3f x %.3f => scale %.3f, fill %.6f",
1127 st.paper_w, st.paper_h,
1128 st.scale, st.fill_factor);
1130 if (!found_solution || best.fill_factor < st.fill_factor)
1132 found_solution = true;
1137 void nup_cmd::find_config(vector<page *> &in, BBox *page_boxes)
1141 // Determine tile size
1142 st.tile_w = st.tile_h = 0;
1143 for (int i=0; i<num_tiles; i++)
1146 page_boxes[i] = common_page_box;
1148 page_boxes[i] = in[i]->image_box;
1150 page_boxes[i] = BBox(in[i]->width, in[i]->height);
1151 st.tile_w = max(st.tile_w, page_boxes[i].width());
1152 st.tile_h = max(st.tile_h, page_boxes[i].height());
1154 debug("NUP: %d tiles of size [%.3f,%.3f]", num_tiles, st.tile_w, st.tile_h);
1157 // Try all possible configurations of tiles
1158 found_solution = false;
1159 if (!is_zero(scale))
1161 // If explicit scaling is requested, we choose page size ourselves,
1162 // so there is just one configuration.
1165 st.paper_w = marg.l + st.cols*st.tile_w + (st.cols-1)*hspace + marg.r;
1166 st.paper_h = marg.t + st.rows*st.tile_h + (st.rows-1)*vspace + marg.b;
1171 // Page size is fixed (either given or copied from the source pages),
1172 // but we can have freedom to rotate and/or to choose grid size.
1173 for (int rot=0; rot<=1; rot++)
1175 if (rotate >= 0 && rot != rotate)
1178 // Establish paper size
1179 if (!is_zero(paper.w))
1181 st.paper_w = paper.w;
1182 st.paper_h = paper.h;
1186 st.paper_w = in[0]->width;
1187 st.paper_h = in[0]->height;
1190 swap(st.paper_w, st.paper_h);
1201 for (int r=1; r<=grid_n; r++)
1205 st.cols = grid_n / r;
1212 if (!found_solution)
1213 err("No feasible solution found");
1214 debug("Best: %dx%d on %.3f x %.3f => scale %.3f, fill %.6f",
1215 best.cols, best.rows,
1216 best.paper_w, best.paper_h,
1217 best.scale, best.fill_factor);
1221 class nup_page : public page {
1223 vector<page *> orig_pages;
1224 vector<pdf_matrix> xforms;
1225 vector<BBox> tile_boxes;
1226 cropmark_spec *cmarks;
1227 void render(out_context *out, pdf_matrix xform) override;
1228 nup_page(nup_state &st) : page(st.paper_w, st.paper_h) { }
1229 void debug_dump() override
1231 debug("N-up printing");
1233 for (auto p: orig_pages)
1239 void nup_page::render(out_context *out, pdf_matrix parent_xform)
1241 for (int i=0; i < (int) orig_pages.size(); i++)
1243 if (cmarks->is_bg())
1244 out->contents += cmarks->pdf_stream(out, tile_boxes[i], parent_xform);
1245 orig_pages[i]->render(out, xforms[i] * parent_xform);
1246 if (!cmarks->is_bg())
1247 out->contents += cmarks->pdf_stream(out, tile_boxes[i], parent_xform);
1251 page *nup_cmd::process_single(vector<page *> &in)
1253 BBox page_boxes[num_tiles];
1254 find_config(in, page_boxes);
1255 double tw = best.scale * best.tile_w;
1256 double th = best.scale * best.tile_h;
1258 // Construct transform from paper to grid of tiles
1259 BBox paper_box(best.paper_w, best.paper_h);
1260 marg.shrink_box(&paper_box);
1261 BBox grid_box(best.cols * tw + (best.cols-1) * hspace,
1262 best.rows * th + (best.rows-1) * vspace);
1263 pdf_matrix place_xform = pos.place(grid_box, paper_box);
1265 nup_page *p = new nup_page(best);
1266 p->image_box = grid_box;
1267 p->image_box.transform(place_xform);
1269 for (int i=0; i<num_tiles; i++)
1272 if (fill_by == BY_ROWS || fill_by == BY_TILE)
1284 BBox &page_box = page_boxes[i];
1285 m.shift(-page_box.x_min, -page_box.y_min);
1286 m.scale(best.scale);
1287 page_box.transform(m);
1289 double x = c * (tw + hspace);
1290 double y = (best.rows-1-r) * (th + vspace);
1291 BBox tile_box = BBox(x, y, x+tw, y+th);
1292 m.concat(tpos.place(page_box, tile_box));
1294 p->orig_pages.push_back(in[i]);
1295 p->xforms.push_back(m * place_xform);
1296 p->tile_boxes.push_back(tile_box.transformed(place_xform));
1297 p->cmarks = &cmarks;
1303 static const arg_def nup_args[] = {
1304 { "n", AT_INT | AT_POSITIONAL | AT_MANDATORY, "Number of tiles on a page" },
1305 { "m", AT_INT | AT_POSITIONAL, "If both n and m are given, produce n x m tiles on a page" },
1306 { "by", AT_STRING, "Tile filling order: rows/cols/tile (default: rows)" },
1307 { "crop", AT_SWITCH, "Crop input pages to their image box" },
1308 { "mixed", AT_SWITCH, "Allow input pages of mixed sizes" },
1309 { "rotate", AT_SWITCH, "Force (non-)rotation" },
1310 { "scale", AT_DOUBLE, "Force specific scaling factor" },
1312 MARGIN_ARGS1_NAMED("margin"),
1313 MARGIN_ARGS2("margin"),
1316 { "tpos", AT_STRING, "Position of images inside tiles (default: tl)" },
1317 { "space", AT_DIMEN, "Space between tiles (default: 0)" },
1318 { "hspace", AT_DIMEN, "Horizontal space between tiles (default: space)" },
1319 { "vspace", AT_DIMEN, "Vertical space between tiles (default: space)" },
1325 class cropmarks_page : public page {
1329 void render(out_context *out, pdf_matrix xform) override
1331 orig_page->render(out, xform);
1332 out->contents += cm->pdf_stream(out, image_box, xform);
1334 void debug_dump() override
1336 debug("Add cropmarks");
1337 orig_page->debug_dump();
1339 cropmarks_page(page *p, cropmark_spec *cms) : page(p), orig_page(p), cm(cms) { }
1342 class cropmarks_cmd : public cmd_exec_simple {
1344 page *process_page(page *p) override
1346 return new cropmarks_page(p, &cm);
1349 cropmarks_cmd(cmd *c) : cm(c) { }
1352 static const arg_def cropmarks_args[] = {
1359 class clip_page : public page {
1363 void render(out_context *out, pdf_matrix xform) override
1365 out->contents += "q " + clip_to.transformed(xform).to_rect() + " re W n ";
1366 orig_page->render(out, xform);
1367 out->contents += "Q ";
1369 void debug_dump() override
1371 debug("Clip [%.3f %.3f %.3f %.3f]", clip_to.x_min, clip_to.y_min, clip_to.x_max, clip_to.y_max);
1372 orig_page->debug_dump();
1374 clip_page(page *p, BBox &to) : page(p), orig_page(p), clip_to(to) { }
1377 class clip_cmd : public cmd_exec_simple {
1379 page *process_page(page *p) override
1381 BBox to = p->image_box.enlarged(bleed);
1382 return new clip_page(p, to);
1387 bleed = c->arg("bleed")->as_double(0);
1391 static const arg_def clip_args[] = {
1392 { "bleed", AT_DIMEN, "Allow bleeding of image outside its box" },
1398 class common_cmd : public cmd_exec {
1399 vector<page *> process(vector<page *> &pages) override
1404 const page *first = pages[0];
1405 BBox pbox(first->width, first->height);
1406 BBox ibox = first->image_box;
1409 BBox pg(p->width, p->height);
1411 ibox.join(p->image_box);
1417 page *q = new xform_page(p, "common", pdf_matrix());
1418 q->width = pbox.width();
1419 q->height = pbox.height();
1420 q->image_box = ibox;
1427 common_cmd(cmd *c UNUSED) { }
1432 class slice_cmd : public cmd_exec {
1438 slice_cmd(cmd *c) : paper(c), pos(c), margin(c, "margin", "margin")
1440 if (is_zero(paper.w) || is_zero(paper.h))
1441 err("Paper format must be given");
1442 bleed = c->arg("bleed")->as_double(0);
1444 vector<page *> process(vector<page *> &pages) override;
1447 vector<page *> slice_cmd::process(vector<page *> &pages)
1453 double pw = paper.w - margin.l - margin.r;
1454 double ph = paper.h - margin.t - margin.b;
1455 if (pw < 0 || ph < 0)
1456 err("Margins larger than paper");
1458 int cols = (int) ceil((p->image_box.width() - 2*mm) / pw);
1459 int rows = (int) ceil((p->image_box.height() - 2*mm) / ph);
1460 BBox big_box(cols*pw, rows*ph);
1461 pdf_matrix placement = pos.place(p->image_box, big_box);
1463 debug("Slicing [%.3f,%.3f] to %dx%d [%.3f,%.3f]", p->image_box.width(), p->image_box.height(), rows, cols, pw, ph);
1464 for (int r=0; r<rows; r++)
1465 for (int c=0; c<cols; c++)
1467 pdf_matrix xf = placement;
1468 xf.shift(-c*pw, -(rows-1-r)*ph);
1469 xf.shift(margin.l, margin.t);
1470 page *q = new xform_page(p, "slice", xf);
1472 q->height = paper.h;
1473 BBox slice_box = BBox(margin.l, margin.t, paper.w - margin.r, paper.h - margin.b);
1474 q->image_box = p->image_box.transformed(xf);
1475 q->image_box.intersect(slice_box);
1476 BBox bleeding_slice = slice_box.enlarged(bleed);
1477 out.push_back(new clip_page(q, bleeding_slice));
1484 static const arg_def slice_args[] = {
1487 MARGIN_ARGS1_NAMED("margin"),
1488 MARGIN_ARGS2("margin"),
1489 { "bleed", AT_DIMEN, "Allow bleeding of image outside its box" },
1493 /*** Command table ***/
1495 template<typename T> cmd_exec *ctor(cmd *c) { return new T(c); }
1497 const cmd_def cmd_table[] = {
1498 { "add-blank",add_blank_args, 0, &ctor<add_blank_cmd>,
1499 "Add blank page(s) after each page" },
1500 { "apply", no_args, 1, &ctor<apply_cmd>,
1501 "Apply commands to selected pages" },
1502 { "book", book_args, 0, &ctor<book_cmd>,
1503 "Prepare booklets for book binding" },
1504 { "clip", clip_args, 0, &ctor<clip_cmd>,
1505 "Suppress page contents drawn outside the image box" },
1506 { "common", no_args, 0, &ctor<common_cmd>,
1507 "Use a common page size and image box for all pages" },
1508 { "cropmarks",cropmarks_args, 0, &ctor<cropmarks_cmd>,
1509 "Draw cropping marks around the image box" },
1510 { "debug", no_args, 0, &ctor<debug_cmd>,
1511 "Draw debugging information on the page)" },
1512 { "expand", expand_args, 0, &ctor<expand_cmd>,
1513 "Expand paper around the image" },
1514 { "fit", fit_args, 0, &ctor<fit_cmd>,
1515 "Fit image to a given paper" },
1516 { "flip", flip_args, 0, &ctor<flip_cmd>,
1517 "Flip page horizontally and/or vertically" },
1518 { "margins", margins_args, 0, &ctor<margins_cmd>,
1519 "Define image box by dimensions of margins around it" },
1520 { "merge", no_args, 0, &ctor<merge_cmd>,
1521 "Merge all pages to one by placing them one over another" },
1522 { "modulo", modulo_args, 1, &ctor<modulo_cmd>,
1523 "Act on n-tuples of pages" },
1524 { "move", move_args, 0, &ctor<move_cmd>,
1525 "Shift contents on the page" },
1526 { "null", no_args, 0, &ctor<null_cmd>,
1528 { "nup", nup_args, 0, &ctor<nup_cmd>,
1529 "Combine multiple pages to one (n-up printing)" },
1530 { "paper", paper_args, 0, &ctor<paper_cmd>,
1531 "Place image on a given paper" },
1532 { "rotate", rotate_args, 0, &ctor<rotate_cmd>,
1533 "Rotate the page by multiples of 90 degrees" },
1534 { "scale", scale_args, 0, &ctor<scale_cmd>,
1535 "Scale the page by a given factor" },
1536 { "scaleto", scaleto_args, 0, &ctor<scaleto_cmd>,
1537 "Scale the page to a given size" },
1538 { "select", no_args, 1, &ctor<select_cmd>,
1539 "Select a subset of pages" },
1540 { "slice", slice_args, 0, &ctor<slice_cmd>,
1541 "Slice to smaller pages" },
1542 { NULL, NULL, 0, NULL,