Qt
Internal/Contributor docs for the Qt SDK. Note: These are NOT official API docs; those are found at https://doc.qt.io/
Loading...
Searching...
No Matches
qpdf.cpp
Go to the documentation of this file.
1// Copyright (C) 2016 The Qt Company Ltd.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
3// Qt-Security score:significant reason:default
4
5#include "qpdf_p.h"
6
7#ifndef QT_NO_PDF
8
9#include "qplatformdefs.h"
10
11#include <private/qcmyk_p.h>
12#include <private/qfont_p.h>
13#include <private/qmath_p.h>
14#include <private/qpainter_p.h>
15#include <private/qstringiterator_p.h>
16
17#include <qbuffer.h>
18#include <qcryptographichash.h>
19#include <qdatetime.h>
20#include <qdebug.h>
21#include <qfile.h>
22#include <qimagewriter.h>
23#include <qnumeric.h>
24#include <qtemporaryfile.h>
25#include <qtimezone.h>
26#include <quuid.h>
27#include <qxmlstream.h>
28#include <QtCore/private/qenumindexedarray_p.h>
29
30#include <cstdio>
31#include <map>
32
33#ifndef QT_NO_COMPRESS
34#include <zlib.h>
35#endif
36
37#ifdef QT_NO_COMPRESS
38static const bool do_compress = false;
39#else
40static const bool do_compress = true;
41#endif
42
43// might be helpful for smooth transforms of images
44// Can't use it though, as gs generates completely wrong images if this is true.
45static const bool interpolateImages = false;
46
47static void initResources()
48{
49 Q_INIT_RESOURCE(qpdf);
50}
51
52QT_BEGIN_NAMESPACE
53
54using namespace Qt::StringLiterals;
55
57{
58 QPaintEngine::PaintEngineFeatures f = QPaintEngine::AllFeatures;
59 f &= ~(QPaintEngine::PorterDuff
60 | QPaintEngine::PerspectiveTransform
61 | QPaintEngine::ObjectBoundingModeGradients
62 | QPaintEngine::ConicalGradientFill);
63 return f;
64}
65
66extern bool qt_isExtendedRadialGradient(const QBrush &brush);
67
68// helper function to remove transparency from brush in PDF/A-1b mode
69static void removeTransparencyFromBrush(QBrush &brush)
70{
71 if (brush.style() == Qt::SolidPattern) {
72 QColor color = brush.color();
73 if (color.alpha() != 255) {
74 color.setAlpha(255);
75 brush.setColor(color);
76 }
77
78 return;
79 }
80
81 if (qt_isExtendedRadialGradient(brush)) {
82 brush = QBrush(Qt::black); // the safest we can do so far...
83 return;
84 }
85
86 if (brush.style() == Qt::LinearGradientPattern
87 || brush.style() == Qt::RadialGradientPattern
88 || brush.style() == Qt::ConicalGradientPattern) {
89
90 QGradientStops stops = brush.gradient()->stops();
91 for (int i = 0; i < stops.size(); ++i) {
92 if (stops[i].second.alpha() != 255)
93 stops[i].second.setAlpha(255);
94 }
95
96 const_cast<QGradient*>(brush.gradient())->setStops(stops);
97 return;
98 }
99
100 if (brush.style() == Qt::TexturePattern) {
101 // handled inside QPdfEnginePrivate::addImage() already
102 return;
103 }
104}
105
106
107/* also adds a space at the end of the number */
108const char *qt_real_to_string(qreal val, char *buf) {
109 const char *ret = buf;
110
111 if (!qIsFinite(val) || std::abs(val) > std::numeric_limits<quint32>::max()) {
112 *(buf++) = '0';
113 *(buf++) = ' ';
114 *buf = 0;
115 return ret;
116 }
117
118 if (val < 0) {
119 *(buf++) = '-';
120 val = -val;
121 }
122 qreal frac = std::modf(val, &val);
123 quint32 ival(val);
124
125 int ifrac = (int)(frac * 1000000000);
126 if (ifrac == 1000000000) {
127 ++ival;
128 ifrac = 0;
129 }
130 char output[256];
131 int i = 0;
132 while (ival) {
133 output[i] = '0' + (ival % 10);
134 ++i;
135 ival /= 10;
136 }
137 int fact = 100000000;
138 if (i == 0) {
139 *(buf++) = '0';
140 } else {
141 while (i) {
142 *(buf++) = output[--i];
143 fact /= 10;
144 ifrac /= 10;
145 }
146 }
147
148 if (ifrac) {
149 *(buf++) = '.';
150 while (fact) {
151 *(buf++) = '0' + ((ifrac/fact) % 10);
152 fact /= 10;
153 }
154 }
155 *(buf++) = ' ';
156 *buf = 0;
157 return ret;
158}
159
160const char *qt_int_to_string(int val, char *buf) {
161 const char *ret = buf;
162 if (val < 0) {
163 *(buf++) = '-';
164 val = -val;
165 }
166 char output[256];
167 int i = 0;
168 while (val) {
169 output[i] = '0' + (val % 10);
170 ++i;
171 val /= 10;
172 }
173 if (i == 0) {
174 *(buf++) = '0';
175 } else {
176 while (i)
177 *(buf++) = output[--i];
178 }
179 *(buf++) = ' ';
180 *buf = 0;
181 return ret;
182}
183
184
185namespace QPdf {
186 ByteStream::ByteStream(QByteArray *byteArray, bool fileBacking)
187 : dev(new QBuffer(byteArray)),
188 fileBackingEnabled(fileBacking),
189 fileBackingActive(false),
190 handleDirty(false)
191 {
192 dev->open(QIODevice::ReadWrite | QIODevice::Append);
193 }
194
195 ByteStream::ByteStream(bool fileBacking)
196 : dev(new QBuffer(&ba)),
197 fileBackingEnabled(fileBacking),
198 fileBackingActive(false),
199 handleDirty(false)
200 {
201 dev->open(QIODevice::ReadWrite);
202 }
203
205 {
206 delete dev;
207 }
208
209 ByteStream &ByteStream::operator <<(char chr)
210 {
211 if (handleDirty) prepareBuffer();
212 dev->write(&chr, 1);
213 return *this;
214 }
215
216 ByteStream &ByteStream::operator <<(const char *str)
217 {
218 if (handleDirty) prepareBuffer();
219 dev->write(str, strlen(str));
220 return *this;
221 }
222
223 ByteStream &ByteStream::operator <<(const QByteArray &str)
224 {
225 if (handleDirty) prepareBuffer();
226 dev->write(str);
227 return *this;
228 }
229
230 ByteStream &ByteStream::operator <<(const ByteStream &src)
231 {
232 Q_ASSERT(!src.dev->isSequential());
233 if (handleDirty) prepareBuffer();
234 // We do play nice here, even though it looks ugly.
235 // We save the position and restore it afterwards.
236 ByteStream &s = const_cast<ByteStream&>(src);
237 qint64 pos = s.dev->pos();
238 s.dev->reset();
239 while (!s.dev->atEnd()) {
240 QByteArray buf = s.dev->read(chunkSize());
241 dev->write(buf);
242 }
243 s.dev->seek(pos);
244 return *this;
245 }
246
247 ByteStream &ByteStream::operator <<(qreal val) {
248 char buf[256];
249 qt_real_to_string(val, buf);
250 *this << buf;
251 return *this;
252 }
253
254 ByteStream &ByteStream::operator <<(int val) {
255 char buf[256];
256 qt_int_to_string(val, buf);
257 *this << buf;
258 return *this;
259 }
260
261 ByteStream &ByteStream::operator <<(const QPointF &p) {
262 char buf[256];
263 qt_real_to_string(p.x(), buf);
264 *this << buf;
265 qt_real_to_string(p.y(), buf);
266 *this << buf;
267 return *this;
268 }
269
270 QIODevice *ByteStream::stream()
271 {
272 dev->reset();
273 handleDirty = true;
274 return dev;
275 }
276
278 {
279 dev->open(QIODevice::ReadWrite | QIODevice::Truncate);
280 }
281
282 void ByteStream::prepareBuffer()
283 {
284 Q_ASSERT(!dev->isSequential());
285 qint64 size = dev->size();
286 if (fileBackingEnabled && !fileBackingActive
287 && size > maxMemorySize()) {
288 // Switch to file backing.
289 QTemporaryFile *newFile = new QTemporaryFile;
290 if (newFile->open()) {
291 dev->reset();
292 while (!dev->atEnd()) {
293 QByteArray buf = dev->read(chunkSize());
294 newFile->write(buf);
295 }
296 delete dev;
297 dev = newFile;
298 ba.clear();
299 fileBackingActive = true;
300 }
301 }
302 if (dev->pos() != size) {
303 dev->seek(size);
304 handleDirty = false;
305 }
306 }
307}
308
309#define QT_PATH_ELEMENT(elm)
310
311QByteArray QPdf::generatePath(const QPainterPath &path, const QTransform &matrix, PathFlags flags)
312{
313 QByteArray result;
314 if (!path.elementCount())
315 return result;
316
317 ByteStream s(&result);
318
319 int start = -1;
320 for (int i = 0; i < path.elementCount(); ++i) {
321 const QPainterPath::Element &elm = path.elementAt(i);
322 switch (elm.type) {
323 case QPainterPath::MoveToElement:
324 if (start >= 0
325 && path.elementAt(start).x == path.elementAt(i-1).x
326 && path.elementAt(start).y == path.elementAt(i-1).y)
327 s << "h\n";
328 s << matrix.map(QPointF(elm.x, elm.y)) << "m\n";
329 start = i;
330 break;
331 case QPainterPath::LineToElement:
332 s << matrix.map(QPointF(elm.x, elm.y)) << "l\n";
333 break;
334 case QPainterPath::CurveToElement:
335 Q_ASSERT(path.elementAt(i+1).type == QPainterPath::CurveToDataElement);
336 Q_ASSERT(path.elementAt(i+2).type == QPainterPath::CurveToDataElement);
337 s << matrix.map(QPointF(elm.x, elm.y))
338 << matrix.map(QPointF(path.elementAt(i+1).x, path.elementAt(i+1).y))
339 << matrix.map(QPointF(path.elementAt(i+2).x, path.elementAt(i+2).y))
340 << "c\n";
341 i += 2;
342 break;
343 default:
344 qFatal("QPdf::generatePath(), unhandled type: %d", elm.type);
345 }
346 }
347 if (start >= 0
348 && path.elementAt(start).x == path.elementAt(path.elementCount()-1).x
349 && path.elementAt(start).y == path.elementAt(path.elementCount()-1).y)
350 s << "h\n";
351
352 Qt::FillRule fillRule = path.fillRule();
353
354 const char *op = "";
355 switch (flags) {
356 case ClipPath:
357 op = (fillRule == Qt::WindingFill) ? "W n\n" : "W* n\n";
358 break;
359 case FillPath:
360 op = (fillRule == Qt::WindingFill) ? "f\n" : "f*\n";
361 break;
362 case StrokePath:
363 op = "S\n";
364 break;
366 op = (fillRule == Qt::WindingFill) ? "B\n" : "B*\n";
367 break;
368 }
369 s << op;
370 return result;
371}
372
373QByteArray QPdf::generateMatrix(const QTransform &matrix)
374{
375 QByteArray result;
376 ByteStream s(&result);
377 s << matrix.m11()
378 << matrix.m12()
379 << matrix.m21()
380 << matrix.m22()
381 << matrix.dx()
382 << matrix.dy()
383 << "cm\n";
384 return result;
385}
386
388{
389 QByteArray result;
390 ByteStream s(&result);
391 s << '[';
392
393 QList<qreal> dasharray = pen.dashPattern();
394 qreal w = pen.widthF();
395 if (w < 0.001)
396 w = 1;
397 for (int i = 0; i < dasharray.size(); ++i) {
398 qreal dw = dasharray.at(i)*w;
399 if (dw < 0.0001) dw = 0.0001;
400 s << dw;
401 }
402 s << ']';
403 s << pen.dashOffset() * w;
404 s << " d\n";
405 return result;
406}
407
408
409
410static const char* const pattern_for_brush[] = {
411 nullptr, // NoBrush
412 nullptr, // SolidPattern
413 "0 J\n"
414 "6 w\n"
415 "[] 0 d\n"
416 "4 0 m\n"
417 "4 8 l\n"
418 "0 4 m\n"
419 "8 4 l\n"
420 "S\n", // Dense1Pattern
421
422 "0 J\n"
423 "2 w\n"
424 "[6 2] 1 d\n"
425 "0 0 m\n"
426 "0 8 l\n"
427 "8 0 m\n"
428 "8 8 l\n"
429 "S\n"
430 "[] 0 d\n"
431 "2 0 m\n"
432 "2 8 l\n"
433 "6 0 m\n"
434 "6 8 l\n"
435 "S\n"
436 "[6 2] -3 d\n"
437 "4 0 m\n"
438 "4 8 l\n"
439 "S\n", // Dense2Pattern
440
441 "0 J\n"
442 "2 w\n"
443 "[6 2] 1 d\n"
444 "0 0 m\n"
445 "0 8 l\n"
446 "8 0 m\n"
447 "8 8 l\n"
448 "S\n"
449 "[2 2] -1 d\n"
450 "2 0 m\n"
451 "2 8 l\n"
452 "6 0 m\n"
453 "6 8 l\n"
454 "S\n"
455 "[6 2] -3 d\n"
456 "4 0 m\n"
457 "4 8 l\n"
458 "S\n", // Dense3Pattern
459
460 "0 J\n"
461 "2 w\n"
462 "[2 2] 1 d\n"
463 "0 0 m\n"
464 "0 8 l\n"
465 "8 0 m\n"
466 "8 8 l\n"
467 "S\n"
468 "[2 2] -1 d\n"
469 "2 0 m\n"
470 "2 8 l\n"
471 "6 0 m\n"
472 "6 8 l\n"
473 "S\n"
474 "[2 2] 1 d\n"
475 "4 0 m\n"
476 "4 8 l\n"
477 "S\n", // Dense4Pattern
478
479 "0 J\n"
480 "2 w\n"
481 "[2 6] -1 d\n"
482 "0 0 m\n"
483 "0 8 l\n"
484 "8 0 m\n"
485 "8 8 l\n"
486 "S\n"
487 "[2 2] 1 d\n"
488 "2 0 m\n"
489 "2 8 l\n"
490 "6 0 m\n"
491 "6 8 l\n"
492 "S\n"
493 "[2 6] 3 d\n"
494 "4 0 m\n"
495 "4 8 l\n"
496 "S\n", // Dense5Pattern
497
498 "0 J\n"
499 "2 w\n"
500 "[2 6] -1 d\n"
501 "0 0 m\n"
502 "0 8 l\n"
503 "8 0 m\n"
504 "8 8 l\n"
505 "S\n"
506 "[2 6] 3 d\n"
507 "4 0 m\n"
508 "4 8 l\n"
509 "S\n", // Dense6Pattern
510
511 "0 J\n"
512 "2 w\n"
513 "[2 6] -1 d\n"
514 "0 0 m\n"
515 "0 8 l\n"
516 "8 0 m\n"
517 "8 8 l\n"
518 "S\n", // Dense7Pattern
519
520 "1 w\n"
521 "0 4 m\n"
522 "8 4 l\n"
523 "S\n", // HorPattern
524
525 "1 w\n"
526 "4 0 m\n"
527 "4 8 l\n"
528 "S\n", // VerPattern
529
530 "1 w\n"
531 "4 0 m\n"
532 "4 8 l\n"
533 "0 4 m\n"
534 "8 4 l\n"
535 "S\n", // CrossPattern
536
537 "1 w\n"
538 "-1 5 m\n"
539 "5 -1 l\n"
540 "3 9 m\n"
541 "9 3 l\n"
542 "S\n", // BDiagPattern
543
544 "1 w\n"
545 "-1 3 m\n"
546 "5 9 l\n"
547 "3 -1 m\n"
548 "9 5 l\n"
549 "S\n", // FDiagPattern
550
551 "1 w\n"
552 "-1 3 m\n"
553 "5 9 l\n"
554 "3 -1 m\n"
555 "9 5 l\n"
556 "-1 5 m\n"
557 "5 -1 l\n"
558 "3 9 m\n"
559 "9 3 l\n"
560 "S\n", // DiagCrossPattern
561};
562
564{
565 int style = b.style();
566 if (style > Qt::DiagCrossPattern)
567 return QByteArray();
568 return pattern_for_brush[style];
569}
570
571
572static void moveToHook(qfixed x, qfixed y, void *data)
573{
574 QPdf::Stroker *t = (QPdf::Stroker *)data;
575 if (!t->first)
576 *t->stream << "h\n";
577 if (!t->cosmeticPen)
578 t->matrix.map(x, y, &x, &y);
579 *t->stream << x << y << "m\n";
580 t->first = false;
581}
582
583static void lineToHook(qfixed x, qfixed y, void *data)
584{
585 QPdf::Stroker *t = (QPdf::Stroker *)data;
586 if (!t->cosmeticPen)
587 t->matrix.map(x, y, &x, &y);
588 *t->stream << x << y << "l\n";
589}
590
591static void cubicToHook(qfixed c1x, qfixed c1y,
592 qfixed c2x, qfixed c2y,
593 qfixed ex, qfixed ey,
594 void *data)
595{
596 QPdf::Stroker *t = (QPdf::Stroker *)data;
597 if (!t->cosmeticPen) {
598 t->matrix.map(c1x, c1y, &c1x, &c1y);
599 t->matrix.map(c2x, c2y, &c2x, &c2y);
600 t->matrix.map(ex, ey, &ex, &ey);
601 }
602 *t->stream << c1x << c1y
603 << c2x << c2y
604 << ex << ey
605 << "c\n";
606}
607
609 : stream(nullptr),
610 first(true),
612{
613 stroker = &basicStroker;
614 basicStroker.setMoveToHook(moveToHook);
615 basicStroker.setLineToHook(lineToHook);
616 basicStroker.setCubicToHook(cubicToHook);
617 cosmeticPen = true;
618 basicStroker.setStrokeWidth(.1);
619}
620
621void QPdf::Stroker::setPen(const QPen &pen, QPainter::RenderHints)
622{
623 if (pen.style() == Qt::NoPen) {
624 stroker = nullptr;
625 return;
626 }
627 qreal w = pen.widthF();
628 bool zeroWidth = w < 0.0001;
629 cosmeticPen = pen.isCosmetic();
630 if (zeroWidth)
631 w = .1;
632
633 basicStroker.setStrokeWidth(w);
634 basicStroker.setCapStyle(pen.capStyle());
635 basicStroker.setJoinStyle(pen.joinStyle());
636 basicStroker.setMiterLimit(pen.miterLimit());
637
638 QList<qreal> dashpattern = pen.dashPattern();
639 if (zeroWidth) {
640 for (int i = 0; i < dashpattern.size(); ++i)
641 dashpattern[i] *= 10.;
642 }
643 if (!dashpattern.isEmpty()) {
644 dashStroker.setDashPattern(dashpattern);
645 dashStroker.setDashOffset(pen.dashOffset());
646 stroker = &dashStroker;
647 } else {
648 stroker = &basicStroker;
649 }
650}
651
652void QPdf::Stroker::strokePath(const QPainterPath &path)
653{
654 if (!stroker)
655 return;
656 first = true;
657
658 stroker->strokePath(path, this, cosmeticPen ? matrix : QTransform());
659 *stream << "h f\n";
660}
661
662QByteArray QPdf::ascii85Encode(const QByteArray &input)
663{
664 int isize = input.size()/4*4;
665 QByteArray output;
666 output.resize(input.size()*5/4+7);
667 char *out = output.data();
668 const uchar *in = (const uchar *)input.constData();
669 for (int i = 0; i < isize; i += 4) {
670 uint val = (((uint)in[i])<<24) + (((uint)in[i+1])<<16) + (((uint)in[i+2])<<8) + (uint)in[i+3];
671 if (val == 0) {
672 *out = 'z';
673 ++out;
674 } else {
675 char base[5];
676 base[4] = val % 85;
677 val /= 85;
678 base[3] = val % 85;
679 val /= 85;
680 base[2] = val % 85;
681 val /= 85;
682 base[1] = val % 85;
683 val /= 85;
684 base[0] = val % 85;
685 *(out++) = base[0] + '!';
686 *(out++) = base[1] + '!';
687 *(out++) = base[2] + '!';
688 *(out++) = base[3] + '!';
689 *(out++) = base[4] + '!';
690 }
691 }
692 //write the last few bytes
693 int remaining = input.size() - isize;
694 if (remaining) {
695 uint val = 0;
696 for (int i = isize; i < input.size(); ++i)
697 val = (val << 8) + in[i];
698 val <<= 8*(4-remaining);
699 char base[5];
700 base[4] = val % 85;
701 val /= 85;
702 base[3] = val % 85;
703 val /= 85;
704 base[2] = val % 85;
705 val /= 85;
706 base[1] = val % 85;
707 val /= 85;
708 base[0] = val % 85;
709 for (int i = 0; i < remaining+1; ++i)
710 *(out++) = base[i] + '!';
711 }
712 *(out++) = '~';
713 *(out++) = '>';
714 output.resize(out-output.data());
715 return output;
716}
717
718const char *QPdf::toHex(ushort u, char *buffer)
719{
720 int i = 3;
721 while (i >= 0) {
722 ushort hex = (u & 0x000f);
723 if (hex < 0x0a)
724 buffer[i] = '0'+hex;
725 else
726 buffer[i] = 'A'+(hex-0x0a);
727 u = u >> 4;
728 i--;
729 }
730 buffer[4] = '\0';
731 return buffer;
732}
733
734const char *QPdf::toHex(uchar u, char *buffer)
735{
736 int i = 1;
737 while (i >= 0) {
738 ushort hex = (u & 0x000f);
739 if (hex < 0x0a)
740 buffer[i] = '0'+hex;
741 else
742 buffer[i] = 'A'+(hex-0x0a);
743 u = u >> 4;
744 i--;
745 }
746 buffer[2] = '\0';
747 return buffer;
748}
749
750
752 : QPdf::ByteStream(true) // Enable file backing
753{
754}
755
756void QPdfPage::streamImage(int w, int h, uint object)
757{
758 *this << w << "0 0 " << -h << "0 " << h << "cm /Im" << object << " Do\n";
759 if (!images.contains(object))
760 images.append(object);
761}
762
763
764QPdfEngine::QPdfEngine(QPdfEnginePrivate &dd)
765 : QPaintEngine(dd, qt_pdf_decide_features())
766{
767}
768
769QPdfEngine::QPdfEngine()
770 : QPaintEngine(*new QPdfEnginePrivate(), qt_pdf_decide_features())
771{
772}
773
774void QPdfEngine::setOutputFilename(const QString &filename)
775{
776 Q_D(QPdfEngine);
777 d->outputFileName = filename;
778}
779
780
781void QPdfEngine::drawPoints (const QPointF *points, int pointCount)
782{
783 if (!points)
784 return;
785
786 Q_D(QPdfEngine);
787 QPainterPath p;
788 for (int i=0; i!=pointCount;++i) {
789 p.moveTo(points[i]);
790 p.lineTo(points[i] + QPointF(0, 0.001));
791 }
792
793 bool hadBrush = d->hasBrush;
794 d->hasBrush = false;
795 drawPath(p);
796 d->hasBrush = hadBrush;
797}
798
799void QPdfEngine::drawLines (const QLineF *lines, int lineCount)
800{
801 if (!lines)
802 return;
803
804 Q_D(QPdfEngine);
805 QPainterPath p;
806 for (int i=0; i!=lineCount;++i) {
807 p.moveTo(lines[i].p1());
808 p.lineTo(lines[i].p2());
809 }
810 bool hadBrush = d->hasBrush;
811 d->hasBrush = false;
812 drawPath(p);
813 d->hasBrush = hadBrush;
814}
815
816void QPdfEngine::drawRects (const QRectF *rects, int rectCount)
817{
818 if (!rects)
819 return;
820
821 Q_D(QPdfEngine);
822
823 if (d->clipEnabled && d->allClipped)
824 return;
825 if (!d->hasPen && !d->hasBrush)
826 return;
827
828 if ((d->simplePen && !d->needsTransform) || !d->hasPen) {
829 // draw natively in this case for better output
830 if (!d->hasPen && d->needsTransform) // i.e. this is just a fillrect
831 *d->currentPage << "q\n" << QPdf::generateMatrix(d->stroker.matrix);
832 for (int i = 0; i < rectCount; ++i)
833 *d->currentPage << rects[i].x() << rects[i].y() << rects[i].width() << rects[i].height() << "re\n";
834 *d->currentPage << (d->hasPen ? (d->hasBrush ? "B\n" : "S\n") : "f\n");
835 if (!d->hasPen && d->needsTransform)
836 *d->currentPage << "Q\n";
837 } else {
838 QPainterPath p;
839 for (int i=0; i!=rectCount; ++i)
840 p.addRect(rects[i]);
841 drawPath(p);
842 }
843}
844
845void QPdfEngine::drawPolygon(const QPointF *points, int pointCount, PolygonDrawMode mode)
846{
847 Q_D(QPdfEngine);
848
849 if (!points || !pointCount)
850 return;
851
852 bool hb = d->hasBrush;
853 QPainterPath p;
854
855 switch(mode) {
856 case OddEvenMode:
857 p.setFillRule(Qt::OddEvenFill);
858 break;
859 case ConvexMode:
860 case WindingMode:
861 p.setFillRule(Qt::WindingFill);
862 break;
863 case PolylineMode:
864 d->hasBrush = false;
865 break;
866 default:
867 break;
868 }
869
870 p.moveTo(points[0]);
871 for (int i = 1; i < pointCount; ++i)
872 p.lineTo(points[i]);
873
874 if (mode != PolylineMode)
875 p.closeSubpath();
876 drawPath(p);
877
878 d->hasBrush = hb;
879}
880
881void QPdfEngine::drawPath (const QPainterPath &p)
882{
883 Q_D(QPdfEngine);
884
885 if (d->clipEnabled && d->allClipped)
886 return;
887 if (!d->hasPen && !d->hasBrush)
888 return;
889
890 if (d->simplePen) {
891 // draw strokes natively in this case for better output
892 *d->currentPage << QPdf::generatePath(p, d->needsTransform ? d->stroker.matrix : QTransform(),
893 d->hasBrush ? QPdf::FillAndStrokePath : QPdf::StrokePath);
894 } else {
895 if (d->hasBrush)
896 *d->currentPage << QPdf::generatePath(p, d->stroker.matrix, QPdf::FillPath);
897 if (d->hasPen) {
898 *d->currentPage << "q\n";
899 QBrush b = d->brush;
900 d->brush = d->pen.brush();
901 setBrush();
902 d->stroker.strokePath(p);
903 *d->currentPage << "Q\n";
904 d->brush = b;
905 }
906 }
907}
908
909void QPdfEngine::drawPixmap (const QRectF &rectangle, const QPixmap &pixmap, const QRectF &sr)
910{
911 if (sr.isEmpty() || rectangle.isEmpty() || pixmap.isNull())
912 return;
913 Q_D(QPdfEngine);
914
915 QBrush b = d->brush;
916
917 QRect sourceRect = sr.toRect();
918 QPixmap pm = sourceRect != pixmap.rect() ? pixmap.copy(sourceRect) : pixmap;
919 QImage image = pm.toImage();
920 bool bitmap = true;
921 const bool lossless = painter()->testRenderHint(QPainter::LosslessImageRendering);
922 const int object = d->addImage(image, &bitmap, lossless, pm.cacheKey());
923 if (object < 0)
924 return;
925
926 *d->currentPage << "q\n";
927
928 if ((d->pdfVersion != QPdfEngine::PdfVersion::PdfVersion_A1b) && (d->opacity != 1.0)) {
929 int stateObject = d->addConstantAlphaObject(qRound(255 * d->opacity), qRound(255 * d->opacity));
930 if (stateObject)
931 *d->currentPage << "/GState" << stateObject << "gs\n";
932 else
933 *d->currentPage << "/GSa gs\n";
934 } else {
935 *d->currentPage << "/GSa gs\n";
936 }
937
938 *d->currentPage
939 << QPdf::generateMatrix(QTransform(rectangle.width() / sr.width(), 0, 0, rectangle.height() / sr.height(),
940 rectangle.x(), rectangle.y()) * (!d->needsTransform ? QTransform() : d->stroker.matrix));
941 if (bitmap) {
942 // set current pen as d->brush
943 d->brush = d->pen.brush();
944 }
945 setBrush();
946 d->currentPage->streamImage(image.width(), image.height(), object);
947 *d->currentPage << "Q\n";
948
949 d->brush = b;
950}
951
952void QPdfEngine::drawImage(const QRectF &rectangle, const QImage &image, const QRectF &sr, Qt::ImageConversionFlags)
953{
954 if (sr.isEmpty() || rectangle.isEmpty() || image.isNull())
955 return;
956 Q_D(QPdfEngine);
957
958 QRect sourceRect = sr.toRect();
959 QImage im = sourceRect != image.rect() ? image.copy(sourceRect) : image;
960 bool bitmap = true;
961 const bool lossless = painter()->testRenderHint(QPainter::LosslessImageRendering);
962 const int object = d->addImage(im, &bitmap, lossless, im.cacheKey());
963 if (object < 0)
964 return;
965
966 *d->currentPage << "q\n";
967
968 if ((d->pdfVersion != QPdfEngine::PdfVersion::PdfVersion_A1b) && (d->opacity != 1.0)) {
969 int stateObject = d->addConstantAlphaObject(qRound(255 * d->opacity), qRound(255 * d->opacity));
970 if (stateObject)
971 *d->currentPage << "/GState" << stateObject << "gs\n";
972 else
973 *d->currentPage << "/GSa gs\n";
974 } else {
975 *d->currentPage << "/GSa gs\n";
976 }
977
978 *d->currentPage
979 << QPdf::generateMatrix(QTransform(rectangle.width() / sr.width(), 0, 0, rectangle.height() / sr.height(),
980 rectangle.x(), rectangle.y()) * (!d->needsTransform ? QTransform() : d->stroker.matrix));
981 setBrush();
982 d->currentPage->streamImage(im.width(), im.height(), object);
983 *d->currentPage << "Q\n";
984}
985
986void QPdfEngine::drawTiledPixmap (const QRectF &rectangle, const QPixmap &pixmap, const QPointF &point)
987{
988 Q_D(QPdfEngine);
989
990 bool bitmap = (pixmap.depth() == 1);
991 QBrush b = d->brush;
992 QPointF bo = d->brushOrigin;
993 bool hp = d->hasPen;
994 d->hasPen = false;
995 bool hb = d->hasBrush;
996 d->hasBrush = true;
997
998 d->brush = QBrush(pixmap);
999 if (bitmap)
1000 // #### fix bitmap case where we have a brush pen
1001 d->brush.setColor(d->pen.color());
1002
1003 d->brushOrigin = -point;
1004 *d->currentPage << "q\n";
1005 setBrush();
1006
1007 drawRects(&rectangle, 1);
1008 *d->currentPage << "Q\n";
1009
1010 d->hasPen = hp;
1011 d->hasBrush = hb;
1012 d->brush = b;
1013 d->brushOrigin = bo;
1014}
1015
1016void QPdfEngine::drawTextItem(const QPointF &p, const QTextItem &textItem)
1017{
1018 Q_D(QPdfEngine);
1019
1020 if (!d->hasPen || (d->clipEnabled && d->allClipped))
1021 return;
1022
1023 if (d->stroker.matrix.type() >= QTransform::TxProject) {
1024 QPaintEngine::drawTextItem(p, textItem);
1025 return;
1026 }
1027
1028 *d->currentPage << "q\n";
1029 if (d->needsTransform)
1030 *d->currentPage << QPdf::generateMatrix(d->stroker.matrix);
1031
1032 bool hp = d->hasPen;
1033 d->hasPen = false;
1034 QBrush b = d->brush;
1035 d->brush = d->pen.brush();
1036 setBrush();
1037
1038 const QTextItemInt &ti = static_cast<const QTextItemInt &>(textItem);
1039 Q_ASSERT(ti.fontEngine->type() != QFontEngine::Multi);
1040 d->drawTextItem(p, ti);
1041 d->hasPen = hp;
1042 d->brush = b;
1043 *d->currentPage << "Q\n";
1044}
1045
1046// Used by QtWebKit
1047void QPdfEngine::drawHyperlink(const QRectF &r, const QUrl &url)
1048{
1049 Q_D(QPdfEngine);
1050
1051 // PDF/X-4 (ยง 6.17) does not allow annotations that don't lie
1052 // outside the BleedBox/TrimBox, so don't emit an hyperlink
1053 // annotation at all.
1054 if (d->pdfVersion == QPdfEngine::PdfVersion::PdfVersion_X4)
1055 return;
1056
1057 const uint annot = d->addXrefEntry(-1);
1058 const QByteArray urlascii = url.toEncoded();
1059 int len = urlascii.size();
1060 QVarLengthArray<char> url_esc;
1061 url_esc.reserve(len + 1);
1062 for (int j = 0; j < len; j++) {
1063 if (urlascii[j] == '(' || urlascii[j] == ')' || urlascii[j] == '\\')
1064 url_esc.append('\\');
1065 url_esc.append(urlascii[j]);
1066 }
1067 url_esc.append('\0');
1068
1069 char buf[256];
1070 const QRectF rr = d->pageMatrix().mapRect(r);
1071 d->xprintf("<<\n/Type /Annot\n/Subtype /Link\n");
1072
1073 if (d->pdfVersion == QPdfEngine::PdfVersion::PdfVersion_A1b)
1074 d->xprintf("/F 4\n"); // enable print flag, disable all other
1075
1076 d->xprintf("/Rect [");
1077 d->xprintf("%s ", qt_real_to_string(rr.left(), buf));
1078 d->xprintf("%s ", qt_real_to_string(rr.top(), buf));
1079 d->xprintf("%s ", qt_real_to_string(rr.right(), buf));
1080 d->xprintf("%s", qt_real_to_string(rr.bottom(), buf));
1081 d->xprintf("]\n/Border [0 0 0]\n/A <<\n");
1082 d->xprintf("/Type /Action\n/S /URI\n/URI (%s)\n", url_esc.constData());
1083 d->xprintf(">>\n>>\n");
1084 d->xprintf("endobj\n");
1085 d->currentPage->annotations.append(annot);
1086}
1087
1088void QPdfEngine::updateState(const QPaintEngineState &state)
1089{
1090 Q_D(QPdfEngine);
1091
1092 QPaintEngine::DirtyFlags flags = state.state();
1093
1094 if (flags & DirtyHints)
1095 flags |= DirtyBrush;
1096
1097 if (flags & DirtyTransform)
1098 d->stroker.matrix = state.transform();
1099
1100 if (flags & DirtyPen) {
1101 if (d->pdfVersion == QPdfEngine::PdfVersion::PdfVersion_A1b) {
1102 QPen pen = state.pen();
1103
1104 QColor penColor = pen.color();
1105 if (penColor.alpha() != 255)
1106 penColor.setAlpha(255);
1107 pen.setColor(penColor);
1108
1109 QBrush penBrush = pen.brush();
1110 removeTransparencyFromBrush(penBrush);
1111 pen.setBrush(penBrush);
1112
1113 d->pen = pen;
1114 } else {
1115 d->pen = state.pen();
1116 }
1117 d->hasPen = d->pen.style() != Qt::NoPen;
1118 bool oldCosmetic = d->stroker.cosmeticPen;
1119 d->stroker.setPen(d->pen, state.renderHints());
1120 QBrush penBrush = d->pen.brush();
1121 bool oldSimple = d->simplePen;
1122 d->simplePen = (d->hasPen && (penBrush.style() == Qt::SolidPattern) && penBrush.isOpaque() && d->opacity == 1.0);
1123 if (oldSimple != d->simplePen || oldCosmetic != d->stroker.cosmeticPen)
1124 flags |= DirtyTransform;
1125 } else if (flags & DirtyHints) {
1126 d->stroker.setPen(d->pen, state.renderHints());
1127 }
1128 if (flags & DirtyBrush) {
1129 if (d->pdfVersion == QPdfEngine::PdfVersion::PdfVersion_A1b) {
1130 QBrush brush = state.brush();
1131 removeTransparencyFromBrush(brush);
1132 d->brush = brush;
1133 } else {
1134 d->brush = state.brush();
1135 }
1136 if (d->brush.color().alpha() == 0 && d->brush.style() == Qt::SolidPattern)
1137 d->brush.setStyle(Qt::NoBrush);
1138 d->hasBrush = d->brush.style() != Qt::NoBrush;
1139 }
1140 if (flags & DirtyBrushOrigin) {
1141 d->brushOrigin = state.brushOrigin();
1142 flags |= DirtyBrush;
1143 }
1144 if (flags & DirtyOpacity) {
1145 d->opacity = state.opacity();
1146 if (d->simplePen && d->opacity != 1.0) {
1147 d->simplePen = false;
1148 flags |= DirtyTransform;
1149 }
1150 }
1151
1152 bool ce = d->clipEnabled;
1153 if (flags & DirtyClipPath) {
1154 d->clipEnabled = true;
1155 updateClipPath(state.clipPath(), state.clipOperation());
1156 } else if (flags & DirtyClipRegion) {
1157 d->clipEnabled = true;
1158 QPainterPath path;
1159 for (const QRect &rect : state.clipRegion())
1160 path.addRect(rect);
1161 updateClipPath(path, state.clipOperation());
1162 flags |= DirtyClipPath;
1163 } else if (flags & DirtyClipEnabled) {
1164 d->clipEnabled = state.isClipEnabled();
1165 }
1166
1167 if (ce != d->clipEnabled)
1168 flags |= DirtyClipPath;
1169 else if (!d->clipEnabled)
1170 flags &= ~DirtyClipPath;
1171
1172 setupGraphicsState(flags);
1173}
1174
1175void QPdfEngine::setupGraphicsState(QPaintEngine::DirtyFlags flags)
1176{
1177 Q_D(QPdfEngine);
1178 if (flags & DirtyClipPath)
1179 flags |= DirtyTransform|DirtyPen|DirtyBrush;
1180
1181 if (flags & DirtyTransform) {
1182 *d->currentPage << "Q\n";
1183 flags |= DirtyPen|DirtyBrush;
1184 }
1185
1186 if (flags & DirtyClipPath) {
1187 *d->currentPage << "Q q\n";
1188
1189 d->allClipped = false;
1190 if (d->clipEnabled && !d->clips.isEmpty()) {
1191 for (int i = 0; i < d->clips.size(); ++i) {
1192 if (d->clips.at(i).isEmpty()) {
1193 d->allClipped = true;
1194 break;
1195 }
1196 }
1197 if (!d->allClipped) {
1198 for (int i = 0; i < d->clips.size(); ++i) {
1199 *d->currentPage << QPdf::generatePath(d->clips.at(i), QTransform(), QPdf::ClipPath);
1200 }
1201 }
1202 }
1203 }
1204
1205 if (flags & DirtyTransform) {
1206 *d->currentPage << "q\n";
1207 d->needsTransform = false;
1208 if (!d->stroker.matrix.isIdentity()) {
1209 if (d->simplePen && !d->stroker.cosmeticPen)
1210 *d->currentPage << QPdf::generateMatrix(d->stroker.matrix);
1211 else
1212 d->needsTransform = true; // I.e. page-wide xf not set, local xf needed
1213 }
1214 }
1215 if (flags & DirtyBrush)
1216 setBrush();
1217 if (d->simplePen && (flags & DirtyPen))
1218 setPen();
1219}
1220
1221void QPdfEngine::updateClipPath(const QPainterPath &p, Qt::ClipOperation op)
1222{
1223 Q_D(QPdfEngine);
1224 QPainterPath path = d->stroker.matrix.map(p);
1225 //qDebug() << "updateClipPath: " << d->stroker.matrix << p.boundingRect() << path.boundingRect() << op;
1226
1227 switch (op) {
1228 case Qt::NoClip:
1229 d->clipEnabled = false;
1230 d->clips.clear();
1231 break;
1232 case Qt::ReplaceClip:
1233 d->clips.clear();
1234 d->clips.append(path);
1235 break;
1236 case Qt::IntersectClip:
1237 d->clips.append(path);
1238 break;
1239 }
1240}
1241
1242void QPdfEngine::setPen()
1243{
1244 Q_D(QPdfEngine);
1245 if (d->pen.style() == Qt::NoPen)
1246 return;
1247 QBrush b = d->pen.brush();
1248 Q_ASSERT(b.style() == Qt::SolidPattern && b.isOpaque());
1249
1250 d->writeColor(QPdfEnginePrivate::ColorDomain::Stroking, b.color());
1251 *d->currentPage << "SCN\n";
1252 *d->currentPage << d->pen.widthF() << "w ";
1253
1254 int pdfCapStyle = 0;
1255 switch(d->pen.capStyle()) {
1256 case Qt::FlatCap:
1257 pdfCapStyle = 0;
1258 break;
1259 case Qt::SquareCap:
1260 pdfCapStyle = 2;
1261 break;
1262 case Qt::RoundCap:
1263 pdfCapStyle = 1;
1264 break;
1265 default:
1266 break;
1267 }
1268 *d->currentPage << pdfCapStyle << "J ";
1269
1270 int pdfJoinStyle = 0;
1271 switch(d->pen.joinStyle()) {
1272 case Qt::MiterJoin:
1273 case Qt::SvgMiterJoin:
1274 *d->currentPage << qMax(qreal(1.0), d->pen.miterLimit()) << "M ";
1275 pdfJoinStyle = 0;
1276 break;
1277 case Qt::BevelJoin:
1278 pdfJoinStyle = 2;
1279 break;
1280 case Qt::RoundJoin:
1281 pdfJoinStyle = 1;
1282 break;
1283 default:
1284 break;
1285 }
1286 *d->currentPage << pdfJoinStyle << "j ";
1287
1288 *d->currentPage << QPdf::generateDashes(d->pen);
1289}
1290
1291
1292void QPdfEngine::setBrush()
1293{
1294 Q_D(QPdfEngine);
1295 Qt::BrushStyle style = d->brush.style();
1296 if (style == Qt::NoBrush)
1297 return;
1298
1299 bool specifyColor;
1300 int gStateObject = 0;
1301 int patternObject = d->addBrushPattern(d->stroker.matrix, &specifyColor, &gStateObject);
1302 if (!patternObject && !specifyColor)
1303 return;
1304
1305 const auto domain = patternObject ? QPdfEnginePrivate::ColorDomain::NonStrokingPattern
1306 : QPdfEnginePrivate::ColorDomain::NonStroking;
1307 d->writeColor(domain, specifyColor ? d->brush.color() : QColor());
1308 if (patternObject)
1309 *d->currentPage << "/Pat" << patternObject;
1310 *d->currentPage << "scn\n";
1311
1312 if (gStateObject)
1313 *d->currentPage << "/GState" << gStateObject << "gs\n";
1314 else
1315 *d->currentPage << "/GSa gs\n";
1316}
1317
1318
1319bool QPdfEngine::newPage()
1320{
1321 Q_D(QPdfEngine);
1322 if (!isActive())
1323 return false;
1324 d->newPage();
1325
1326 setupGraphicsState(DirtyBrush|DirtyPen|DirtyClipPath);
1327 QFile *outfile = qobject_cast<QFile*> (d->outDevice);
1328 if (outfile && outfile->error() != QFile::NoError)
1329 return false;
1330 return true;
1331}
1332
1333QPaintEngine::Type QPdfEngine::type() const
1334{
1335 return QPaintEngine::Pdf;
1336}
1337
1338void QPdfEngine::setResolution(int resolution)
1339{
1340 Q_D(QPdfEngine);
1341 d->resolution = resolution;
1342}
1343
1344int QPdfEngine::resolution() const
1345{
1346 Q_D(const QPdfEngine);
1347 return d->resolution;
1348}
1349
1350void QPdfEngine::setPdfVersion(PdfVersion version)
1351{
1352 Q_D(QPdfEngine);
1353 d->pdfVersion = version;
1354}
1355
1356void QPdfEngine::setDocumentXmpMetadata(const QByteArray &xmpMetadata)
1357{
1358 Q_D(QPdfEngine);
1359 d->xmpDocumentMetadata = xmpMetadata;
1360}
1361
1362QByteArray QPdfEngine::documentXmpMetadata() const
1363{
1364 Q_D(const QPdfEngine);
1365 return d->xmpDocumentMetadata;
1366}
1367
1368void QPdfEngine::setPageLayout(const QPageLayout &pageLayout)
1369{
1370 Q_D(QPdfEngine);
1371 d->m_pageLayout = pageLayout;
1372}
1373
1374void QPdfEngine::setPageSize(const QPageSize &pageSize)
1375{
1376 Q_D(QPdfEngine);
1377 d->m_pageLayout.setPageSize(pageSize);
1378}
1379
1380void QPdfEngine::setPageOrientation(QPageLayout::Orientation orientation)
1381{
1382 Q_D(QPdfEngine);
1383 d->m_pageLayout.setOrientation(orientation);
1384}
1385
1386void QPdfEngine::setPageMargins(const QMarginsF &margins, QPageLayout::Unit units)
1387{
1388 Q_D(QPdfEngine);
1389 d->m_pageLayout.setUnits(units);
1390 d->m_pageLayout.setMargins(margins);
1391}
1392
1393QPageLayout QPdfEngine::pageLayout() const
1394{
1395 Q_D(const QPdfEngine);
1396 return d->m_pageLayout;
1397}
1398
1399// Metrics are in Device Pixels
1400int QPdfEngine::metric(QPaintDevice::PaintDeviceMetric metricType) const
1401{
1402 Q_D(const QPdfEngine);
1403 int val;
1404 switch (metricType) {
1405 case QPaintDevice::PdmWidth:
1406 val = d->m_pageLayout.paintRectPixels(d->resolution).width();
1407 break;
1408 case QPaintDevice::PdmHeight:
1409 val = d->m_pageLayout.paintRectPixels(d->resolution).height();
1410 break;
1411 case QPaintDevice::PdmDpiX:
1412 case QPaintDevice::PdmDpiY:
1413 val = d->resolution;
1414 break;
1415 case QPaintDevice::PdmPhysicalDpiX:
1416 case QPaintDevice::PdmPhysicalDpiY:
1417 val = 1200;
1418 break;
1419 case QPaintDevice::PdmWidthMM:
1420 val = qRound(d->m_pageLayout.paintRect(QPageLayout::Millimeter).width());
1421 break;
1422 case QPaintDevice::PdmHeightMM:
1423 val = qRound(d->m_pageLayout.paintRect(QPageLayout::Millimeter).height());
1424 break;
1425 case QPaintDevice::PdmNumColors:
1426 val = INT_MAX;
1427 break;
1428 case QPaintDevice::PdmDepth:
1429 val = 32;
1430 break;
1431 case QPaintDevice::PdmDevicePixelRatio:
1432 val = 1;
1433 break;
1434 case QPaintDevice::PdmDevicePixelRatioScaled:
1435 val = 1 * QPaintDevice::devicePixelRatioFScale();
1436 break;
1437 default:
1438 qWarning("QPdfWriter::metric: Invalid metric command");
1439 return 0;
1440 }
1441 return val;
1442}
1443
1444QPdfEnginePrivate::QPdfEnginePrivate()
1445 : clipEnabled(false), allClipped(false), hasPen(true), hasBrush(false), simplePen(false),
1446 needsTransform(false), pdfVersion(QPdfEngine::PdfVersion::PdfVersion_1_4),
1447 colorModel(QPdfEngine::ColorModel::Auto),
1448 outDevice(nullptr), ownsDevice(false),
1449 embedFonts(true),
1450 m_pageLayout(QPageSize(QPageSize::A4), QPageLayout::Portrait, QMarginsF(10, 10, 10, 10))
1451{
1452 initResources();
1453 resolution = 1200;
1454 currentObject = 1;
1455 currentPage = nullptr;
1456 stroker.stream = nullptr;
1457
1458 streampos = 0;
1459
1460 stream = new QDataStream;
1461}
1462
1463bool QPdfEngine::begin(QPaintDevice *pdev)
1464{
1465 Q_D(QPdfEngine);
1466 d->pdev = pdev;
1467
1468 if (!d->outDevice) {
1469 if (!d->outputFileName.isEmpty()) {
1470 QFile *file = new QFile(d->outputFileName);
1471 if (!file->open(QFile::WriteOnly|QFile::Truncate)) {
1472 delete file;
1473 return false;
1474 }
1475 d->outDevice = file;
1476 } else {
1477 return false;
1478 }
1479 d->ownsDevice = true;
1480 }
1481
1482 d->currentObject = 1;
1483
1484 d->currentPage = new QPdfPage;
1485 d->stroker.stream = d->currentPage;
1486 d->opacity = 1.0;
1487
1488 d->stream->setDevice(d->outDevice);
1489
1490 d->streampos = 0;
1491 d->hasPen = true;
1492 d->hasBrush = false;
1493 d->clipEnabled = false;
1494 d->allClipped = false;
1495
1496 d->xrefPositions.clear();
1497 d->pageRoot = 0;
1498 d->namesRoot = 0;
1499 d->destsRoot = 0;
1500 d->attachmentsRoot = 0;
1501 d->catalog = 0;
1502 d->info = 0;
1503 d->graphicsState = 0;
1504 d->patternColorSpaceRGB = 0;
1505 d->patternColorSpaceGrayscale = 0;
1506 d->patternColorSpaceCMYK = 0;
1507 d->simplePen = false;
1508 d->needsTransform = false;
1509
1510 d->pages.clear();
1511 d->imageCache.clear();
1512 d->alphaCache.clear();
1513
1514 setActive(true);
1515 d->writeHeader();
1516 newPage();
1517
1518 return true;
1519}
1520
1521bool QPdfEngine::end()
1522{
1523 Q_D(QPdfEngine);
1524 d->writeTail();
1525
1526 d->stream->setDevice(nullptr);
1527
1528 qDeleteAll(d->fonts);
1529 d->fonts.clear();
1530 delete d->currentPage;
1531 d->currentPage = nullptr;
1532
1533 if (d->outDevice && d->ownsDevice) {
1534 d->outDevice->close();
1535 delete d->outDevice;
1536 d->outDevice = nullptr;
1537 }
1538
1539 d->destCache.clear();
1540 d->fileCache.clear();
1541
1542 setActive(false);
1543 return true;
1544}
1545
1546void QPdfEngine::addFileAttachment(const QString &fileName, const QByteArray &data, const QString &mimeType)
1547{
1548 Q_D(QPdfEngine);
1549 d->fileCache.push_back({fileName, data, mimeType});
1550}
1551
1552QPdfEnginePrivate::~QPdfEnginePrivate()
1553{
1554 qDeleteAll(fonts);
1555 delete currentPage;
1556 delete stream;
1557}
1558
1559void QPdfEnginePrivate::writeHeader()
1560{
1561 addXrefEntry(0,false);
1562
1563 struct VersionString { // small wrapper around char[4]
1564 char data[4];
1565 Q_IMPLICIT constexpr VersionString(const char (&s)[4]) // clazy:exclude=function-args-by-value
1566 : data{s[0], s[1], s[2], s[3]} {}
1567 };
1568 constexpr QEnumIndexedArray<VersionString, QPdfEngine::PdfVersion, QPdfEngine::NumPdfVersions> mapping = {{{
1569 { QPdfEngine::PdfVersion::PdfVersion_1_4, "1.4" },
1570 { QPdfEngine::PdfVersion::PdfVersion_A1b, "1.4" },
1571 { QPdfEngine::PdfVersion::PdfVersion_1_6, "1.6" },
1572 { QPdfEngine::PdfVersion::PdfVersion_X4, "1.6" },
1573 }}};
1574 const char *verStr = mapping[pdfVersion].data;
1575
1576 xprintf("%%PDF-%s\n", verStr);
1577 xprintf("%%\303\242\303\243\n");
1578
1579#if QT_CONFIG(timezone)
1580 const QDateTime now = QDateTime::currentDateTime(QTimeZone::systemTimeZone());
1581#else
1582 const QDateTime now = QDateTime::currentDateTimeUtc();
1583#endif
1584
1585 writeInfo(now);
1586
1587 const int metaDataObj = writeXmpDocumentMetaData(now);
1588 const int outputIntentObj = [&]() {
1589 switch (pdfVersion) {
1590 case QPdfEngine::PdfVersion::PdfVersion_1_4:
1591 case QPdfEngine::PdfVersion::PdfVersion_1_6:
1592 break;
1593 case QPdfEngine::PdfVersion::PdfVersion_A1b:
1594 case QPdfEngine::PdfVersion::PdfVersion_X4:
1595 return writeOutputIntent();
1596 }
1597
1598 return -1;
1599 }();
1600
1601 catalog = addXrefEntry(-1);
1602 pageRoot = requestObject();
1603 namesRoot = requestObject();
1604
1605 // catalog
1606 {
1607 QByteArray catalog;
1608 QPdf::ByteStream s(&catalog);
1609 s << "<<\n"
1610 << "/Type /Catalog\n"
1611 << "/Pages " << pageRoot << "0 R\n"
1612 << "/Names " << namesRoot << "0 R\n";
1613
1614 s << "/Metadata " << metaDataObj << "0 R\n";
1615
1616 if (outputIntentObj >= 0)
1617 s << "/OutputIntents [" << outputIntentObj << "0 R]\n";
1618
1619 s << ">>\n"
1620 << "endobj\n";
1621
1622 write(catalog);
1623 }
1624
1625 // graphics state
1626 graphicsState = addXrefEntry(-1);
1627 xprintf("<<\n"
1628 "/Type /ExtGState\n"
1629 "/SA true\n"
1630 "/SM 0.02\n"
1631 "/ca 1.0\n"
1632 "/CA 1.0\n"
1633 "/AIS false\n"
1634 "/SMask /None"
1635 ">>\n"
1636 "endobj\n");
1637
1638 // color spaces for pattern
1639 patternColorSpaceRGB = addXrefEntry(-1);
1640 xprintf("[/Pattern /DeviceRGB]\n"
1641 "endobj\n");
1642 patternColorSpaceGrayscale = addXrefEntry(-1);
1643 xprintf("[/Pattern /DeviceGray]\n"
1644 "endobj\n");
1645 patternColorSpaceCMYK = addXrefEntry(-1);
1646 xprintf("[/Pattern /DeviceCMYK]\n"
1647 "endobj\n");
1648}
1649
1650QPdfEngine::ColorModel QPdfEnginePrivate::colorModelForColor(const QColor &color) const
1651{
1652 switch (colorModel) {
1653 case QPdfEngine::ColorModel::RGB:
1654 case QPdfEngine::ColorModel::Grayscale:
1655 case QPdfEngine::ColorModel::CMYK:
1656 return colorModel;
1657 case QPdfEngine::ColorModel::Auto:
1658 switch (color.spec()) {
1659 case QColor::Invalid:
1660 case QColor::Rgb:
1661 case QColor::Hsv:
1662 case QColor::Hsl:
1663 case QColor::ExtendedRgb:
1664 return QPdfEngine::ColorModel::RGB;
1665 case QColor::Cmyk:
1666 return QPdfEngine::ColorModel::CMYK;
1667 }
1668
1669 break;
1670 }
1671
1672 Q_UNREACHABLE_RETURN(QPdfEngine::ColorModel::RGB);
1673}
1674
1675void QPdfEnginePrivate::writeColor(ColorDomain domain, const QColor &color)
1676{
1677 // Switch to the right colorspace.
1678 // For simplicity: do it even if it redundant (= already in that colorspace)
1679 const QPdfEngine::ColorModel actualColorModel = colorModelForColor(color);
1680
1681 switch (actualColorModel) {
1682 case QPdfEngine::ColorModel::RGB:
1683 switch (domain) {
1684 case ColorDomain::Stroking:
1685 *currentPage << "/CSp CS\n"; break;
1686 case ColorDomain::NonStroking:
1687 *currentPage << "/CSp cs\n"; break;
1688 case ColorDomain::NonStrokingPattern:
1689 *currentPage << "/PCSp cs\n"; break;
1690 }
1691 break;
1692 case QPdfEngine::ColorModel::Grayscale:
1693 switch (domain) {
1694 case ColorDomain::Stroking:
1695 *currentPage << "/CSpg CS\n"; break;
1696 case ColorDomain::NonStroking:
1697 *currentPage << "/CSpg cs\n"; break;
1698 case ColorDomain::NonStrokingPattern:
1699 *currentPage << "/PCSpg cs\n"; break;
1700 }
1701 break;
1702 case QPdfEngine::ColorModel::CMYK:
1703 switch (domain) {
1704 case ColorDomain::Stroking:
1705 *currentPage << "/CSpcmyk CS\n"; break;
1706 case ColorDomain::NonStroking:
1707 *currentPage << "/CSpcmyk cs\n"; break;
1708 case ColorDomain::NonStrokingPattern:
1709 *currentPage << "/PCSpcmyk cs\n"; break;
1710 }
1711 break;
1712 case QPdfEngine::ColorModel::Auto:
1713 Q_UNREACHABLE_RETURN();
1714 }
1715
1716 // If we also have a color specified, write it out.
1717 if (!color.isValid())
1718 return;
1719
1720 switch (actualColorModel) {
1721 case QPdfEngine::ColorModel::RGB:
1722 *currentPage << color.redF()
1723 << color.greenF()
1724 << color.blueF();
1725 break;
1726 case QPdfEngine::ColorModel::Grayscale: {
1727 const qreal gray = qGray(color.rgba()) / 255.;
1728 *currentPage << gray;
1729 break;
1730 }
1731 case QPdfEngine::ColorModel::CMYK:
1732 *currentPage << color.cyanF()
1733 << color.magentaF()
1734 << color.yellowF()
1735 << color.blackF();
1736 break;
1737 case QPdfEngine::ColorModel::Auto:
1738 Q_UNREACHABLE_RETURN();
1739 }
1740}
1741
1742void QPdfEnginePrivate::writeInfo(const QDateTime &date)
1743{
1744 info = addXrefEntry(-1);
1745 write("<<\n/Title ");
1746 printString(title);
1747 write("\n/Creator ");
1748 printString(creator);
1749 write("\n/Author ");
1750 printString(author);
1751 write("\n/Producer ");
1752 printString(QString::fromLatin1("Qt " QT_VERSION_STR));
1753
1754 const QTime t = date.time();
1755 const QDate d = date.date();
1756 // (D:YYYYMMDDHHmmSSOHH'mm')
1757 constexpr size_t formattedDateSize = 26;
1758 char formattedDate[formattedDateSize];
1759 const int year = qBound(0, d.year(), 9999); // ASN.1, max 4 digits
1760 auto printedSize = std::snprintf(formattedDate,
1761 formattedDateSize,
1762 "(D:%04d%02d%02d%02d%02d%02d",
1763 year,
1764 d.month(),
1765 d.day(),
1766 t.hour(),
1767 t.minute(),
1768 t.second());
1769 const int offset = date.offsetFromUtc();
1770 const int hours = (offset / 60) / 60;
1771 const int mins = (offset / 60) % 60;
1772 if (offset < 0) {
1773 std::snprintf(formattedDate + printedSize,
1774 formattedDateSize - printedSize,
1775 "-%02d'%02d')", -hours, -mins);
1776 } else if (offset > 0) {
1777 std::snprintf(formattedDate + printedSize,
1778 formattedDateSize - printedSize,
1779 "+%02d'%02d')", hours, mins);
1780 } else {
1781 std::snprintf(formattedDate + printedSize,
1782 formattedDateSize - printedSize,
1783 "Z)");
1784 }
1785
1786 write("\n/CreationDate ");
1787 write(formattedDate);
1788 write("\n/ModDate ");
1789 write(formattedDate);
1790
1791 write("\n/Trapped /False\n"
1792 ">>\n"
1793 "endobj\n");
1794}
1795
1796int QPdfEnginePrivate::writeXmpDocumentMetaData(const QDateTime &date)
1797{
1798 const int metaDataObj = addXrefEntry(-1);
1799 QByteArray metaDataContent;
1800
1801 if (!xmpDocumentMetadata.isEmpty()) {
1802 metaDataContent = xmpDocumentMetadata;
1803 } else {
1804 const QString producer(QString::fromLatin1("Qt " QT_VERSION_STR));
1805 const QString metaDataDate = date.toString(Qt::ISODate);
1806
1807 using namespace Qt::Literals;
1808 constexpr QLatin1String xmlNS = "http://www.w3.org/XML/1998/namespace"_L1;
1809
1810 constexpr QLatin1String adobeNS = "adobe:ns:meta/"_L1;
1811 constexpr QLatin1String rdfNS = "http://www.w3.org/1999/02/22-rdf-syntax-ns#"_L1;
1812 constexpr QLatin1String dcNS = "http://purl.org/dc/elements/1.1/"_L1;
1813 constexpr QLatin1String xmpNS = "http://ns.adobe.com/xap/1.0/"_L1;
1814 constexpr QLatin1String xmpMMNS = "http://ns.adobe.com/xap/1.0/mm/"_L1;
1815 constexpr QLatin1String pdfNS = "http://ns.adobe.com/pdf/1.3/"_L1;
1816 constexpr QLatin1String pdfaidNS = "http://www.aiim.org/pdfa/ns/id/"_L1;
1817 constexpr QLatin1String pdfxidNS = "http://www.npes.org/pdfx/ns/id/"_L1;
1818
1819 QBuffer output(&metaDataContent);
1820 output.open(QIODevice::WriteOnly);
1821 output.write("<?xpacket begin='' id='W5M0MpCehiHzreSzNTczkc9d'?>");
1822
1823 QXmlStreamWriter w(&output);
1824 w.setAutoFormatting(true);
1825 w.writeNamespace(adobeNS, "x");
1826 w.writeNamespace(rdfNS, "rdf");
1827 w.writeNamespace(dcNS, "dc");
1828 w.writeNamespace(xmpNS, "xmp");
1829 w.writeNamespace(xmpMMNS, "xmpMM");
1830 w.writeNamespace(pdfNS, "pdf");
1831 w.writeNamespace(pdfaidNS, "pdfaid");
1832 w.writeNamespace(pdfxidNS, "pdfxid");
1833
1834 w.writeStartElement(adobeNS, "xmpmeta");
1835 w.writeStartElement(rdfNS, "RDF");
1836
1837 /*
1838 XMP says: "The recommended approach is to have either a
1839 single rdf:Description element containing all XMP
1840 properties or a separate rdf:Description element for each
1841 XMP property namespace."
1842 We do the the latter.
1843 */
1844
1845 // DC
1846 w.writeStartElement(rdfNS, "Description");
1847 w.writeAttribute(rdfNS, "about", "");
1848 w.writeStartElement(dcNS, "title");
1849 w.writeStartElement(rdfNS, "Alt");
1850 w.writeStartElement(rdfNS, "li");
1851 w.writeAttribute(xmlNS, "lang", "x-default");
1852 w.writeCharacters(title);
1853 w.writeEndElement();
1854 w.writeEndElement();
1855 w.writeEndElement();
1856 w.writeStartElement(dcNS, "creator");
1857 w.writeStartElement(rdfNS, "Seq");
1858 w.writeStartElement(rdfNS, "li");
1859 w.writeCharacters(author);
1860 w.writeEndElement();
1861 w.writeEndElement();
1862 w.writeEndElement();
1863 w.writeEndElement();
1864
1865 // PDF
1866 w.writeStartElement(rdfNS, "Description");
1867 w.writeAttribute(rdfNS, "about", "");
1868 w.writeAttribute(pdfNS, "Producer", producer);
1869 w.writeAttribute(pdfNS, "Trapped", "False");
1870 w.writeEndElement();
1871
1872 // XMP
1873 w.writeStartElement(rdfNS, "Description");
1874 w.writeAttribute(rdfNS, "about", "");
1875 w.writeAttribute(xmpNS, "CreatorTool", creator);
1876 w.writeAttribute(xmpNS, "CreateDate", metaDataDate);
1877 w.writeAttribute(xmpNS, "ModifyDate", metaDataDate);
1878 w.writeAttribute(xmpNS, "MetadataDate", metaDataDate);
1879 w.writeEndElement();
1880
1881 // XMPMM
1882 w.writeStartElement(rdfNS, "Description");
1883 w.writeAttribute(rdfNS, "about", "");
1884 w.writeAttribute(xmpMMNS, "DocumentID", "uuid:"_L1 + documentId.toString(QUuid::WithoutBraces));
1885 w.writeAttribute(xmpMMNS, "VersionID", "1");
1886 w.writeAttribute(xmpMMNS, "RenditionClass", "default");
1887 w.writeEndElement();
1888
1889 // Version-specific
1890 switch (pdfVersion) {
1891 case QPdfEngine::PdfVersion::PdfVersion_1_4:
1892 break;
1893 case QPdfEngine::PdfVersion::PdfVersion_A1b:
1894 w.writeStartElement(rdfNS, "Description");
1895 w.writeAttribute(rdfNS, "about", "");
1896 w.writeAttribute(pdfaidNS, "part", "1");
1897 w.writeAttribute(pdfaidNS, "conformance", "B");
1898 w.writeEndElement();
1899 break;
1900 case QPdfEngine::PdfVersion::PdfVersion_1_6:
1901 break;
1902 case QPdfEngine::PdfVersion::PdfVersion_X4:
1903 w.writeStartElement(rdfNS, "Description");
1904 w.writeAttribute(rdfNS, "about", "");
1905 w.writeAttribute(pdfxidNS, "GTS_PDFXVersion", "PDF/X-4");
1906 w.writeEndElement();
1907 break;
1908 }
1909
1910 w.writeEndElement(); // </RDF>
1911 w.writeEndElement(); // </xmpmeta>
1912
1913 w.writeEndDocument();
1914 output.write("<?xpacket end='w'?>");
1915 }
1916
1917 xprintf("<<\n"
1918 "/Type /Metadata /Subtype /XML\n"
1919 "/Length %" PRIdQSIZETYPE "\n"
1920 ">>\n"
1921 "stream\n", metaDataContent.size());
1922 write(metaDataContent);
1923 xprintf("\nendstream\n"
1924 "endobj\n");
1925
1926 return metaDataObj;
1927}
1928
1929int QPdfEnginePrivate::writeOutputIntent()
1930{
1931 const int colorProfileEntry = addXrefEntry(-1);
1932 {
1933 const QColorSpace profile = outputIntent.outputProfile();
1934 const QByteArray colorProfileData = profile.iccProfile();
1935
1936 QByteArray data;
1937 QPdf::ByteStream s(&data);
1938 int length_object = requestObject();
1939
1940 s << "<<\n";
1941
1942 switch (profile.colorModel()) {
1943 case QColorSpace::ColorModel::Undefined:
1944 qWarning("QPdfEngine: undefined color model in the output intent profile, assuming RGB");
1945 [[fallthrough]];
1946 case QColorSpace::ColorModel::Rgb:
1947 s << "/N 3\n";
1948 s << "/Alternate /DeviceRGB\n";
1949 break;
1950 case QColorSpace::ColorModel::Gray:
1951 s << "/N 1\n";
1952 s << "/Alternate /DeviceGray\n";
1953 break;
1954 case QColorSpace::ColorModel::Cmyk:
1955 s << "/N 4\n";
1956 s << "/Alternate /DeviceCMYK\n";
1957 break;
1958 }
1959
1960 s << "/Length " << length_object << "0 R\n";
1961 if (do_compress)
1962 s << "/Filter /FlateDecode\n";
1963 s << ">>\n";
1964 s << "stream\n";
1965 write(data);
1966 const int len = writeCompressed(colorProfileData);
1967 write("\nendstream\n"
1968 "endobj\n");
1969 addXrefEntry(length_object);
1970 xprintf("%d\n"
1971 "endobj\n", len);
1972 }
1973
1974 const int outputIntentEntry = addXrefEntry(-1);
1975 {
1976 write("<<\n");
1977 write("/Type /OutputIntent\n");
1978
1979 switch (pdfVersion) {
1980 case QPdfEngine::PdfVersion::PdfVersion_1_4:
1981 case QPdfEngine::PdfVersion::PdfVersion_1_6:
1982 Q_UNREACHABLE(); // no output intent for these versions
1983 break;
1984 case QPdfEngine::PdfVersion::PdfVersion_A1b:
1985 write("/S/GTS_PDFA1\n");
1986 break;
1987 case QPdfEngine::PdfVersion::PdfVersion_X4:
1988 write("/S/GTS_PDFX\n");
1989 break;
1990 }
1991
1992 xprintf("/DestOutputProfile %d 0 R\n", colorProfileEntry);
1993 write("/OutputConditionIdentifier ");
1994 printString(outputIntent.outputConditionIdentifier());
1995 write("\n");
1996
1997 write("/Info ");
1998 printString(outputIntent.outputCondition());
1999 write("\n");
2000
2001 write("/OutputCondition ");
2002 printString(outputIntent.outputCondition());
2003 write("\n");
2004
2005 if (const auto registryName = outputIntent.registryName(); !registryName.isEmpty()) {
2006 write("/RegistryName ");
2007 printString(registryName.toString());
2008 write("\n");
2009 }
2010
2011 write(">>\n");
2012 write("endobj\n");
2013 }
2014
2015 return outputIntentEntry;
2016}
2017
2018void QPdfEnginePrivate::writePageRoot()
2019{
2020 addXrefEntry(pageRoot);
2021
2022 xprintf("<<\n"
2023 "/Type /Pages\n"
2024 "/Kids \n"
2025 "[\n");
2026 int size = pages.size();
2027 for (int i = 0; i < size; ++i)
2028 xprintf("%d 0 R\n", pages[i]);
2029 xprintf("]\n");
2030
2031 //xprintf("/Group <</S /Transparency /I true /K false>>\n");
2032 xprintf("/Count %" PRIdQSIZETYPE "\n", pages.size());
2033
2034 xprintf("/ProcSet [/PDF /Text /ImageB /ImageC]\n"
2035 ">>\n"
2036 "endobj\n");
2037}
2038
2039void QPdfEnginePrivate::writeDestsRoot()
2040{
2041 if (destCache.isEmpty())
2042 return;
2043
2044 std::map<QString, int> destObjects;
2045 QByteArray xs, ys;
2046 for (const DestInfo &destInfo : std::as_const(destCache)) {
2047 int destObj = addXrefEntry(-1);
2048 xs.setNum(static_cast<double>(destInfo.coords.x()), 'f');
2049 ys.setNum(static_cast<double>(destInfo.coords.y()), 'f');
2050 xprintf("[%d 0 R /XYZ %s %s 0]\n", destInfo.pageObj, xs.constData(), ys.constData());
2051 xprintf("endobj\n");
2052 destObjects.insert_or_assign(destInfo.anchor, destObj);
2053 }
2054
2055 // names
2056 destsRoot = addXrefEntry(-1);
2057 xprintf("<<\n/Limits [");
2058 printString(destObjects.begin()->first);
2059 xprintf(" ");
2060 printString(destObjects.rbegin()->first);
2061 xprintf("]\n/Names [\n");
2062 for (const auto &[anchor, destObject] : destObjects) {
2063 printString(anchor);
2064 xprintf(" %d 0 R\n", destObject);
2065 }
2066 xprintf("]\n>>\n"
2067 "endobj\n");
2068}
2069
2070/*!
2071 \internal
2072
2073 Returns \a string as a file specification string object, including the
2074 enclosing parentheses, for the \c /F entry of a file specification
2075 dictionary.
2076
2077 A file specification string is a byte string, so only printable ASCII can
2078 be passed to readers reliably. Characters outside of that range are
2079 replaced by '?'; the exact name is stored in the \c /UF entry, which is a
2080 Unicode text string (ISO 32000-1, table 44).
2081*/
2082static QByteArray pdfFileSpecName(QStringView string)
2083{
2084 QByteArray result;
2085 result.reserve(string.size() + 2);
2086 result.append('(');
2087 QStringIterator it(string);
2088 while (it.hasNext()) {
2089 const char32_t uc = it.next();
2090 char c = '?';
2091 if (uc >= 0x20 && uc <= 0x7e)
2092 c = char(uc);
2093 if (c == '(' || c == ')' || c == '\\')
2094 result.append('\\');
2095 result.append(c);
2096 }
2097 result.append(')');
2098 return result;
2099}
2100
2101void QPdfEnginePrivate::writeAttachmentRoot()
2102{
2103 if (fileCache.isEmpty())
2104 return;
2105
2106 QList<int> attachments;
2107 const int size = fileCache.size();
2108 for (int i = 0; i < size; ++i) {
2109 auto attachment = fileCache.at(i);
2110 const int attachmentID = addXrefEntry(-1);
2111 xprintf("<<\n");
2112 if (do_compress)
2113 xprintf("/Filter /FlateDecode\n");
2114
2115 const int lenobj = requestObject();
2116 xprintf("/Length %d 0 R\n", lenobj);
2117 int len = 0;
2118 xprintf(">>\nstream\n");
2119 len = writeCompressed(attachment.data);
2120 xprintf("\nendstream\n"
2121 "endobj\n");
2122 addXrefEntry(lenobj);
2123 xprintf("%d\n"
2124 "endobj\n", len);
2125
2126 attachments.push_back(addXrefEntry(-1));
2127 xprintf("<<\n"
2128 "/F ");
2129 write(pdfFileSpecName(attachment.fileName));
2130
2131 // /F is a byte string and can only carry the ASCII fallback. The exact
2132 // name goes into /UF, which is a Unicode text string. Table 44 of
2133 // ISO 32000-1 recommends writing both, and PDF/A-2 and PDF/A-3 require
2134 // both entries on embedded file specifications.
2135 xprintf("\n/UF ");
2136 printString(attachment.fileName);
2137
2138 xprintf("\n/EF <</F %d 0 R>>\n"
2139 "/Type/Filespec\n"
2140 , attachmentID);
2141 if (!attachment.mimeType.isEmpty())
2142 xprintf("/Subtype/%s\n",
2143 attachment.mimeType.replace("/"_L1, "#2F"_L1).toLatin1().constData());
2144 xprintf(">>\nendobj\n");
2145 }
2146
2147 // names
2148 attachmentsRoot = addXrefEntry(-1);
2149 xprintf("<</Names[");
2150 for (int i = 0; i < size; ++i) {
2151 auto attachment = fileCache.at(i);
2152 // The name tree keys are never displayed to the user, and they must be
2153 // unique: the ASCII fallback used for /F may map several names to the
2154 // same string, so store the exact name as a Unicode text string.
2155 printString(attachment.fileName);
2156 xprintf("%d 0 R\n", attachments.at(i));
2157 }
2158 xprintf("]>>\n"
2159 "endobj\n");
2160}
2161
2162void QPdfEnginePrivate::writeNamesRoot()
2163{
2164 addXrefEntry(namesRoot);
2165 xprintf("<<\n");
2166
2167 if (attachmentsRoot)
2168 xprintf("/EmbeddedFiles %d 0 R\n", attachmentsRoot);
2169
2170 if (destsRoot)
2171 xprintf("/Dests %d 0 R\n", destsRoot);
2172
2173 xprintf(">>\n");
2174 xprintf("endobj\n");
2175}
2176
2177static QByteArray qt_toPdfName(const QByteArray &input, qsizetype maxLength)
2178{
2179 // The name length limit applies to the unescaped name, where an escape
2180 // sequence counts as a single byte (ISO 32000-1, 7.3.5)
2181 const qsizetype length = qMin(input.size(), maxLength);
2182 QByteArray output;
2183 output.reserve(length);
2184 for (qsizetype i = 0; i < length; ++i) {
2185 const uchar c = uchar(input.at(i));
2186 switch (c) {
2187 case 0:
2188 continue;
2189 case '(': case ')': case '<': case '>': case '[': case ']':
2190 case '{': case '}': case '/': case '%': case '#':
2191 break;
2192 default:
2193 if (c > ' ' && c < 0x7f) {
2194 output += char(c);
2195 continue;
2196 }
2197 break;
2198 }
2199 char hex[3];
2200 output += '#';
2201 output += QPdf::toHex(c, hex);
2202 }
2203 return output;
2204}
2205
2206void QPdfEnginePrivate::embedFont(QFontSubset *font)
2207{
2208 //qDebug() << "embedFont" << font->object_id;
2209 int fontObject = font->object_id;
2210 QByteArray fontData = font->toTruetype();
2211#ifdef FONT_DUMP
2212 static int i = 0;
2213 QString fileName("font%1.ttf");
2214 fileName = fileName.arg(i++);
2215 QFile ff(fileName);
2216 ff.open(QFile::WriteOnly);
2217 ff.write(fontData);
2218 ff.close();
2219#endif
2220
2221 int fontDescriptor = requestObject();
2222 int fontstream = requestObject();
2223 int cidfont = requestObject();
2224 int toUnicode = requestObject();
2225 int cidset = requestObject();
2226
2227 QFontEngine::Properties properties = font->fontEngine->properties();
2228
2229 constexpr qsizetype MaxNameLength = 127; // ISO 32000-1, Annex C
2230 const qsizetype subsetTagLength = 7;
2231 const QByteArray postscriptName = qt_toPdfName(properties.postscriptName,
2232 MaxNameLength - subsetTagLength);
2233
2234 {
2235 qreal scale = 1000/properties.emSquare.toReal();
2236 addXrefEntry(fontDescriptor);
2237 QByteArray descriptor;
2238 QPdf::ByteStream s(&descriptor);
2239 s << "<< /Type /FontDescriptor\n"
2240 "/FontName /Q";
2241 int tag = fontDescriptor;
2242 for (int i = 0; i < 5; ++i) {
2243 s << (char)('A' + (tag % 26));
2244 tag /= 26;
2245 }
2246 s << '+' << postscriptName << "\n"
2247 "/Flags " << 4 << "\n"
2248 "/FontBBox ["
2249 << properties.boundingBox.x()*scale
2250 << -(properties.boundingBox.y() + properties.boundingBox.height())*scale
2251 << (properties.boundingBox.x() + properties.boundingBox.width())*scale
2252 << -properties.boundingBox.y()*scale << "]\n"
2253 "/ItalicAngle " << properties.italicAngle.toReal() << "\n"
2254 "/Ascent " << properties.ascent.toReal()*scale << "\n"
2255 "/Descent " << -properties.descent.toReal()*scale << "\n"
2256 "/CapHeight " << properties.capHeight.toReal()*scale << "\n"
2257 "/StemV " << properties.lineWidth.toReal()*scale << "\n"
2258 "/FontFile2 " << fontstream << "0 R\n"
2259 "/CIDSet " << cidset << "0 R\n"
2260 ">>\nendobj\n";
2261 write(descriptor);
2262 }
2263 {
2264 addXrefEntry(fontstream);
2265 QByteArray header;
2266 QPdf::ByteStream s(&header);
2267
2268 int length_object = requestObject();
2269 s << "<<\n"
2270 "/Length1 " << fontData.size() << "\n"
2271 "/Length " << length_object << "0 R\n";
2272 if (do_compress)
2273 s << "/Filter /FlateDecode\n";
2274 s << ">>\n"
2275 "stream\n";
2276 write(header);
2277 int len = writeCompressed(fontData);
2278 write("\nendstream\n"
2279 "endobj\n");
2280 addXrefEntry(length_object);
2281 xprintf("%d\n"
2282 "endobj\n", len);
2283 }
2284 {
2285 addXrefEntry(cidfont);
2286 QByteArray cid;
2287 QPdf::ByteStream s(&cid);
2288 s << "<< /Type /Font\n"
2289 "/Subtype /CIDFontType2\n"
2290 "/BaseFont /" << postscriptName << "\n"
2291 "/CIDSystemInfo << /Registry (Adobe) /Ordering (Identity) /Supplement 0 >>\n"
2292 "/FontDescriptor " << fontDescriptor << "0 R\n"
2293 "/CIDToGIDMap /Identity\n"
2294 << font->widthArray() <<
2295 ">>\n"
2296 "endobj\n";
2297 write(cid);
2298 }
2299 {
2300 addXrefEntry(toUnicode);
2301 QByteArray touc = font->createToUnicodeMap();
2302 xprintf("<< /Length %" PRIdQSIZETYPE " >>\n"
2303 "stream\n", touc.size());
2304 write(touc);
2305 write("\nendstream\n"
2306 "endobj\n");
2307 }
2308 {
2309 addXrefEntry(fontObject);
2310 QByteArray font;
2311 QPdf::ByteStream s(&font);
2312 s << "<< /Type /Font\n"
2313 "/Subtype /Type0\n"
2314 "/BaseFont /" << postscriptName << "\n"
2315 "/Encoding /Identity-H\n"
2316 "/DescendantFonts [" << cidfont << "0 R]\n"
2317 "/ToUnicode " << toUnicode << "0 R"
2318 ">>\n"
2319 "endobj\n";
2320 write(font);
2321 }
2322 {
2323 QByteArray cidSetStream(font->nGlyphs() / 8 + 1, 0);
2324 int byteCounter = 0;
2325 int bitCounter = 0;
2326 for (qsizetype i = 0; i < font->nGlyphs(); ++i) {
2327 cidSetStream.data()[byteCounter] |= (1 << (7 - bitCounter));
2328
2329 bitCounter++;
2330 if (bitCounter == 8) {
2331 bitCounter = 0;
2332 byteCounter++;
2333 }
2334 }
2335
2336 addXrefEntry(cidset);
2337 xprintf("<<\n");
2338 xprintf("/Length %" PRIdQSIZETYPE "\n", cidSetStream.size());
2339 xprintf(">>\n");
2340 xprintf("stream\n");
2341 write(cidSetStream);
2342 xprintf("\nendstream\n");
2343 xprintf("endobj\n");
2344 }
2345}
2346
2347qreal QPdfEnginePrivate::calcUserUnit() const
2348{
2349 // PDF standards < 1.6 support max 200x200in pages (no UserUnit)
2350 if (pdfVersion < QPdfEngine::PdfVersion::PdfVersion_1_6)
2351 return 1.0;
2352
2353 const int maxLen = qMax(currentPage->pageSize.width(), currentPage->pageSize.height());
2354 if (maxLen <= 14400)
2355 return 1.0; // for pages up to 200x200in (14400x14400 units) use default scaling
2356
2357 // for larger pages, rescale units so we can have up to 381x381km
2358 return qMin(maxLen / 14400.0, 75000.0);
2359}
2360
2361void QPdfEnginePrivate::writeFonts()
2362{
2363 for (QHash<QFontEngine::FaceId, QFontSubset *>::iterator it = fonts.begin(); it != fonts.end(); ++it) {
2364 embedFont(*it);
2365 delete *it;
2366 }
2367 fonts.clear();
2368}
2369
2370void QPdfEnginePrivate::writePage()
2371{
2372 if (pages.empty())
2373 return;
2374
2375 *currentPage << "Q Q\n";
2376
2377 uint pageStream = requestObject();
2378 uint pageStreamLength = requestObject();
2379 uint resources = requestObject();
2380 uint annots = requestObject();
2381
2382 qreal userUnit = calcUserUnit();
2383
2384 addXrefEntry(pages.constLast());
2385
2386 // make sure we use the pagesize from when we started the page, since the user may have changed it
2387 const QByteArray formattedPageWidth = QByteArray::number(currentPage->pageSize.width() / userUnit, 'f');
2388 const QByteArray formattedPageHeight = QByteArray::number(currentPage->pageSize.height() / userUnit, 'f');
2389
2390 xprintf("<<\n"
2391 "/Type /Page\n"
2392 "/Parent %d 0 R\n"
2393 "/Contents %d 0 R\n"
2394 "/Resources %d 0 R\n"
2395 "/Annots %d 0 R\n"
2396 "/MediaBox [0 0 %s %s]\n"
2397 "/TrimBox [0 0 %s %s]\n",
2398 pageRoot, pageStream, resources, annots,
2399 formattedPageWidth.constData(),
2400 formattedPageHeight.constData(),
2401 formattedPageWidth.constData(),
2402 formattedPageHeight.constData());
2403
2404 if (pdfVersion >= QPdfEngine::PdfVersion::PdfVersion_1_6)
2405 xprintf("/UserUnit %s\n", QByteArray::number(userUnit, 'f').constData());
2406
2407 xprintf(">>\n"
2408 "endobj\n");
2409
2410 addXrefEntry(resources);
2411 xprintf("<<\n"
2412 "/ColorSpace <<\n"
2413 "/PCSp %d 0 R\n"
2414 "/PCSpg %d 0 R\n"
2415 "/PCSpcmyk %d 0 R\n"
2416 "/CSp /DeviceRGB\n"
2417 "/CSpg /DeviceGray\n"
2418 "/CSpcmyk /DeviceCMYK\n"
2419 ">>\n"
2420 "/ExtGState <<\n"
2421 "/GSa %d 0 R\n",
2422 patternColorSpaceRGB,
2423 patternColorSpaceGrayscale,
2424 patternColorSpaceCMYK,
2425 graphicsState);
2426
2427 for (int i = 0; i < currentPage->graphicStates.size(); ++i)
2428 xprintf("/GState%d %d 0 R\n", currentPage->graphicStates.at(i), currentPage->graphicStates.at(i));
2429 xprintf(">>\n");
2430
2431 xprintf("/Pattern <<\n");
2432 for (int i = 0; i < currentPage->patterns.size(); ++i)
2433 xprintf("/Pat%d %d 0 R\n", currentPage->patterns.at(i), currentPage->patterns.at(i));
2434 xprintf(">>\n");
2435
2436 xprintf("/Font <<\n");
2437 for (int i = 0; i < currentPage->fonts.size();++i)
2438 xprintf("/F%d %d 0 R\n", currentPage->fonts[i], currentPage->fonts[i]);
2439 xprintf(">>\n");
2440
2441 xprintf("/XObject <<\n");
2442 for (int i = 0; i<currentPage->images.size(); ++i) {
2443 xprintf("/Im%d %d 0 R\n", currentPage->images.at(i), currentPage->images.at(i));
2444 }
2445 xprintf(">>\n");
2446
2447 xprintf(">>\n"
2448 "endobj\n");
2449
2450 addXrefEntry(annots);
2451 xprintf("[ ");
2452 for (int i = 0; i<currentPage->annotations.size(); ++i) {
2453 xprintf("%d 0 R ", currentPage->annotations.at(i));
2454 }
2455 xprintf("]\nendobj\n");
2456
2457 addXrefEntry(pageStream);
2458 xprintf("<<\n"
2459 "/Length %d 0 R\n", pageStreamLength); // object number for stream length object
2460 if (do_compress)
2461 xprintf("/Filter /FlateDecode\n");
2462
2463 xprintf(">>\n");
2464 xprintf("stream\n");
2465 QIODevice *content = currentPage->stream();
2466 int len = writeCompressed(content);
2467 xprintf("\nendstream\n"
2468 "endobj\n");
2469
2470 addXrefEntry(pageStreamLength);
2471 xprintf("%d\nendobj\n",len);
2472}
2473
2474void QPdfEnginePrivate::writeTail()
2475{
2476 writePage();
2477 writeFonts();
2478 writePageRoot();
2479 writeDestsRoot();
2480 writeAttachmentRoot();
2481 writeNamesRoot();
2482
2483 addXrefEntry(xrefPositions.size(),false);
2484 xprintf("xref\n"
2485 "0 %" PRIdQSIZETYPE "\n"
2486 "%010d 65535 f \n", xrefPositions.size()-1, xrefPositions[0]);
2487
2488 for (int i = 1; i < xrefPositions.size()-1; ++i)
2489 xprintf("%010d 00000 n \n", xrefPositions[i]);
2490
2491 {
2492 QByteArray trailer;
2493 QPdf::ByteStream s(&trailer);
2494
2495 s << "trailer\n"
2496 << "<<\n"
2497 << "/Size " << xrefPositions.size() - 1 << "\n"
2498 << "/Info " << info << "0 R\n"
2499 << "/Root " << catalog << "0 R\n";
2500
2501 const QByteArray id = documentId.toString(QUuid::WithoutBraces).toUtf8().toHex();
2502 s << "/ID [ <" << id << "> <" << id << "> ]\n";
2503
2504 s << ">>\n"
2505 << "startxref\n" << xrefPositions.constLast() << "\n"
2506 << "%%EOF\n";
2507
2508 write(trailer);
2509 }
2510}
2511
2512int QPdfEnginePrivate::addXrefEntry(int object, bool printostr)
2513{
2514 if (object < 0)
2515 object = requestObject();
2516
2517 if (object>=xrefPositions.size())
2518 xrefPositions.resize(object+1);
2519
2520 xrefPositions[object] = streampos;
2521 if (printostr)
2522 xprintf("%d 0 obj\n",object);
2523
2524 return object;
2525}
2526
2527void QPdfEnginePrivate::printString(QStringView string)
2528{
2529 if (string.isEmpty()) {
2530 write("()");
2531 return;
2532 }
2533
2534 // The 'text string' type in PDF is encoded either as PDFDocEncoding, or
2535 // Unicode UTF-16 with a Unicode byte order mark as the first character
2536 // (0xfeff), with the high-order byte first.
2537 QByteArray array("(\xfe\xff");
2538 const char16_t *utf16 = string.utf16();
2539
2540 for (qsizetype i = 0; i < string.size(); ++i) {
2541 char part[2] = {char((*(utf16 + i)) >> 8), char((*(utf16 + i)) & 0xff)};
2542 for(int j=0; j < 2; ++j) {
2543 if (part[j] == '(' || part[j] == ')' || part[j] == '\\')
2544 array.append('\\');
2545 array.append(part[j]);
2546 }
2547 }
2548 array.append(')');
2549 write(array);
2550}
2551
2552
2553void QPdfEnginePrivate::xprintf(const char* fmt, ...)
2554{
2555 if (!stream)
2556 return;
2557
2558 const int msize = 10000;
2559 char buf[msize];
2560
2561 va_list args;
2562 va_start(args, fmt);
2563 int bufsize = std::vsnprintf(buf, msize, fmt, args);
2564 va_end(args);
2565
2566 if (Q_LIKELY(bufsize < msize)) {
2567 stream->writeRawData(buf, bufsize);
2568 } else {
2569 // Fallback for abnormal cases
2570 QScopedArrayPointer<char> tmpbuf(new char[bufsize + 1]);
2571 va_start(args, fmt);
2572 bufsize = std::vsnprintf(tmpbuf.data(), bufsize + 1, fmt, args);
2573 va_end(args);
2574 stream->writeRawData(tmpbuf.data(), bufsize);
2575 }
2576 streampos += bufsize;
2577}
2578
2579int QPdfEnginePrivate::writeCompressed(QIODevice *dev)
2580{
2581#ifndef QT_NO_COMPRESS
2582 if (do_compress) {
2583 int size = QPdfPage::chunkSize();
2584 int sum = 0;
2585 ::z_stream zStruct;
2586 zStruct.zalloc = Z_NULL;
2587 zStruct.zfree = Z_NULL;
2588 zStruct.opaque = Z_NULL;
2589 if (::deflateInit(&zStruct, Z_DEFAULT_COMPRESSION) != Z_OK) {
2590 qWarning("QPdfStream::writeCompressed: Error in deflateInit()");
2591 return sum;
2592 }
2593 zStruct.avail_in = 0;
2594 QByteArray in, out;
2595 out.resize(size);
2596 while (!dev->atEnd() || zStruct.avail_in != 0) {
2597 if (zStruct.avail_in == 0) {
2598 in = dev->read(size);
2599 zStruct.avail_in = in.size();
2600 zStruct.next_in = reinterpret_cast<unsigned char*>(in.data());
2601 if (in.size() <= 0) {
2602 qWarning("QPdfStream::writeCompressed: Error in read()");
2603 ::deflateEnd(&zStruct);
2604 return sum;
2605 }
2606 }
2607 zStruct.next_out = reinterpret_cast<unsigned char*>(out.data());
2608 zStruct.avail_out = out.size();
2609 if (::deflate(&zStruct, 0) != Z_OK) {
2610 qWarning("QPdfStream::writeCompressed: Error in deflate()");
2611 ::deflateEnd(&zStruct);
2612 return sum;
2613 }
2614 int written = out.size() - zStruct.avail_out;
2615 stream->writeRawData(out.constData(), written);
2616 streampos += written;
2617 sum += written;
2618 }
2619 int ret;
2620 do {
2621 zStruct.next_out = reinterpret_cast<unsigned char*>(out.data());
2622 zStruct.avail_out = out.size();
2623 ret = ::deflate(&zStruct, Z_FINISH);
2624 if (ret != Z_OK && ret != Z_STREAM_END) {
2625 qWarning("QPdfStream::writeCompressed: Error in deflate()");
2626 ::deflateEnd(&zStruct);
2627 return sum;
2628 }
2629 int written = out.size() - zStruct.avail_out;
2630 stream->writeRawData(out.constData(), written);
2631 streampos += written;
2632 sum += written;
2633 } while (ret == Z_OK);
2634
2635 ::deflateEnd(&zStruct);
2636
2637 return sum;
2638 } else
2639#endif
2640 {
2641 QByteArray arr;
2642 int sum = 0;
2643 while (!dev->atEnd()) {
2644 arr = dev->read(QPdfPage::chunkSize());
2645 stream->writeRawData(arr.constData(), arr.size());
2646 streampos += arr.size();
2647 sum += arr.size();
2648 }
2649 return sum;
2650 }
2651}
2652
2653int QPdfEnginePrivate::writeCompressed(const char *src, int len)
2654{
2655#ifndef QT_NO_COMPRESS
2656 if (do_compress) {
2657 const QByteArray data = qCompress(reinterpret_cast<const uchar *>(src), len);
2658 constexpr qsizetype HeaderSize = 4;
2659 if (!data.isNull()) {
2660 stream->writeRawData(data.data() + HeaderSize, data.size() - HeaderSize);
2661 len = data.size() - HeaderSize;
2662 } else {
2663 qWarning("QPdfStream::writeCompressed: Error in compress()");
2664 len = 0;
2665 }
2666 } else
2667#endif
2668 {
2669 stream->writeRawData(src,len);
2670 }
2671 streampos += len;
2672 return len;
2673}
2674
2675int QPdfEnginePrivate::writeImage(const QByteArray &data, int width, int height, WriteImageOption option,
2676 int maskObject, int softMaskObject, bool dct, bool isMono)
2677{
2678 int image = addXrefEntry(-1);
2679 xprintf("<<\n"
2680 "/Type /XObject\n"
2681 "/Subtype /Image\n"
2682 "/Width %d\n"
2683 "/Height %d\n", width, height);
2684
2685 switch (option) {
2686 case WriteImageOption::Monochrome:
2687 if (!isMono) {
2688 xprintf("/ImageMask true\n"
2689 "/Decode [1 0]\n");
2690 } else {
2691 xprintf("/BitsPerComponent 1\n"
2692 "/ColorSpace /DeviceGray\n");
2693 }
2694 break;
2695 case WriteImageOption::Grayscale:
2696 xprintf("/BitsPerComponent 8\n"
2697 "/ColorSpace /DeviceGray\n");
2698 break;
2699 case WriteImageOption::RGB:
2700 xprintf("/BitsPerComponent 8\n"
2701 "/ColorSpace /DeviceRGB\n");
2702 break;
2703 case WriteImageOption::CMYK:
2704 xprintf("/BitsPerComponent 8\n"
2705 "/ColorSpace /DeviceCMYK\n");
2706 break;
2707 }
2708
2709 if (maskObject > 0)
2710 xprintf("/Mask %d 0 R\n", maskObject);
2711 if (softMaskObject > 0)
2712 xprintf("/SMask %d 0 R\n", softMaskObject);
2713
2714 int lenobj = requestObject();
2715 xprintf("/Length %d 0 R\n", lenobj);
2716 if (interpolateImages)
2717 xprintf("/Interpolate true\n");
2718 int len = 0;
2719 if (dct) {
2720 //qDebug("DCT");
2721 xprintf("/Filter /DCTDecode\n>>\nstream\n");
2722 write(data);
2723 len = data.size();
2724 } else {
2725 if (do_compress)
2726 xprintf("/Filter /FlateDecode\n>>\nstream\n");
2727 else
2728 xprintf(">>\nstream\n");
2729 len = writeCompressed(data);
2730 }
2731 xprintf("\nendstream\n"
2732 "endobj\n");
2733 addXrefEntry(lenobj);
2734 xprintf("%d\n"
2735 "endobj\n", len);
2736 return image;
2737}
2738
2746
2747void QPdfEnginePrivate::ShadingFunctionResult::writeColorSpace(QPdf::ByteStream *stream) const
2748{
2749 *stream << "/ColorSpace ";
2750 switch (colorModel) {
2751 case QPdfEngine::ColorModel::RGB:
2752 *stream << "/DeviceRGB\n"; break;
2753 case QPdfEngine::ColorModel::Grayscale:
2754 *stream << "/DeviceGray\n"; break;
2755 case QPdfEngine::ColorModel::CMYK:
2756 *stream << "/DeviceCMYK\n"; break;
2757 case QPdfEngine::ColorModel::Auto:
2758 Q_UNREACHABLE(); break;
2759 }
2760}
2761
2762QPdfEnginePrivate::ShadingFunctionResult
2763QPdfEnginePrivate::createShadingFunction(const QGradient *gradient, int from, int to, bool reflect, bool alpha)
2764{
2765 QGradientStops stops = gradient->stops();
2766 if (stops.isEmpty()) {
2767 stops << QGradientStop(0, Qt::black);
2768 stops << QGradientStop(1, Qt::white);
2769 }
2770 if (stops.at(0).first > 0)
2771 stops.prepend(QGradientStop(0, stops.at(0).second));
2772 if (stops.at(stops.size() - 1).first < 1)
2773 stops.append(QGradientStop(1, stops.at(stops.size() - 1).second));
2774
2775 // Color to use which colorspace to use
2776 const QColor referenceColor = stops.constFirst().second;
2777
2778 switch (colorModel) {
2779 case QPdfEngine::ColorModel::RGB:
2780 case QPdfEngine::ColorModel::Grayscale:
2781 case QPdfEngine::ColorModel::CMYK:
2782 break;
2783 case QPdfEngine::ColorModel::Auto: {
2784 // Make sure that all the stops have the same color spec
2785 // (we don't support anything else)
2786 const QColor::Spec referenceSpec = referenceColor.spec();
2787 bool warned = false;
2788 for (QGradientStop &stop : stops) {
2789 if (stop.second.spec() != referenceSpec) {
2790 if (!warned) {
2791 qWarning("QPdfEngine: unable to create a gradient between colors of different spec");
2792 warned = true;
2793 }
2794 stop.second = stop.second.convertTo(referenceSpec);
2795 }
2796 }
2797 break;
2798 }
2799 }
2800
2801 ShadingFunctionResult result;
2802 result.colorModel = colorModelForColor(referenceColor);
2803
2804 QList<int> functions;
2805 const int numStops = stops.size();
2806 functions.reserve(numStops - 1);
2807 for (int i = 0; i < numStops - 1; ++i) {
2808 int f = addXrefEntry(-1);
2809 QByteArray data;
2810 QPdf::ByteStream s(&data);
2811 s << "<<\n"
2812 "/FunctionType 2\n"
2813 "/Domain [0 1]\n"
2814 "/N 1\n";
2815 if (alpha) {
2816 s << "/C0 [" << stops.at(i).second.alphaF() << "]\n"
2817 "/C1 [" << stops.at(i + 1).second.alphaF() << "]\n";
2818 } else {
2819 switch (result.colorModel) {
2820 case QPdfEngine::ColorModel::RGB:
2821 s << "/C0 [" << stops.at(i).second.redF() << stops.at(i).second.greenF() << stops.at(i).second.blueF() << "]\n"
2822 "/C1 [" << stops.at(i + 1).second.redF() << stops.at(i + 1).second.greenF() << stops.at(i + 1).second.blueF() << "]\n";
2823 break;
2824 case QPdfEngine::ColorModel::Grayscale: {
2825 constexpr qreal normalisationFactor = 1. / 255.;
2826 s << "/C0 [" << (qGray(stops.at(i).second.rgba()) * normalisationFactor) << "]\n"
2827 "/C1 [" << (qGray(stops.at(i + 1).second.rgba()) * normalisationFactor) << "]\n";
2828 break;
2829 }
2830 case QPdfEngine::ColorModel::CMYK:
2831 s << "/C0 [" << stops.at(i).second.cyanF()
2832 << stops.at(i).second.magentaF()
2833 << stops.at(i).second.yellowF()
2834 << stops.at(i).second.blackF() << "]\n"
2835 "/C1 [" << stops.at(i + 1).second.cyanF()
2836 << stops.at(i + 1).second.magentaF()
2837 << stops.at(i + 1).second.yellowF()
2838 << stops.at(i + 1).second.blackF() << "]\n";
2839 break;
2840
2841 case QPdfEngine::ColorModel::Auto:
2842 Q_UNREACHABLE();
2843 break;
2844 }
2845
2846 }
2847 s << ">>\n"
2848 "endobj\n";
2849 write(data);
2850 functions << f;
2851 }
2852
2853 QList<QGradientBound> gradientBounds;
2854 gradientBounds.reserve((to - from) * (numStops - 1));
2855
2856 for (int step = from; step < to; ++step) {
2857 if (reflect && step % 2) {
2858 for (int i = numStops - 1; i > 0; --i) {
2859 QGradientBound b;
2860 b.start = step + 1 - qBound(qreal(0.), stops.at(i).first, qreal(1.));
2861 b.stop = step + 1 - qBound(qreal(0.), stops.at(i - 1).first, qreal(1.));
2862 b.function = functions.at(i - 1);
2863 b.reverse = true;
2864 gradientBounds << b;
2865 }
2866 } else {
2867 for (int i = 0; i < numStops - 1; ++i) {
2868 QGradientBound b;
2869 b.start = step + qBound(qreal(0.), stops.at(i).first, qreal(1.));
2870 b.stop = step + qBound(qreal(0.), stops.at(i + 1).first, qreal(1.));
2871 b.function = functions.at(i);
2872 b.reverse = false;
2873 gradientBounds << b;
2874 }
2875 }
2876 }
2877
2878 // normalize bounds to [0..1]
2879 qreal bstart = gradientBounds.at(0).start;
2880 qreal bend = gradientBounds.at(gradientBounds.size() - 1).stop;
2881 qreal norm = 1./(bend - bstart);
2882 for (int i = 0; i < gradientBounds.size(); ++i) {
2883 gradientBounds[i].start = (gradientBounds[i].start - bstart)*norm;
2884 gradientBounds[i].stop = (gradientBounds[i].stop - bstart)*norm;
2885 }
2886
2887 int function;
2888 if (gradientBounds.size() > 1) {
2889 function = addXrefEntry(-1);
2890 QByteArray data;
2891 QPdf::ByteStream s(&data);
2892 s << "<<\n"
2893 "/FunctionType 3\n"
2894 "/Domain [0 1]\n"
2895 "/Bounds [";
2896 for (int i = 1; i < gradientBounds.size(); ++i)
2897 s << gradientBounds.at(i).start;
2898 s << "]\n"
2899 "/Encode [";
2900 for (int i = 0; i < gradientBounds.size(); ++i)
2901 s << (gradientBounds.at(i).reverse ? "1 0 " : "0 1 ");
2902 s << "]\n"
2903 "/Functions [";
2904 for (int i = 0; i < gradientBounds.size(); ++i)
2905 s << gradientBounds.at(i).function << "0 R ";
2906 s << "]\n"
2907 ">>\n"
2908 "endobj\n";
2909 write(data);
2910 } else {
2911 function = functions.at(0);
2912 }
2913 result.function = function;
2914 return result;
2915}
2916
2917int QPdfEnginePrivate::generateLinearGradientShader(const QLinearGradient *gradient, const QTransform &matrix, bool alpha)
2918{
2919 QPointF start = gradient->start();
2920 QPointF stop = gradient->finalStop();
2921 QPointF offset = stop - start;
2922 Q_ASSERT(gradient->coordinateMode() == QGradient::LogicalMode);
2923
2924 int from = 0;
2925 int to = 1;
2926 bool reflect = false;
2927 switch (gradient->spread()) {
2928 case QGradient::PadSpread:
2929 break;
2930 case QGradient::ReflectSpread:
2931 reflect = true;
2932 Q_FALLTHROUGH();
2933 case QGradient::RepeatSpread: {
2934 // calculate required bounds
2935 QRectF pageRect = m_pageLayout.fullRectPixels(resolution);
2936 QTransform inv = matrix.inverted();
2937 QPointF page_rect[4] = { inv.map(pageRect.topLeft()),
2938 inv.map(pageRect.topRight()),
2939 inv.map(pageRect.bottomLeft()),
2940 inv.map(pageRect.bottomRight()) };
2941
2942 qreal length = offset.x()*offset.x() + offset.y()*offset.y();
2943
2944 // find the max and min values in offset and orth direction that are needed to cover
2945 // the whole page
2946 from = INT_MAX;
2947 to = INT_MIN;
2948 for (int i = 0; i < 4; ++i) {
2949 qreal off = ((page_rect[i].x() - start.x()) * offset.x() + (page_rect[i].y() - start.y()) * offset.y())/length;
2950 from = qMin(from, qFloor(off));
2951 to = qMax(to, qCeil(off));
2952 }
2953
2954 stop = start + to * offset;
2955 start = start + from * offset;
2956 break;
2957 }
2958 }
2959
2960 const auto shadingFunctionResult = createShadingFunction(gradient, from, to, reflect, alpha);
2961
2962 QByteArray shader;
2963 QPdf::ByteStream s(&shader);
2964 s << "<<\n"
2965 "/ShadingType 2\n";
2966
2967 if (alpha)
2968 s << "/ColorSpace /DeviceGray\n";
2969 else
2970 shadingFunctionResult.writeColorSpace(&s);
2971
2972 s << "/AntiAlias true\n"
2973 "/Coords [" << start.x() << start.y() << stop.x() << stop.y() << "]\n"
2974 "/Extend [true true]\n"
2975 "/Function " << shadingFunctionResult.function << "0 R\n"
2976 ">>\n"
2977 "endobj\n";
2978 int shaderObject = addXrefEntry(-1);
2979 write(shader);
2980 return shaderObject;
2981}
2982
2983int QPdfEnginePrivate::generateRadialGradientShader(const QRadialGradient *gradient, const QTransform &matrix, bool alpha)
2984{
2985 QPointF p1 = gradient->center();
2986 qreal r1 = gradient->centerRadius();
2987 QPointF p0 = gradient->focalPoint();
2988 qreal r0 = gradient->focalRadius();
2989
2990 Q_ASSERT(gradient->coordinateMode() == QGradient::LogicalMode);
2991
2992 int from = 0;
2993 int to = 1;
2994 bool reflect = false;
2995 switch (gradient->spread()) {
2996 case QGradient::PadSpread:
2997 break;
2998 case QGradient::ReflectSpread:
2999 reflect = true;
3000 Q_FALLTHROUGH();
3001 case QGradient::RepeatSpread: {
3002 Q_ASSERT(qFuzzyIsNull(r0)); // QPainter emulates if this is not 0
3003
3004 QRectF pageRect = m_pageLayout.fullRectPixels(resolution);
3005 QTransform inv = matrix.inverted();
3006 QPointF page_rect[4] = { inv.map(pageRect.topLeft()),
3007 inv.map(pageRect.topRight()),
3008 inv.map(pageRect.bottomLeft()),
3009 inv.map(pageRect.bottomRight()) };
3010
3011 // increase to until the whole page fits into it
3012 bool done = false;
3013 while (!done) {
3014 QPointF center = QPointF(p0.x() + to*(p1.x() - p0.x()), p0.y() + to*(p1.y() - p0.y()));
3015 double radius = r0 + to*(r1 - r0);
3016 double r2 = radius*radius;
3017 done = true;
3018 for (int i = 0; i < 4; ++i) {
3019 QPointF off = page_rect[i] - center;
3020 if (off.x()*off.x() + off.y()*off.y() > r2) {
3021 ++to;
3022 done = false;
3023 break;
3024 }
3025 }
3026 }
3027 p1 = QPointF(p0.x() + to*(p1.x() - p0.x()), p0.y() + to*(p1.y() - p0.y()));
3028 r1 = r0 + to*(r1 - r0);
3029 break;
3030 }
3031 }
3032
3033 const auto shadingFunctionResult = createShadingFunction(gradient, from, to, reflect, alpha);
3034
3035 QByteArray shader;
3036 QPdf::ByteStream s(&shader);
3037 s << "<<\n"
3038 "/ShadingType 3\n";
3039
3040 if (alpha)
3041 s << "/ColorSpace /DeviceGray\n";
3042 else
3043 shadingFunctionResult.writeColorSpace(&s);
3044
3045 s << "/AntiAlias true\n"
3046 "/Domain [0 1]\n"
3047 "/Coords [" << p0.x() << p0.y() << r0 << p1.x() << p1.y() << r1 << "]\n"
3048 "/Extend [true true]\n"
3049 "/Function " << shadingFunctionResult.function << "0 R\n"
3050 ">>\n"
3051 "endobj\n";
3052 int shaderObject = addXrefEntry(-1);
3053 write(shader);
3054 return shaderObject;
3055}
3056
3057int QPdfEnginePrivate::generateGradientShader(const QGradient *gradient, const QTransform &matrix, bool alpha)
3058{
3059 switch (gradient->type()) {
3060 case QGradient::LinearGradient:
3061 return generateLinearGradientShader(static_cast<const QLinearGradient *>(gradient), matrix, alpha);
3062 case QGradient::RadialGradient:
3063 return generateRadialGradientShader(static_cast<const QRadialGradient *>(gradient), matrix, alpha);
3064 case QGradient::ConicalGradient:
3065 Q_UNIMPLEMENTED(); // ### Implement me!
3066 break;
3067 case QGradient::NoGradient:
3068 break;
3069 }
3070 return 0;
3071}
3072
3073int QPdfEnginePrivate::gradientBrush(const QBrush &b, const QTransform &matrix, int *gStateObject)
3074{
3075 const QGradient *gradient = b.gradient();
3076
3077 if (!gradient || gradient->coordinateMode() != QGradient::LogicalMode)
3078 return 0;
3079
3080 QRectF pageRect = m_pageLayout.fullRectPixels(resolution);
3081
3082 QTransform m = b.transform() * matrix;
3083 int shaderObject = generateGradientShader(gradient, m);
3084
3085 QByteArray str;
3086 QPdf::ByteStream s(&str);
3087 s << "<<\n"
3088 "/Type /Pattern\n"
3089 "/PatternType 2\n"
3090 "/Shading " << shaderObject << "0 R\n"
3091 "/Matrix ["
3092 << m.m11()
3093 << m.m12()
3094 << m.m21()
3095 << m.m22()
3096 << m.dx()
3097 << m.dy() << "]\n";
3098 s << ">>\n"
3099 "endobj\n";
3100
3101 int patternObj = addXrefEntry(-1);
3102 write(str);
3103 currentPage->patterns.append(patternObj);
3104
3105 if (!b.isOpaque()) {
3106 bool ca = true;
3107 QGradientStops stops = gradient->stops();
3108 int a = stops.at(0).second.alpha();
3109 for (int i = 1; i < stops.size(); ++i) {
3110 if (stops.at(i).second.alpha() != a) {
3111 ca = false;
3112 break;
3113 }
3114 }
3115 if (ca) {
3116 *gStateObject = addConstantAlphaObject(stops.at(0).second.alpha());
3117 } else {
3118 int alphaShaderObject = generateGradientShader(gradient, m, true);
3119
3120 QByteArray content;
3121 QPdf::ByteStream c(&content);
3122 c << "/Shader" << alphaShaderObject << "sh\n";
3123
3124 QByteArray form;
3125 QPdf::ByteStream f(&form);
3126 f << "<<\n"
3127 "/Type /XObject\n"
3128 "/Subtype /Form\n"
3129 "/BBox [0 0 " << pageRect.width() << pageRect.height() << "]\n"
3130 "/Group <</S /Transparency >>\n"
3131 "/Resources <<\n"
3132 "/Shading << /Shader" << alphaShaderObject << alphaShaderObject << "0 R >>\n"
3133 ">>\n";
3134
3135 f << "/Length " << content.size() << "\n"
3136 ">>\n"
3137 "stream\n"
3138 << content
3139 << "\nendstream\n"
3140 "endobj\n";
3141
3142 int softMaskFormObject = addXrefEntry(-1);
3143 write(form);
3144 *gStateObject = addXrefEntry(-1);
3145 xprintf("<< /SMask << /S /Alpha /G %d 0 R >> >>\n"
3146 "endobj\n", softMaskFormObject);
3147 currentPage->graphicStates.append(*gStateObject);
3148 }
3149 }
3150
3151 return patternObj;
3152}
3153
3154int QPdfEnginePrivate::addConstantAlphaObject(int brushAlpha, int penAlpha)
3155{
3156 if (brushAlpha == 255 && penAlpha == 255)
3157 return 0;
3158 uint object = alphaCache.value(std::pair<uint, uint>(brushAlpha, penAlpha), 0);
3159 if (!object) {
3160 object = addXrefEntry(-1);
3161 QByteArray alphaDef;
3162 QPdf::ByteStream s(&alphaDef);
3163 s << "<<\n/ca " << (brushAlpha/qreal(255.)) << '\n';
3164 s << "/CA " << (penAlpha/qreal(255.)) << "\n>>";
3165 xprintf("%s\nendobj\n", alphaDef.constData());
3166 alphaCache.insert(std::pair<uint, uint>(brushAlpha, penAlpha), object);
3167 }
3168 if (currentPage->graphicStates.indexOf(object) < 0)
3169 currentPage->graphicStates.append(object);
3170
3171 return object;
3172}
3173
3174
3175int QPdfEnginePrivate::addBrushPattern(const QTransform &m, bool *specifyColor, int *gStateObject)
3176{
3177 Q_Q(QPdfEngine);
3178
3179 int paintType = 2; // Uncolored tiling
3180 int w = 8;
3181 int h = 8;
3182
3183 *specifyColor = true;
3184 *gStateObject = 0;
3185
3186 const Qt::BrushStyle style = brush.style();
3187 const bool isCosmetic = style >= Qt::Dense1Pattern && style <= Qt::DiagCrossPattern
3188 && !q->painter()->testRenderHint(QPainter::NonCosmeticBrushPatterns);
3189 QTransform matrix;
3190 if (!isCosmetic)
3191 matrix = m;
3192 matrix.translate(brushOrigin.x(), brushOrigin.y());
3193 matrix = matrix * pageMatrix();
3194
3195 if (style == Qt::LinearGradientPattern || style == Qt::RadialGradientPattern) {// && style <= Qt::ConicalGradientPattern) {
3196 *specifyColor = false;
3197 return gradientBrush(brush, matrix, gStateObject);
3198 }
3199
3200 if (!isCosmetic)
3201 matrix = brush.transform() * matrix;
3202
3203 if ((!brush.isOpaque() && brush.style() < Qt::LinearGradientPattern) || opacity != 1.0)
3204 *gStateObject = addConstantAlphaObject(qRound(brush.color().alpha() * opacity),
3205 qRound(pen.color().alpha() * opacity));
3206
3207 int imageObject = -1;
3208 QByteArray pattern = QPdf::patternForBrush(brush);
3209 if (pattern.isEmpty()) {
3210 if (brush.style() != Qt::TexturePattern)
3211 return 0;
3212 QImage image = brush.textureImage();
3213 bool bitmap = true;
3214 const bool lossless = q->painter()->testRenderHint(QPainter::LosslessImageRendering);
3215 imageObject = addImage(image, &bitmap, lossless, image.cacheKey());
3216 if (imageObject != -1) {
3217 QImage::Format f = image.format();
3218 if (f != QImage::Format_MonoLSB && f != QImage::Format_Mono) {
3219 paintType = 1; // Colored tiling
3220 *specifyColor = false;
3221 }
3222 w = image.width();
3223 h = image.height();
3224 QTransform m(w, 0, 0, -h, 0, h);
3225 QPdf::ByteStream s(&pattern);
3226 s << QPdf::generateMatrix(m);
3227 s << "/Im" << imageObject << " Do\n";
3228 }
3229 }
3230
3231 QByteArray str;
3232 QPdf::ByteStream s(&str);
3233 s << "<<\n"
3234 "/Type /Pattern\n"
3235 "/PatternType 1\n"
3236 "/PaintType " << paintType << "\n"
3237 "/TilingType 1\n"
3238 "/BBox [0 0 " << w << h << "]\n"
3239 "/XStep " << w << "\n"
3240 "/YStep " << h << "\n"
3241 "/Matrix ["
3242 << matrix.m11()
3243 << matrix.m12()
3244 << matrix.m21()
3245 << matrix.m22()
3246 << matrix.dx()
3247 << matrix.dy() << "]\n"
3248 "/Resources \n<< "; // open resource tree
3249 if (imageObject > 0) {
3250 s << "/XObject << /Im" << imageObject << ' ' << imageObject << "0 R >> ";
3251 }
3252 s << ">>\n"
3253 "/Length " << pattern.size() << "\n"
3254 ">>\n"
3255 "stream\n"
3256 << pattern
3257 << "\nendstream\n"
3258 "endobj\n";
3259
3260 int patternObj = addXrefEntry(-1);
3261 write(str);
3262 currentPage->patterns.append(patternObj);
3263 return patternObj;
3264}
3265
3266static inline bool is_monochrome(const QList<QRgb> &colorTable)
3267{
3268 return colorTable.size() == 2
3269 && colorTable.at(0) == QColor(Qt::black).rgba()
3270 && colorTable.at(1) == QColor(Qt::white).rgba()
3271 ;
3272}
3273
3274/*!
3275 * \internal
3276 * Adds an image to the pdf and return the pdf-object id. Returns -1 if adding the image failed.
3277 */
3278int QPdfEnginePrivate::addImage(const QImage &img, bool *bitmap, bool lossless, qint64 serial_no)
3279{
3280 if (img.isNull())
3281 return -1;
3282
3283 int object = imageCache.value(serial_no);
3284 if (object)
3285 return object;
3286
3287 QImage image = img;
3288 QImage::Format format = image.format();
3289 const bool grayscale = (colorModel == QPdfEngine::ColorModel::Grayscale);
3290
3291 if (pdfVersion == QPdfEngine::PdfVersion::PdfVersion_A1b) {
3292 if (image.hasAlphaChannel()) {
3293 // transparent images are not allowed in PDF/A-1b, so we convert it to
3294 // a format without alpha channel first
3295
3296 QImage alphaLessImage(image.width(), image.height(), QImage::Format_RGB32);
3297 alphaLessImage.setDevicePixelRatio(image.devicePixelRatioF());
3298 alphaLessImage.fill(Qt::white);
3299
3300 QPainter p(&alphaLessImage);
3301 p.drawImage(0, 0, image);
3302
3303 image = alphaLessImage;
3304 format = image.format();
3305 }
3306 }
3307
3308 if (image.depth() == 1 && *bitmap && is_monochrome(img.colorTable())) {
3309 if (format == QImage::Format_MonoLSB)
3310 image = image.convertToFormat(QImage::Format_Mono);
3311 format = QImage::Format_Mono;
3312 } else {
3313 *bitmap = false;
3314 if (format != QImage::Format_RGB32 && format != QImage::Format_ARGB32 && format != QImage::Format_CMYK8888) {
3315 image = image.convertToFormat(QImage::Format_ARGB32);
3316 format = QImage::Format_ARGB32;
3317 }
3318 }
3319
3320 int w = image.width();
3321 int h = image.height();
3322
3323 if (format == QImage::Format_Mono) {
3324 int bytesPerLine = (w + 7) >> 3;
3325 QByteArray data;
3326 data.resize(bytesPerLine * h);
3327 char *rawdata = data.data();
3328 for (int y = 0; y < h; ++y) {
3329 memcpy(rawdata, image.constScanLine(y), bytesPerLine);
3330 rawdata += bytesPerLine;
3331 }
3332 object = writeImage(data, w, h, WriteImageOption::Monochrome, 0, 0, false, is_monochrome(img.colorTable()));
3333 } else {
3334 QByteArray softMaskData;
3335 bool dct = false;
3336 QByteArray imageData;
3337 bool hasAlpha = false;
3338 bool hasMask = false;
3339
3340 if (QImageWriter::supportedImageFormats().contains("jpeg") && !grayscale && !lossless) {
3341 QBuffer buffer(&imageData);
3342 QImageWriter writer(&buffer, "jpeg");
3343 writer.setQuality(94);
3344 if (format == QImage::Format_CMYK8888) {
3345 // PDFs require CMYK colors not to be inverted in the JPEG encoding
3346 writer.setSubType("CMYK");
3347 }
3348 writer.write(image);
3349 dct = true;
3350
3351 if (format != QImage::Format_RGB32 && format != QImage::Format_CMYK8888) {
3352 softMaskData.resize(w * h);
3353 uchar *sdata = (uchar *)softMaskData.data();
3354 for (int y = 0; y < h; ++y) {
3355 const QRgb *rgb = (const QRgb *)image.constScanLine(y);
3356 for (int x = 0; x < w; ++x) {
3357 uchar alpha = qAlpha(*rgb);
3358 *sdata++ = alpha;
3359 hasMask |= (alpha < 255);
3360 hasAlpha |= (alpha != 0 && alpha != 255);
3361 ++rgb;
3362 }
3363 }
3364 }
3365 } else {
3366 if (format == QImage::Format_CMYK8888) {
3367 imageData.resize(grayscale ? w * h : w * h * 4);
3368 uchar *data = (uchar *)imageData.data();
3369 const qsizetype bytesPerLine = image.bytesPerLine();
3370 if (grayscale) {
3371 for (int y = 0; y < h; ++y) {
3372 const uint *cmyk = (const uint *)image.constScanLine(y);
3373 for (int x = 0; x < w; ++x)
3374 *data++ = qGray(QCmyk32::fromCmyk32(*cmyk++).toColor().rgba());
3375 }
3376 } else {
3377 for (int y = 0; y < h; ++y) {
3378 uchar *start = data + y * w * 4;
3379 memcpy(start, image.constScanLine(y), bytesPerLine);
3380 }
3381 }
3382 } else {
3383 imageData.resize(grayscale ? w * h : 3 * w * h);
3384 uchar *data = (uchar *)imageData.data();
3385 softMaskData.resize(w * h);
3386 uchar *sdata = (uchar *)softMaskData.data();
3387 for (int y = 0; y < h; ++y) {
3388 const QRgb *rgb = (const QRgb *)image.constScanLine(y);
3389 if (grayscale) {
3390 for (int x = 0; x < w; ++x) {
3391 *(data++) = qGray(*rgb);
3392 uchar alpha = qAlpha(*rgb);
3393 *sdata++ = alpha;
3394 hasMask |= (alpha < 255);
3395 hasAlpha |= (alpha != 0 && alpha != 255);
3396 ++rgb;
3397 }
3398 } else {
3399 for (int x = 0; x < w; ++x) {
3400 *(data++) = qRed(*rgb);
3401 *(data++) = qGreen(*rgb);
3402 *(data++) = qBlue(*rgb);
3403 uchar alpha = qAlpha(*rgb);
3404 *sdata++ = alpha;
3405 hasMask |= (alpha < 255);
3406 hasAlpha |= (alpha != 0 && alpha != 255);
3407 ++rgb;
3408 }
3409 }
3410 }
3411 }
3412 if (format == QImage::Format_RGB32 || format == QImage::Format_CMYK8888)
3413 hasAlpha = hasMask = false;
3414 }
3415 int maskObject = 0;
3416 int softMaskObject = 0;
3417 if (hasAlpha) {
3418 softMaskObject = writeImage(softMaskData, w, h, WriteImageOption::Grayscale, 0, 0);
3419 } else if (hasMask) {
3420 // dither the soft mask to 1bit and add it. This also helps PDF viewers
3421 // without transparency support
3422 int bytesPerLine = (w + 7) >> 3;
3423 QByteArray mask(bytesPerLine * h, 0);
3424 uchar *mdata = (uchar *)mask.data();
3425 const uchar *sdata = (const uchar *)softMaskData.constData();
3426 for (int y = 0; y < h; ++y) {
3427 for (int x = 0; x < w; ++x) {
3428 if (*sdata)
3429 mdata[x>>3] |= (0x80 >> (x&7));
3430 ++sdata;
3431 }
3432 mdata += bytesPerLine;
3433 }
3434 maskObject = writeImage(mask, w, h, WriteImageOption::Monochrome, 0, 0);
3435 }
3436
3437 const WriteImageOption option = [&]() {
3438 if (grayscale)
3439 return WriteImageOption::Grayscale;
3440 if (format == QImage::Format_CMYK8888)
3441 return WriteImageOption::CMYK;
3442 return WriteImageOption::RGB;
3443 }();
3444
3445 object = writeImage(imageData, w, h, option,
3446 maskObject, softMaskObject, dct);
3447 }
3448 imageCache.insert(serial_no, object);
3449 return object;
3450}
3451
3452void QPdfEnginePrivate::drawTextItem(const QPointF &p, const QTextItemInt &ti)
3453{
3454 Q_Q(QPdfEngine);
3455
3456 const bool isLink = ti.charFormat.hasProperty(QTextFormat::AnchorHref);
3457 const bool isAnchor = ti.charFormat.hasProperty(QTextFormat::AnchorName);
3458 // PDF/X-4 (ยง 6.17) does not allow annotations that don't lie
3459 // outside the BleedBox/TrimBox, so don't emit an hyperlink
3460 // annotation at all.
3461 const bool isX4 = pdfVersion == QPdfEngine::PdfVersion::PdfVersion_X4;
3462 if ((isLink && !isX4) || isAnchor) {
3463 qreal size = ti.fontEngine->fontDef.pixelSize;
3464 int synthesized = ti.fontEngine->synthesized();
3465 qreal stretch = synthesized & QFontEngine::SynthesizedStretch ? ti.fontEngine->fontDef.stretch/100. : 1.;
3466 Q_ASSERT(stretch > qreal(0));
3467
3468 QTransform trans;
3469 // Build text rendering matrix (Trm). We need it to map the text area to user
3470 // space units on the PDF page.
3471 trans = QTransform(size*stretch, 0, 0, size, 0, 0);
3472 // Apply text matrix (Tm).
3473 trans *= QTransform(1,0,0,-1,p.x(),p.y());
3474 // Apply page displacement (Identity for first page).
3475 trans *= stroker.matrix;
3476 // Apply Current Transformation Matrix (CTM)
3477 trans *= pageMatrix();
3478 qreal x1, y1, x2, y2;
3479 trans.map(0, 0, &x1, &y1);
3480 trans.map(ti.width.toReal()/size, (ti.ascent.toReal()-ti.descent.toReal())/size, &x2, &y2);
3481
3482 if (isLink) {
3483 uint annot = addXrefEntry(-1);
3484 QByteArray x1s, y1s, x2s, y2s;
3485 x1s.setNum(static_cast<double>(x1), 'f');
3486 y1s.setNum(static_cast<double>(y1), 'f');
3487 x2s.setNum(static_cast<double>(x2), 'f');
3488 y2s.setNum(static_cast<double>(y2), 'f');
3489 QByteArray rectData = x1s + ' ' + y1s + ' ' + x2s + ' ' + y2s;
3490 xprintf("<<\n/Type /Annot\n/Subtype /Link\n");
3491
3492 if (pdfVersion == QPdfEngine::PdfVersion::PdfVersion_A1b)
3493 xprintf("/F 4\n"); // enable print flag, disable all other
3494
3495 xprintf("/Rect [");
3496 write(rectData.constData());
3497#ifdef Q_DEBUG_PDF_LINKS
3498 xprintf("]\n/Border [16 16 1]\n");
3499#else
3500 xprintf("]\n/Border [0 0 0]\n");
3501#endif
3502 const QString link = ti.charFormat.anchorHref();
3503 const bool isInternal = link.startsWith(QLatin1Char('#'));
3504 if (!isInternal) {
3505 xprintf("/A <<\n");
3506 xprintf("/Type /Action\n/S /URI\n/URI (%s)\n", link.toLatin1().constData());
3507 xprintf(">>\n");
3508 } else {
3509 xprintf("/Dest ");
3510 printString(link.sliced(1));
3511 xprintf("\n");
3512 }
3513 xprintf(">>\n");
3514 xprintf("endobj\n");
3515
3516 if (!currentPage->annotations.contains(annot)) {
3517 currentPage->annotations.append(annot);
3518 }
3519 } else {
3520 const QString anchor = ti.charFormat.anchorNames().constFirst();
3521 const uint curPage = pages.last();
3522 destCache.append(DestInfo({ anchor, curPage, QPointF(x1, y2) }));
3523 }
3524 }
3525
3526 QFontEngine *fe = ti.fontEngine;
3527
3528 QFontEngine::FaceId face_id = fe->faceId();
3529 bool noEmbed = false;
3530 if (!embedFonts
3531 || face_id.filename.isEmpty()
3532 || fe->fsType & 0x200 /* bitmap embedding only */
3533 || fe->fsType == 2 /* no embedding allowed */
3534 || fe->isColorFont()) {
3535 *currentPage << "Q\n";
3536 q->QPaintEngine::drawTextItem(p, ti);
3537 *currentPage << "q\n";
3538 // The font system treats all color fonts as bitmap fonts, so
3539 // QFontSubset cannot embed a usable outline subset for them; the
3540 // glyphs have already been drawn as images above.
3541 if (face_id.filename.isEmpty() || fe->isColorFont())
3542 return;
3543 noEmbed = true;
3544 }
3545
3546 QFontSubset *font = fonts.value(face_id, nullptr);
3547 if (!font) {
3548 font = new QFontSubset(fe, requestObject());
3549 font->noEmbed = noEmbed;
3550 }
3551 fonts.insert(face_id, font);
3552
3553 if (!currentPage->fonts.contains(font->object_id))
3554 currentPage->fonts.append(font->object_id);
3555
3556 qreal size = ti.fontEngine->fontDef.pixelSize;
3557
3558 QVarLengthArray<glyph_t> glyphs;
3559 QVarLengthArray<QFixedPoint> positions;
3560 QTransform m = QTransform::fromTranslate(p.x(), p.y());
3561 ti.fontEngine->getGlyphPositions(ti.glyphs, m, ti.flags,
3562 glyphs, positions);
3563 if (glyphs.size() == 0)
3564 return;
3565 int synthesized = ti.fontEngine->synthesized();
3566 qreal stretch = synthesized & QFontEngine::SynthesizedStretch ? ti.fontEngine->fontDef.stretch/100. : 1.;
3567 Q_ASSERT(stretch > qreal(0));
3568
3569 *currentPage << "BT\n"
3570 << "/F" << font->object_id << size << "Tf "
3571 << stretch << (synthesized & QFontEngine::SynthesizedItalic
3572 ? "0 .3 -1 0 0 Tm\n"
3573 : "0 0 -1 0 0 Tm\n");
3574
3575
3576#if 0
3577 // #### implement actual text for complex languages
3578 const unsigned short *logClusters = ti.logClusters;
3579 int pos = 0;
3580 do {
3581 int end = pos + 1;
3582 while (end < ti.num_chars && logClusters[end] == logClusters[pos])
3583 ++end;
3584 *currentPage << "/Span << /ActualText <FEFF";
3585 for (int i = pos; i < end; ++i) {
3586 s << toHex((ushort)ti.chars[i].unicode(), buf);
3587 }
3588 *currentPage << "> >>\n"
3589 "BDC\n"
3590 "<";
3591 int ge = end == ti.num_chars ? ti.num_glyphs : logClusters[end];
3592 for (int gs = logClusters[pos]; gs < ge; ++gs)
3593 *currentPage << toHex((ushort)ti.glyphs[gs].glyph, buf);
3594 *currentPage << "> Tj\n"
3595 "EMC\n";
3596 pos = end;
3597 } while (pos < ti.num_chars);
3598#else
3599 qreal last_x = 0.;
3600 qreal last_y = 0.;
3601 for (int i = 0; i < glyphs.size(); ++i) {
3602 qreal x = positions[i].x.toReal();
3603 qreal y = positions[i].y.toReal();
3604 if (synthesized & QFontEngine::SynthesizedItalic)
3605 x += .3*y;
3606 x /= stretch;
3607 char buf[5];
3608 qsizetype g = font->addGlyph(glyphs[i]);
3609 *currentPage << x - last_x << last_y - y << "Td <"
3610 << QPdf::toHex((ushort)g, buf) << "> Tj\n";
3611 last_x = x;
3612 last_y = y;
3613 }
3614 if (synthesized & QFontEngine::SynthesizedBold) {
3615 *currentPage << stretch << (synthesized & QFontEngine::SynthesizedItalic
3616 ? "0 .3 -1 0 0 Tm\n"
3617 : "0 0 -1 0 0 Tm\n");
3618 *currentPage << "/Span << /ActualText <> >> BDC\n";
3619 last_x = 0.5*fe->lineThickness().toReal();
3620 last_y = 0.;
3621 for (int i = 0; i < glyphs.size(); ++i) {
3622 qreal x = positions[i].x.toReal();
3623 qreal y = positions[i].y.toReal();
3624 if (synthesized & QFontEngine::SynthesizedItalic)
3625 x += .3*y;
3626 x /= stretch;
3627 char buf[5];
3628 qsizetype g = font->addGlyph(glyphs[i]);
3629 *currentPage << x - last_x << last_y - y << "Td <"
3630 << QPdf::toHex((ushort)g, buf) << "> Tj\n";
3631 last_x = x;
3632 last_y = y;
3633 }
3634 *currentPage << "EMC\n";
3635 }
3636#endif
3637
3638 *currentPage << "ET\n";
3639}
3640
3641QTransform QPdfEnginePrivate::pageMatrix() const
3642{
3643 qreal userUnit = calcUserUnit();
3644 qreal scale = 72. / userUnit / resolution;
3645 QTransform tmp(scale, 0.0, 0.0, -scale, 0.0, m_pageLayout.fullRectPoints().height() / userUnit);
3646 if (m_pageLayout.mode() != QPageLayout::FullPageMode) {
3647 QRect r = m_pageLayout.paintRectPixels(resolution);
3648 tmp.translate(r.left(), r.top());
3649 }
3650 return tmp;
3651}
3652
3653void QPdfEnginePrivate::newPage()
3654{
3655 if (currentPage && currentPage->pageSize.isEmpty())
3656 currentPage->pageSize = m_pageLayout.fullRectPoints().size();
3657 writePage();
3658
3659 delete currentPage;
3660 currentPage = new QPdfPage;
3661 currentPage->pageSize = m_pageLayout.fullRectPoints().size();
3662 stroker.stream = currentPage;
3663 pages.append(requestObject());
3664
3665 *currentPage << "/GSa gs /CSp cs /CSp CS\n"
3666 << QPdf::generateMatrix(pageMatrix())
3667 << "q q\n";
3668}
3669
3670QT_END_NAMESPACE
3671
3672#endif // QT_NO_PDF
QPdfPage()
Definition qpdf.cpp:751
ByteStream(QByteArray *ba, bool fileBacking=false)
Definition qpdf.cpp:186
ByteStream(bool fileBacking=false)
Definition qpdf.cpp:195
static int chunkSize()
Definition qpdf_p.h:65
QIODevice * stream()
Definition qpdf.cpp:270
static int maxMemorySize()
Definition qpdf_p.h:64
Definition qpdf.cpp:185
const char * toHex(ushort u, char *buffer)
Definition qpdf.cpp:718
QByteArray generatePath(const QPainterPath &path, const QTransform &matrix, PathFlags flags)
Definition qpdf.cpp:311
PathFlags
Definition qpdf_p.h:78
@ StrokePath
Definition qpdf_p.h:81
@ FillAndStrokePath
Definition qpdf_p.h:82
@ FillPath
Definition qpdf_p.h:80
@ ClipPath
Definition qpdf_p.h:79
QByteArray ascii85Encode(const QByteArray &input)
Definition qpdf.cpp:662
QByteArray generateDashes(const QPen &pen)
Definition qpdf.cpp:387
QByteArray patternForBrush(const QBrush &b)
Definition qpdf.cpp:563
QByteArray generateMatrix(const QTransform &matrix)
Definition qpdf.cpp:373
Q_GUI_EXPORT bool qt_isExtendedRadialGradient(const QBrush &brush)
Definition qbrush.cpp:877
const char * qt_int_to_string(int val, char *buf)
Definition qpdf.cpp:160
static void initResources()
Definition qpdf.cpp:47
static bool is_monochrome(const QList< QRgb > &colorTable)
Definition qpdf.cpp:3266
Q_DECLARE_TYPEINFO(QGradientBound, Q_PRIMITIVE_TYPE)
static void removeTransparencyFromBrush(QBrush &brush)
Definition qpdf.cpp:69
static void lineToHook(qfixed x, qfixed y, void *data)
Definition qpdf.cpp:583
static QByteArray qt_toPdfName(const QByteArray &input, qsizetype maxLength)
Definition qpdf.cpp:2177
static QByteArray pdfFileSpecName(QStringView string)
Definition qpdf.cpp:2082
const char * qt_real_to_string(qreal val, char *buf)
Definition qpdf.cpp:108
constexpr QPaintEngine::PaintEngineFeatures qt_pdf_decide_features()
Definition qpdf.cpp:56
static const bool interpolateImages
Definition qpdf.cpp:45
static void moveToHook(qfixed x, qfixed y, void *data)
Definition qpdf.cpp:572
static const char *const pattern_for_brush[]
Definition qpdf.cpp:410
static void cubicToHook(qfixed c1x, qfixed c1y, qfixed c2x, qfixed c2y, qfixed ex, qfixed ey, void *data)
Definition qpdf.cpp:591
static const bool do_compress
Definition qpdf.cpp:40
bool first
Definition qpdf_p.h:94
bool cosmeticPen
Definition qpdf_p.h:96
ByteStream * stream
Definition qpdf_p.h:93
void setPen(const QPen &pen, QPainter::RenderHints hints)
Definition qpdf.cpp:621
void strokePath(const QPainterPath &path)
Definition qpdf.cpp:652