1 /****************************************************************************
3 ** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
4 ** Contact: http://www.qt-project.org/legal
6 ** This file is part of the QtGui module of the Qt Toolkit.
8 ** $QT_BEGIN_LICENSE:LGPL$
9 ** Commercial License Usage
10 ** Licensees holding valid commercial Qt licenses may use this file in
11 ** accordance with the commercial license agreement provided with the
12 ** Software or, alternatively, in accordance with the terms contained in
13 ** a written agreement between you and Digia. For licensing terms and
14 ** conditions see http://qt.digia.com/licensing. For further information
15 ** use the contact form at http://qt.digia.com/contact-us.
17 ** GNU Lesser General Public License Usage
18 ** Alternatively, this file may be used under the terms of the GNU Lesser
19 ** General Public License version 2.1 as published by the Free Software
20 ** Foundation and appearing in the file LICENSE.LGPL included in the
21 ** packaging of this file. Please review the following information to
22 ** ensure the GNU Lesser General Public License version 2.1 requirements
23 ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
25 ** In addition, as a special exception, Digia gives you certain additional
26 ** rights. These rights are described in the Digia Qt LGPL Exception
27 ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
29 ** GNU General Public License Usage
30 ** Alternatively, this file may be used under the terms of the GNU
31 ** General Public License version 3.0 as published by the Free Software
32 ** Foundation and appearing in the file LICENSE.GPL included in the
33 ** packaging of this file. Please review the following information to
34 ** ensure the GNU General Public License version 3.0 requirements will be
35 ** met: http://www.gnu.org/copyleft/gpl.html.
40 ****************************************************************************/
41 #include "qplatformdefs.h"
45 #include <qtemporaryfile.h>
46 #include <private/qmath_p.h>
48 #include "private/qfont_p.h"
49 #include <qimagewriter.h>
51 #include "QtCore/qdatetime.h"
53 #ifndef QT_NO_COMPRESS
58 static const bool do_compress = false;
60 static const bool do_compress = true;
63 // might be helpful for smooth transforms of images
64 // Can't use it though, as gs generates completely wrong images if this is true.
65 static const bool interpolateImages = false;
69 inline QPaintEngine::PaintEngineFeatures qt_pdf_decide_features()
71 QPaintEngine::PaintEngineFeatures f = QPaintEngine::AllFeatures;
72 f &= ~(QPaintEngine::PorterDuff | QPaintEngine::PerspectiveTransform
73 | QPaintEngine::ObjectBoundingModeGradients
74 #ifndef USE_NATIVE_GRADIENTS
75 | QPaintEngine::LinearGradientFill
77 | QPaintEngine::RadialGradientFill
78 | QPaintEngine::ConicalGradientFill);
84 /* also adds a space at the end of the number */
85 const char *qt_real_to_string(qreal val, char *buf) {
86 const char *ret = buf;
99 unsigned int ival = (unsigned int) val;
100 qreal frac = val - (qreal)ival;
102 int ifrac = (int)(frac * 1000000000);
103 if (ifrac == 1000000000) {
110 output[i] = '0' + (ival % 10);
114 int fact = 100000000;
119 *(buf++) = output[--i];
128 *(buf++) = '0' + ((ifrac/fact) % 10);
137 const char *qt_int_to_string(int val, char *buf) {
138 const char *ret = buf;
146 output[i] = '0' + (val % 10);
154 *(buf++) = output[--i];
163 ByteStream::ByteStream(QByteArray *byteArray, bool fileBacking)
164 : dev(new QBuffer(byteArray)),
165 fileBackingEnabled(fileBacking),
166 fileBackingActive(false),
169 dev->open(QIODevice::ReadWrite | QIODevice::Append);
172 ByteStream::ByteStream(bool fileBacking)
173 : dev(new QBuffer(&ba)),
174 fileBackingEnabled(fileBacking),
175 fileBackingActive(false),
178 dev->open(QIODevice::ReadWrite);
181 ByteStream::~ByteStream()
186 ByteStream &ByteStream::operator <<(char chr)
188 if (handleDirty) prepareBuffer();
193 ByteStream &ByteStream::operator <<(const char *str)
195 if (handleDirty) prepareBuffer();
196 dev->write(str, strlen(str));
200 ByteStream &ByteStream::operator <<(const QByteArray &str)
202 if (handleDirty) prepareBuffer();
207 ByteStream &ByteStream::operator <<(const ByteStream &src)
209 Q_ASSERT(!src.dev->isSequential());
210 if (handleDirty) prepareBuffer();
211 // We do play nice here, even though it looks ugly.
212 // We save the position and restore it afterwards.
213 ByteStream &s = const_cast<ByteStream&>(src);
214 qint64 pos = s.dev->pos();
216 while (!s.dev->atEnd()) {
217 QByteArray buf = s.dev->read(chunkSize());
224 ByteStream &ByteStream::operator <<(qreal val) {
226 qt_real_to_string(val, buf);
231 ByteStream &ByteStream::operator <<(int val) {
233 qt_int_to_string(val, buf);
238 ByteStream &ByteStream::operator <<(const QPointF &p) {
240 qt_real_to_string(p.x(), buf);
242 qt_real_to_string(p.y(), buf);
247 QIODevice *ByteStream::stream()
254 void ByteStream::clear()
256 dev->open(QIODevice::ReadWrite | QIODevice::Truncate);
259 void ByteStream::constructor_helper(QByteArray *ba)
262 dev = new QBuffer(ba);
263 dev->open(QIODevice::ReadWrite);
266 void ByteStream::prepareBuffer()
268 Q_ASSERT(!dev->isSequential());
269 qint64 size = dev->size();
270 if (fileBackingEnabled && !fileBackingActive
271 && size > maxMemorySize()) {
272 // Switch to file backing.
273 QTemporaryFile *newFile = new QTemporaryFile;
276 while (!dev->atEnd()) {
277 QByteArray buf = dev->read(chunkSize());
283 fileBackingActive = true;
285 if (dev->pos() != size) {
292 #define QT_PATH_ELEMENT(elm)
294 QByteArray QPdf::generatePath(const QPainterPath &path, const QTransform &matrix, PathFlags flags)
297 if (!path.elementCount())
300 ByteStream s(&result);
303 for (int i = 0; i < path.elementCount(); ++i) {
304 const QPainterPath::Element &elm = path.elementAt(i);
306 case QPainterPath::MoveToElement:
308 && path.elementAt(start).x == path.elementAt(i-1).x
309 && path.elementAt(start).y == path.elementAt(i-1).y)
311 s << matrix.map(QPointF(elm.x, elm.y)) << "m\n";
314 case QPainterPath::LineToElement:
315 s << matrix.map(QPointF(elm.x, elm.y)) << "l\n";
317 case QPainterPath::CurveToElement:
318 Q_ASSERT(path.elementAt(i+1).type == QPainterPath::CurveToDataElement);
319 Q_ASSERT(path.elementAt(i+2).type == QPainterPath::CurveToDataElement);
320 s << matrix.map(QPointF(elm.x, elm.y))
321 << matrix.map(QPointF(path.elementAt(i+1).x, path.elementAt(i+1).y))
322 << matrix.map(QPointF(path.elementAt(i+2).x, path.elementAt(i+2).y))
327 qFatal("QPdf::generatePath(), unhandled type: %d", elm.type);
331 && path.elementAt(start).x == path.elementAt(path.elementCount()-1).x
332 && path.elementAt(start).y == path.elementAt(path.elementCount()-1).y)
335 Qt::FillRule fillRule = path.fillRule();
340 op = (fillRule == Qt::WindingFill) ? "W n\n" : "W* n\n";
343 op = (fillRule == Qt::WindingFill) ? "f\n" : "f*\n";
348 case FillAndStrokePath:
349 op = (fillRule == Qt::WindingFill) ? "B\n" : "B*\n";
356 QByteArray QPdf::generateMatrix(const QTransform &matrix)
359 ByteStream s(&result);
370 QByteArray QPdf::generateDashes(const QPen &pen)
373 ByteStream s(&result);
376 QVector<qreal> dasharray = pen.dashPattern();
377 qreal w = pen.widthF();
380 for (int i = 0; i < dasharray.size(); ++i) {
381 qreal dw = dasharray.at(i)*w;
382 if (dw < 0.0001) dw = 0.0001;
386 //qDebug() << "dasharray: pen has" << dasharray;
387 //qDebug() << " => " << result;
393 static const char* pattern_for_brush[] = {
403 "S\n", // Dense1Pattern
422 "S\n", // Dense2Pattern
441 "S\n", // Dense3Pattern
460 "S\n", // Dense4Pattern
479 "S\n", // Dense5Pattern
492 "S\n", // Dense6Pattern
501 "S\n", // Dense7Pattern
518 "S\n", // CrossPattern
525 "S\n", // BDiagPattern
532 "S\n", // FDiagPattern
543 "S\n", // DiagCrossPattern
546 QByteArray QPdf::patternForBrush(const QBrush &b)
548 int style = b.style();
549 if (style > Qt::DiagCrossPattern)
551 return pattern_for_brush[style];
554 #ifdef USE_NATIVE_GRADIENTS
555 static void writeTriangleLine(uchar *&data, int xpos, int ypos, int xoff, int yoff, uint rgb, uchar flag, bool alpha)
558 data[1] = (uchar)(xpos >> 16);
559 data[2] = (uchar)(xpos >> 8);
560 data[3] = (uchar)(xpos >> 0);
561 data[4] = (uchar)(ypos >> 16);
562 data[5] = (uchar)(ypos >> 8);
563 data[6] = (uchar)(ypos >> 0);
566 *data++ = (uchar)qAlpha(rgb);
568 *data++ = (uchar)qRed(rgb);
569 *data++ = (uchar)qGreen(rgb);
570 *data++ = (uchar)qBlue(rgb);
575 data[1] = (uchar)(xpos >> 16);
576 data[2] = (uchar)(xpos >> 8);
577 data[3] = (uchar)(xpos >> 0);
578 data[4] = (uchar)(ypos >> 16);
579 data[5] = (uchar)(ypos >> 8);
580 data[6] = (uchar)(ypos >> 0);
583 *data++ = (uchar)qAlpha(rgb);
585 *data++ = (uchar)qRed(rgb);
586 *data++ = (uchar)qGreen(rgb);
587 *data++ = (uchar)qBlue(rgb);
592 QByteArray QPdf::generateLinearGradientShader(const QLinearGradient *gradient, const QPointF *page_rect, bool alpha)
594 // generate list of triangles with colors
595 QPointF start = gradient->start();
596 QPointF stop = gradient->finalStop();
597 QGradientStops stops = gradient->stops();
598 QPointF offset = stop - start;
599 QGradient::Spread spread = gradient->spread();
601 if (gradient->spread() == QGradient::ReflectSpread) {
603 for (int i = stops.size() - 2; i >= 0; --i) {
604 QGradientStop stop = stops.at(i);
605 stop.first = 2. - stop.first;
608 for (int i = 0 ; i < stops.size(); ++i)
609 stops[i].first /= 2.;
612 QPointF orthogonal(offset.y(), -offset.x());
613 qreal length = offset.x()*offset.x() + offset.y()*offset.y();
615 // find the max and min values in offset and orth direction that are needed to cover
617 int off_min = INT_MAX;
618 int off_max = INT_MIN;
619 qreal ort_min = INT_MAX;
620 qreal ort_max = INT_MIN;
621 for (int i = 0; i < 4; ++i) {
622 qreal off = ((page_rect[i].x() - start.x()) * offset.x() + (page_rect[i].y() - start.y()) * offset.y())/length;
623 qreal ort = ((page_rect[i].x() - start.x()) * orthogonal.x() + (page_rect[i].y() - start.y()) * orthogonal.y())/length;
624 off_min = qMin(off_min, qFloor(off));
625 off_max = qMax(off_max, qCeil(off));
626 ort_min = qMin(ort_min, ort);
627 ort_max = qMax(ort_max, ort);
632 start += off_min * offset + ort_min * orthogonal;
633 orthogonal *= (ort_max - ort_min);
634 int num = off_max - off_min;
636 QPointF gradient_rect[4] = { start,
639 start + num*offset + orthogonal };
640 qreal xmin = gradient_rect[0].x();
641 qreal xmax = gradient_rect[0].x();
642 qreal ymin = gradient_rect[0].y();
643 qreal ymax = gradient_rect[0].y();
644 for (int i = 1; i < 4; ++i) {
645 xmin = qMin(xmin, gradient_rect[i].x());
646 xmax = qMax(xmax, gradient_rect[i].x());
647 ymin = qMin(ymin, gradient_rect[i].y());
648 ymax = qMax(ymax, gradient_rect[i].y());
654 start -= QPointF(xmin, ymin);
655 qreal factor_x = qreal(1<<24)/(xmax - xmin);
656 qreal factor_y = qreal(1<<24)/(ymax - ymin);
657 int xoff = (int)(orthogonal.x()*factor_x);
658 int yoff = (int)(orthogonal.y()*factor_y);
660 QByteArray triangles;
661 triangles.resize(spread == QGradient::PadSpread ? 20*(stops.size()+2) : 20*num*stops.size());
662 uchar *data = (uchar *) triangles.data();
663 if (spread == QGradient::PadSpread) {
664 if (off_min > 0 || off_max < 1) {
665 // linear gradient outside of page
666 const QGradientStop ¤t_stop = off_min > 0 ? stops.at(stops.size()-1) : stops.at(0);
667 uint rgb = current_stop.second.rgba();
668 int xpos = (int)(start.x()*factor_x);
669 int ypos = (int)(start.y()*factor_y);
670 writeTriangleLine(data, xpos, ypos, xoff, yoff, rgb, 0, alpha);
672 xpos = (int)(start.x()*factor_x);
673 ypos = (int)(start.y()*factor_y);
674 writeTriangleLine(data, xpos, ypos, xoff, yoff, rgb, 1, alpha);
678 uint rgb = stops.at(0).second.rgba();
679 int xpos = (int)(start.x()*factor_x);
680 int ypos = (int)(start.y()*factor_y);
681 writeTriangleLine(data, xpos, ypos, xoff, yoff, rgb, flag, alpha);
682 start -= off_min*offset;
685 for (int s = 0; s < stops.size(); ++s) {
686 const QGradientStop ¤t_stop = stops.at(s);
687 uint rgb = current_stop.second.rgba();
688 int xpos = (int)(start.x()*factor_x);
689 int ypos = (int)(start.y()*factor_y);
690 writeTriangleLine(data, xpos, ypos, xoff, yoff, rgb, flag, alpha);
691 if (s < stops.size()-1)
692 start += offset*(stops.at(s+1).first - stops.at(s).first);
696 start += (off_max - 1)*offset;
697 uint rgb = stops.at(stops.size()-1).second.rgba();
698 int xpos = (int)(start.x()*factor_x);
699 int ypos = (int)(start.y()*factor_y);
700 writeTriangleLine(data, xpos, ypos, xoff, yoff, rgb, flag, alpha);
704 for (int i = 0; i < num; ++i) {
706 for (int s = 0; s < stops.size(); ++s) {
707 uint rgb = stops.at(s).second.rgba();
708 int xpos = (int)(start.x()*factor_x);
709 int ypos = (int)(start.y()*factor_y);
710 writeTriangleLine(data, xpos, ypos, xoff, yoff, rgb, flag, alpha);
711 if (s < stops.size()-1)
712 start += offset*(stops.at(s+1).first - stops.at(s).first);
717 triangles.resize((char *)data - triangles.constData());
720 QPdf::ByteStream s(&shader);
723 "/ColorSpace " << (alpha ? "/DeviceGray\n" : "/DeviceRGB\n") <<
725 "/BitsPerCoordinate 24\n"
726 "/BitsPerComponent 8\n"
728 "/Decode [" << xmin << xmax << ymin << ymax << (alpha ? "0 1]\n" : "0 1 0 1 0 1]\n") <<
730 "/Length " << triangles.length() << "\n"
732 "stream\n" << triangles << "endstream\n"
738 static void moveToHook(qfixed x, qfixed y, void *data)
740 QPdf::Stroker *t = (QPdf::Stroker *)data;
744 t->matrix.map(x, y, &x, &y);
745 *t->stream << x << y << "m\n";
749 static void lineToHook(qfixed x, qfixed y, void *data)
751 QPdf::Stroker *t = (QPdf::Stroker *)data;
753 t->matrix.map(x, y, &x, &y);
754 *t->stream << x << y << "l\n";
757 static void cubicToHook(qfixed c1x, qfixed c1y,
758 qfixed c2x, qfixed c2y,
759 qfixed ex, qfixed ey,
762 QPdf::Stroker *t = (QPdf::Stroker *)data;
763 if (!t->cosmeticPen) {
764 t->matrix.map(c1x, c1y, &c1x, &c1y);
765 t->matrix.map(c2x, c2y, &c2x, &c2y);
766 t->matrix.map(ex, ey, &ex, &ey);
768 *t->stream << c1x << c1y
774 QPdf::Stroker::Stroker()
777 dashStroker(&basicStroker)
779 stroker = &basicStroker;
780 basicStroker.setMoveToHook(moveToHook);
781 basicStroker.setLineToHook(lineToHook);
782 basicStroker.setCubicToHook(cubicToHook);
784 basicStroker.setStrokeWidth(.1);
787 void QPdf::Stroker::setPen(const QPen &pen)
789 if (pen.style() == Qt::NoPen) {
793 qreal w = pen.widthF();
794 bool zeroWidth = w < 0.0001;
795 cosmeticPen = pen.isCosmetic();
799 basicStroker.setStrokeWidth(w);
800 basicStroker.setCapStyle(pen.capStyle());
801 basicStroker.setJoinStyle(pen.joinStyle());
802 basicStroker.setMiterLimit(pen.miterLimit());
804 QVector<qreal> dashpattern = pen.dashPattern();
806 for (int i = 0; i < dashpattern.size(); ++i)
807 dashpattern[i] *= 10.;
809 if (!dashpattern.isEmpty()) {
810 dashStroker.setDashPattern(dashpattern);
811 dashStroker.setDashOffset(pen.dashOffset());
812 stroker = &dashStroker;
814 stroker = &basicStroker;
818 void QPdf::Stroker::strokePath(const QPainterPath &path)
824 stroker->strokePath(path, this, cosmeticPen ? matrix : QTransform());
828 QByteArray QPdf::ascii85Encode(const QByteArray &input)
830 int isize = input.size()/4*4;
832 output.resize(input.size()*5/4+7);
833 char *out = output.data();
834 const uchar *in = (const uchar *)input.constData();
835 for (int i = 0; i < isize; i += 4) {
836 uint val = (((uint)in[i])<<24) + (((uint)in[i+1])<<16) + (((uint)in[i+2])<<8) + (uint)in[i+3];
851 *(out++) = base[0] + '!';
852 *(out++) = base[1] + '!';
853 *(out++) = base[2] + '!';
854 *(out++) = base[3] + '!';
855 *(out++) = base[4] + '!';
858 //write the last few bytes
859 int remaining = input.size() - isize;
862 for (int i = isize; i < input.size(); ++i)
863 val = (val << 8) + in[i];
864 val <<= 8*(4-remaining);
875 for (int i = 0; i < remaining+1; ++i)
876 *(out++) = base[i] + '!';
880 output.resize(out-output.data());
884 const char *QPdf::toHex(ushort u, char *buffer)
888 ushort hex = (u & 0x000f);
892 buffer[i] = 'A'+(hex-0x0a);
900 const char *QPdf::toHex(uchar u, char *buffer)
904 ushort hex = (u & 0x000f);
908 buffer[i] = 'A'+(hex-0x0a);
918 : QPdf::ByteStream(true) // Enable file backing
922 void QPdfPage::streamImage(int w, int h, int object)
924 *this << w << "0 0 " << -h << "0 " << h << "cm /Im" << object << " Do\n";
925 if (!images.contains(object))
926 images.append(object);
930 QPdfEngine::QPdfEngine(QPdfEnginePrivate &dd)
931 : QPaintEngine(dd, qt_pdf_decide_features())
935 QPdfEngine::QPdfEngine()
936 : QPaintEngine(*new QPdfEnginePrivate(), qt_pdf_decide_features())
940 void QPdfEngine::setOutputFilename(const QString &filename)
943 d->outputFileName = filename;
947 void QPdfEngine::drawPoints (const QPointF *points, int pointCount)
954 for (int i=0; i!=pointCount;++i) {
956 p.lineTo(points[i] + QPointF(0, 0.001));
959 bool hadBrush = d->hasBrush;
962 d->hasBrush = hadBrush;
965 void QPdfEngine::drawLines (const QLineF *lines, int lineCount)
972 for (int i=0; i!=lineCount;++i) {
973 p.moveTo(lines[i].p1());
974 p.lineTo(lines[i].p2());
976 bool hadBrush = d->hasBrush;
979 d->hasBrush = hadBrush;
982 void QPdfEngine::drawRects (const QRectF *rects, int rectCount)
989 if (d->clipEnabled && d->allClipped)
991 if (!d->hasPen && !d->hasBrush)
994 QBrush penBrush = d->pen.brush();
995 if (d->simplePen || !d->hasPen) {
996 // draw strokes natively in this case for better output
997 if(!d->simplePen && !d->stroker.matrix.isIdentity())
998 *d->currentPage << "q\n" << QPdf::generateMatrix(d->stroker.matrix);
999 for (int i = 0; i < rectCount; ++i)
1000 *d->currentPage << rects[i].x() << rects[i].y() << rects[i].width() << rects[i].height() << "re\n";
1001 *d->currentPage << (d->hasPen ? (d->hasBrush ? "B\n" : "S\n") : "f\n");
1002 if(!d->simplePen && !d->stroker.matrix.isIdentity())
1003 *d->currentPage << "Q\n";
1006 for (int i=0; i!=rectCount; ++i)
1007 p.addRect(rects[i]);
1012 void QPdfEngine::drawPolygon(const QPointF *points, int pointCount, PolygonDrawMode mode)
1016 if (!points || !pointCount)
1019 bool hb = d->hasBrush;
1024 p.setFillRule(Qt::OddEvenFill);
1028 p.setFillRule(Qt::WindingFill);
1031 d->hasBrush = false;
1037 p.moveTo(points[0]);
1038 for (int i = 1; i < pointCount; ++i)
1039 p.lineTo(points[i]);
1041 if (mode != PolylineMode)
1048 void QPdfEngine::drawPath (const QPainterPath &p)
1052 if (d->clipEnabled && d->allClipped)
1054 if (!d->hasPen && !d->hasBrush)
1058 // draw strokes natively in this case for better output
1059 *d->currentPage << QPdf::generatePath(p, QTransform(), d->hasBrush ? QPdf::FillAndStrokePath : QPdf::StrokePath);
1062 *d->currentPage << QPdf::generatePath(p, d->stroker.matrix, QPdf::FillPath);
1064 *d->currentPage << "q\n";
1065 QBrush b = d->brush;
1066 d->brush = d->pen.brush();
1068 d->stroker.strokePath(p);
1069 *d->currentPage << "Q\n";
1075 void QPdfEngine::drawPixmap (const QRectF &rectangle, const QPixmap &pixmap, const QRectF &sr)
1077 if (sr.isEmpty() || rectangle.isEmpty() || pixmap.isNull())
1081 QBrush b = d->brush;
1083 QRect sourceRect = sr.toRect();
1084 QPixmap pm = sourceRect != pixmap.rect() ? pixmap.copy(sourceRect) : pixmap;
1085 QImage image = pm.toImage();
1087 const int object = d->addImage(image, &bitmap, pm.cacheKey());
1091 *d->currentPage << "q\n/GSa gs\n";
1093 << QPdf::generateMatrix(QTransform(rectangle.width() / sr.width(), 0, 0, rectangle.height() / sr.height(),
1094 rectangle.x(), rectangle.y()) * (d->simplePen ? QTransform() : d->stroker.matrix));
1096 // set current pen as d->brush
1097 d->brush = d->pen.brush();
1100 d->currentPage->streamImage(image.width(), image.height(), object);
1101 *d->currentPage << "Q\n";
1106 void QPdfEngine::drawImage(const QRectF &rectangle, const QImage &image, const QRectF &sr, Qt::ImageConversionFlags)
1108 if (sr.isEmpty() || rectangle.isEmpty() || image.isNull())
1112 QRect sourceRect = sr.toRect();
1113 QImage im = sourceRect != image.rect() ? image.copy(sourceRect) : image;
1115 const int object = d->addImage(im, &bitmap, im.cacheKey());
1119 *d->currentPage << "q\n/GSa gs\n";
1121 << QPdf::generateMatrix(QTransform(rectangle.width() / sr.width(), 0, 0, rectangle.height() / sr.height(),
1122 rectangle.x(), rectangle.y()) * (d->simplePen ? QTransform() : d->stroker.matrix));
1124 d->currentPage->streamImage(im.width(), im.height(), object);
1125 *d->currentPage << "Q\n";
1128 void QPdfEngine::drawTiledPixmap (const QRectF &rectangle, const QPixmap &pixmap, const QPointF &point)
1132 bool bitmap = (pixmap.depth() == 1);
1133 QBrush b = d->brush;
1134 QPointF bo = d->brushOrigin;
1135 bool hp = d->hasPen;
1137 bool hb = d->hasBrush;
1140 d->brush = QBrush(pixmap);
1142 // #### fix bitmap case where we have a brush pen
1143 d->brush.setColor(d->pen.color());
1145 d->brushOrigin = -point;
1146 *d->currentPage << "q\n";
1149 drawRects(&rectangle, 1);
1150 *d->currentPage << "Q\n";
1155 d->brushOrigin = bo;
1158 void QPdfEngine::drawTextItem(const QPointF &p, const QTextItem &textItem)
1162 if (!d->hasPen || (d->clipEnabled && d->allClipped))
1165 if (d->stroker.matrix.type() >= QTransform::TxProject) {
1166 QPaintEngine::drawTextItem(p, textItem);
1170 *d->currentPage << "q\n";
1172 *d->currentPage << QPdf::generateMatrix(d->stroker.matrix);
1174 bool hp = d->hasPen;
1176 QBrush b = d->brush;
1177 d->brush = d->pen.brush();
1180 const QTextItemInt &ti = static_cast<const QTextItemInt &>(textItem);
1181 Q_ASSERT(ti.fontEngine->type() != QFontEngine::Multi);
1182 d->drawTextItem(p, ti);
1185 *d->currentPage << "Q\n";
1189 void QPdfEngine::updateState(const QPaintEngineState &state)
1193 QPaintEngine::DirtyFlags flags = state.state();
1195 if (flags & DirtyTransform)
1196 d->stroker.matrix = state.transform();
1198 if (flags & DirtyPen) {
1199 d->pen = state.pen();
1200 d->hasPen = d->pen.style() != Qt::NoPen;
1201 d->stroker.setPen(d->pen);
1202 QBrush penBrush = d->pen.brush();
1203 bool oldSimple = d->simplePen;
1204 d->simplePen = (d->hasPen && (penBrush.style() == Qt::SolidPattern) && penBrush.isOpaque());
1205 if (oldSimple != d->simplePen)
1206 flags |= DirtyTransform;
1208 if (flags & DirtyBrush) {
1209 d->brush = state.brush();
1210 if (d->brush.color().alpha() == 0 && d->brush.style() == Qt::SolidPattern)
1211 d->brush.setStyle(Qt::NoBrush);
1212 d->hasBrush = d->brush.style() != Qt::NoBrush;
1214 if (flags & DirtyBrushOrigin) {
1215 d->brushOrigin = state.brushOrigin();
1216 flags |= DirtyBrush;
1218 if (flags & DirtyOpacity)
1219 d->opacity = state.opacity();
1221 bool ce = d->clipEnabled;
1222 if (flags & DirtyClipPath) {
1223 d->clipEnabled = true;
1224 updateClipPath(state.clipPath(), state.clipOperation());
1225 } else if (flags & DirtyClipRegion) {
1226 d->clipEnabled = true;
1228 QVector<QRect> rects = state.clipRegion().rects();
1229 for (int i = 0; i < rects.size(); ++i)
1230 path.addRect(rects.at(i));
1231 updateClipPath(path, state.clipOperation());
1232 flags |= DirtyClipPath;
1233 } else if (flags & DirtyClipEnabled) {
1234 d->clipEnabled = state.isClipEnabled();
1237 if (ce != d->clipEnabled)
1238 flags |= DirtyClipPath;
1239 else if (!d->clipEnabled)
1240 flags &= ~DirtyClipPath;
1242 setupGraphicsState(flags);
1245 void QPdfEngine::setupGraphicsState(QPaintEngine::DirtyFlags flags)
1248 if (flags & DirtyClipPath)
1249 flags |= DirtyTransform|DirtyPen|DirtyBrush;
1251 if (flags & DirtyTransform) {
1252 *d->currentPage << "Q\n";
1253 flags |= DirtyPen|DirtyBrush;
1256 if (flags & DirtyClipPath) {
1257 *d->currentPage << "Q q\n";
1259 d->allClipped = false;
1260 if (d->clipEnabled && !d->clips.isEmpty()) {
1261 for (int i = 0; i < d->clips.size(); ++i) {
1262 if (d->clips.at(i).isEmpty()) {
1263 d->allClipped = true;
1267 if (!d->allClipped) {
1268 for (int i = 0; i < d->clips.size(); ++i) {
1269 *d->currentPage << QPdf::generatePath(d->clips.at(i), QTransform(), QPdf::ClipPath);
1275 if (flags & DirtyTransform) {
1276 *d->currentPage << "q\n";
1277 if (d->simplePen && !d->stroker.matrix.isIdentity())
1278 *d->currentPage << QPdf::generateMatrix(d->stroker.matrix);
1280 if (flags & DirtyBrush)
1282 if (d->simplePen && (flags & DirtyPen))
1286 extern QPainterPath qt_regionToPath(const QRegion ®ion);
1288 void QPdfEngine::updateClipPath(const QPainterPath &p, Qt::ClipOperation op)
1291 QPainterPath path = d->stroker.matrix.map(p);
1292 //qDebug() << "updateClipPath: " << d->stroker.matrix << p.boundingRect() << path.boundingRect() << op;
1294 if (op == Qt::NoClip) {
1295 d->clipEnabled = false;
1297 } else if (op == Qt::ReplaceClip) {
1299 d->clips.append(path);
1300 } else if (op == Qt::IntersectClip) {
1301 d->clips.append(path);
1302 } else { // UniteClip
1303 // ask the painter for the current clipping path. that's the easiest solution
1304 path = painter()->clipPath();
1305 path = d->stroker.matrix.map(path);
1307 d->clips.append(path);
1311 void QPdfEngine::setPen()
1314 if (d->pen.style() == Qt::NoPen)
1316 QBrush b = d->pen.brush();
1317 Q_ASSERT(b.style() == Qt::SolidPattern && b.isOpaque());
1319 QColor rgba = b.color();
1321 qreal gray = qGray(rgba.rgba())/255.;
1322 *d->currentPage << gray << gray << gray;
1324 *d->currentPage << rgba.redF()
1328 *d->currentPage << "SCN\n";
1330 *d->currentPage << d->pen.widthF() << "w ";
1332 int pdfCapStyle = 0;
1333 switch(d->pen.capStyle()) {
1346 *d->currentPage << pdfCapStyle << "J ";
1348 int pdfJoinStyle = 0;
1349 switch(d->pen.joinStyle()) {
1362 *d->currentPage << pdfJoinStyle << "j ";
1364 *d->currentPage << QPdf::generateDashes(d->pen) << " 0 d\n";
1368 void QPdfEngine::setBrush()
1371 Qt::BrushStyle style = d->brush.style();
1372 if (style == Qt::NoBrush)
1376 int gStateObject = 0;
1377 int patternObject = d->addBrushPattern(d->stroker.matrix, &specifyColor, &gStateObject);
1379 *d->currentPage << (patternObject ? "/PCSp cs " : "/CSp cs ");
1381 QColor rgba = d->brush.color();
1383 qreal gray = qGray(rgba.rgba())/255.;
1384 *d->currentPage << gray << gray << gray;
1386 *d->currentPage << rgba.redF()
1392 *d->currentPage << "/Pat" << patternObject;
1393 *d->currentPage << "scn\n";
1396 *d->currentPage << "/GState" << gStateObject << "gs\n";
1398 *d->currentPage << "/GSa gs\n";
1402 bool QPdfEngine::newPage()
1409 setupGraphicsState(DirtyBrush|DirtyPen|DirtyClipPath);
1410 QFile *outfile = qobject_cast<QFile*> (d->outDevice);
1411 if (outfile && outfile->error() != QFile::NoError)
1416 QPaintEngine::Type QPdfEngine::type() const
1418 return QPaintEngine::Pdf;
1423 int QPdfEngine::metric(QPaintDevice::PaintDeviceMetric metricType) const
1425 Q_D(const QPdfEngine);
1427 QRect r = d->pageRect();
1428 switch (metricType) {
1429 case QPaintDevice::PdmWidth:
1432 case QPaintDevice::PdmHeight:
1435 case QPaintDevice::PdmDpiX:
1436 case QPaintDevice::PdmDpiY:
1437 val = d->resolution;
1439 case QPaintDevice::PdmPhysicalDpiX:
1440 case QPaintDevice::PdmPhysicalDpiY:
1443 case QPaintDevice::PdmWidthMM:
1444 val = qRound(r.width()*25.4/d->resolution);
1446 case QPaintDevice::PdmHeightMM:
1447 val = qRound(r.height()*25.4/d->resolution);
1449 case QPaintDevice::PdmNumColors:
1452 case QPaintDevice::PdmDepth:
1456 qWarning("QPdfWriter::metric: Invalid metric command");
1462 #define Q_MM(n) int((n * 720 + 127) / 254)
1464 QPdfEnginePrivate::QPdfEnginePrivate()
1465 : clipEnabled(false), allClipped(false), hasPen(true), hasBrush(false), simplePen(false),
1466 outDevice(0), ownsDevice(false),
1467 fullPage(false), embedFonts(true),
1470 paperSize(Q_MM(210), Q_MM(297)), // A4
1471 leftMargin(10), topMargin(10), rightMargin(10), bottomMargin(10) // ~3.5 mm
1481 stream = new QDataStream;
1484 bool QPdfEngine::begin(QPaintDevice *pdev)
1489 if (!d->outDevice) {
1490 if (!d->outputFileName.isEmpty()) {
1491 QFile *file = new QFile(d->outputFileName);
1492 if (!file->open(QFile::WriteOnly|QFile::Truncate)) {
1496 d->outDevice = file;
1500 d->ownsDevice = true;
1503 d->postscript = false;
1504 d->currentObject = 1;
1506 d->currentPage = new QPdfPage;
1507 d->stroker.stream = d->currentPage;
1510 d->stream->setDevice(d->outDevice);
1514 d->hasBrush = false;
1515 d->clipEnabled = false;
1516 d->allClipped = false;
1518 d->xrefPositions.clear();
1522 d->graphicsState = 0;
1523 d->patternColorSpace = 0;
1524 d->simplePen = false;
1527 d->imageCache.clear();
1528 d->alphaCache.clear();
1537 bool QPdfEngine::end()
1542 d->stream->unsetDevice();
1544 qDeleteAll(d->fonts);
1546 delete d->currentPage;
1549 if (d->outDevice && d->ownsDevice) {
1550 d->outDevice->close();
1551 delete d->outDevice;
1559 QPdfEnginePrivate::~QPdfEnginePrivate()
1566 QRect QPdfEnginePrivate::paperRect() const
1568 int w = qRound(paperSize.width()*resolution/72.);
1569 int h = qRound(paperSize.height()*resolution/72.);
1572 return QRect(0, 0, w, h);
1574 return QRect(0, 0, h, w);
1577 QRect QPdfEnginePrivate::pageRect() const
1579 QRect r = paperRect();
1582 r.adjust(qRound(leftMargin*(resolution/72.)),
1583 qRound(topMargin*(resolution/72.)),
1584 -qRound(rightMargin*(resolution/72.)),
1585 -qRound(bottomMargin*(resolution/72.)));
1591 void QPdfEnginePrivate::writeHeader()
1593 addXrefEntry(0,false);
1595 xprintf("%%PDF-1.4\n");
1599 catalog = addXrefEntry(-1);
1600 pageRoot = requestObject();
1605 "endobj\n", pageRoot);
1608 graphicsState = addXrefEntry(-1);
1610 "/Type /ExtGState\n"
1620 // color space for pattern
1621 patternColorSpace = addXrefEntry(-1);
1622 xprintf("[/Pattern /DeviceRGB]\n"
1626 void QPdfEnginePrivate::writeInfo()
1628 info = addXrefEntry(-1);
1629 xprintf("<<\n/Title ");
1631 xprintf("\n/Creator ");
1632 printString(creator);
1633 xprintf("\n/Producer ");
1634 printString(QString::fromLatin1("Qt " QT_VERSION_STR " (C) 2011 Nokia Corporation and/or its subsidiary(-ies)"));
1635 QDateTime now = QDateTime::currentDateTime().toUTC();
1636 QTime t = now.time();
1637 QDate d = now.date();
1638 xprintf("\n/CreationDate (D:%d%02d%02d%02d%02d%02d)\n",
1649 void QPdfEnginePrivate::writePageRoot()
1651 addXrefEntry(pageRoot);
1657 int size = pages.size();
1658 for (int i = 0; i < size; ++i)
1659 xprintf("%d 0 R\n", pages[i]);
1662 //xprintf("/Group <</S /Transparency /I true /K false>>\n");
1663 xprintf("/Count %d\n", pages.size());
1665 xprintf("/ProcSet [/PDF /Text /ImageB /ImageC]\n"
1671 void QPdfEnginePrivate::embedFont(QFontSubset *font)
1673 //qDebug() << "embedFont" << font->object_id;
1674 int fontObject = font->object_id;
1675 QByteArray fontData = font->toTruetype();
1678 QString fileName("font%1.ttf");
1679 fileName = fileName.arg(i++);
1681 ff.open(QFile::WriteOnly);
1686 int fontDescriptor = requestObject();
1687 int fontstream = requestObject();
1688 int cidfont = requestObject();
1689 int toUnicode = requestObject();
1691 QFontEngine::Properties properties = font->fontEngine->properties();
1694 qreal scale = 1000/properties.emSquare.toReal();
1695 addXrefEntry(fontDescriptor);
1696 QByteArray descriptor;
1697 QPdf::ByteStream s(&descriptor);
1698 s << "<< /Type /FontDescriptor\n"
1700 int tag = fontDescriptor;
1701 for (int i = 0; i < 5; ++i) {
1702 s << (char)('A' + (tag % 26));
1705 s << '+' << properties.postscriptName << "\n"
1706 "/Flags " << 4 << "\n"
1708 << properties.boundingBox.x()*scale
1709 << -(properties.boundingBox.y() + properties.boundingBox.height())*scale
1710 << (properties.boundingBox.x() + properties.boundingBox.width())*scale
1711 << -properties.boundingBox.y()*scale << "]\n"
1712 "/ItalicAngle " << properties.italicAngle.toReal() << "\n"
1713 "/Ascent " << properties.ascent.toReal()*scale << "\n"
1714 "/Descent " << -properties.descent.toReal()*scale << "\n"
1715 "/CapHeight " << properties.capHeight.toReal()*scale << "\n"
1716 "/StemV " << properties.lineWidth.toReal()*scale << "\n"
1717 "/FontFile2 " << fontstream << "0 R\n"
1722 addXrefEntry(fontstream);
1724 QPdf::ByteStream s(&header);
1726 int length_object = requestObject();
1728 "/Length1 " << fontData.size() << "\n"
1729 "/Length " << length_object << "0 R\n";
1731 s << "/Filter /FlateDecode\n";
1735 int len = writeCompressed(fontData);
1738 addXrefEntry(length_object);
1743 addXrefEntry(cidfont);
1745 QPdf::ByteStream s(&cid);
1746 s << "<< /Type /Font\n"
1747 "/Subtype /CIDFontType2\n"
1748 "/BaseFont /" << properties.postscriptName << "\n"
1749 "/CIDSystemInfo << /Registry (Adobe) /Ordering (Identity) /Supplement 0 >>\n"
1750 "/FontDescriptor " << fontDescriptor << "0 R\n"
1751 "/CIDToGIDMap /Identity\n"
1752 << font->widthArray() <<
1758 addXrefEntry(toUnicode);
1759 QByteArray touc = font->createToUnicodeMap();
1760 xprintf("<< /Length %d >>\n"
1761 "stream\n", touc.length());
1767 addXrefEntry(fontObject);
1769 QPdf::ByteStream s(&font);
1770 s << "<< /Type /Font\n"
1772 "/BaseFont /" << properties.postscriptName << "\n"
1773 "/Encoding /Identity-H\n"
1774 "/DescendantFonts [" << cidfont << "0 R]\n"
1775 "/ToUnicode " << toUnicode << "0 R"
1783 void QPdfEnginePrivate::writeFonts()
1785 for (QHash<QFontEngine::FaceId, QFontSubset *>::iterator it = fonts.begin(); it != fonts.end(); ++it) {
1792 void QPdfEnginePrivate::writePage()
1797 *currentPage << "Q Q\n";
1799 uint pageStream = requestObject();
1800 uint pageStreamLength = requestObject();
1801 uint resources = requestObject();
1802 uint annots = requestObject();
1804 addXrefEntry(pages.last());
1808 "/Contents %d 0 R\n"
1809 "/Resources %d 0 R\n"
1811 "/MediaBox [0 0 %d %d]\n"
1814 pageRoot, pageStream, resources, annots,
1815 // make sure we use the pagesize from when we started the page, since the user may have changed it
1816 currentPage->pageSize.width(), currentPage->pageSize.height());
1818 addXrefEntry(resources);
1823 "/CSpg /DeviceGray\n"
1827 patternColorSpace, graphicsState);
1829 for (int i = 0; i < currentPage->graphicStates.size(); ++i)
1830 xprintf("/GState%d %d 0 R\n", currentPage->graphicStates.at(i), currentPage->graphicStates.at(i));
1833 xprintf("/Pattern <<\n");
1834 for (int i = 0; i < currentPage->patterns.size(); ++i)
1835 xprintf("/Pat%d %d 0 R\n", currentPage->patterns.at(i), currentPage->patterns.at(i));
1838 xprintf("/Font <<\n");
1839 for (int i = 0; i < currentPage->fonts.size();++i)
1840 xprintf("/F%d %d 0 R\n", currentPage->fonts[i], currentPage->fonts[i]);
1843 xprintf("/XObject <<\n");
1844 for (int i = 0; i<currentPage->images.size(); ++i) {
1845 xprintf("/Im%d %d 0 R\n", currentPage->images.at(i), currentPage->images.at(i));
1852 addXrefEntry(annots);
1854 for (int i = 0; i<currentPage->annotations.size(); ++i) {
1855 xprintf("%d 0 R ", currentPage->annotations.at(i));
1857 xprintf("]\nendobj\n");
1859 addXrefEntry(pageStream);
1861 "/Length %d 0 R\n", pageStreamLength); // object number for stream length object
1863 xprintf("/Filter /FlateDecode\n");
1866 xprintf("stream\n");
1867 QIODevice *content = currentPage->stream();
1868 int len = writeCompressed(content);
1869 xprintf("endstream\n"
1872 addXrefEntry(pageStreamLength);
1873 xprintf("%d\nendobj\n",len);
1876 void QPdfEnginePrivate::writeTail()
1881 addXrefEntry(xrefPositions.size(),false);
1884 "%010d 65535 f \n", xrefPositions.size()-1, xrefPositions[0]);
1886 for (int i = 1; i < xrefPositions.size()-1; ++i)
1887 xprintf("%010d 00000 n \n", xrefPositions[i]);
1897 xrefPositions.size()-1, info, catalog, xrefPositions.last());
1900 int QPdfEnginePrivate::addXrefEntry(int object, bool printostr)
1903 object = requestObject();
1905 if (object>=xrefPositions.size())
1906 xrefPositions.resize(object+1);
1908 xrefPositions[object] = streampos;
1910 xprintf("%d 0 obj\n",object);
1915 void QPdfEnginePrivate::printString(const QString &string) {
1916 // The 'text string' type in PDF is encoded either as PDFDocEncoding, or
1917 // Unicode UTF-16 with a Unicode byte order mark as the first character
1918 // (0xfeff), with the high-order byte first.
1919 QByteArray array("(\xfe\xff");
1920 const ushort *utf16 = string.utf16();
1922 for (int i=0; i < string.size(); ++i) {
1923 char part[2] = {char((*(utf16 + i)) >> 8), char((*(utf16 + i)) & 0xff)};
1924 for(int j=0; j < 2; ++j) {
1925 if (part[j] == '(' || part[j] == ')' || part[j] == '\\')
1927 array.append(part[j]);
1935 // For strings up to 10000 bytes only !
1936 void QPdfEnginePrivate::xprintf(const char* fmt, ...)
1941 const int msize = 10000;
1945 va_start(args, fmt);
1946 int bufsize = qvsnprintf(buf, msize, fmt, args);
1948 Q_ASSERT(bufsize<msize);
1952 stream->writeRawData(buf, bufsize);
1953 streampos += bufsize;
1956 int QPdfEnginePrivate::writeCompressed(QIODevice *dev)
1958 #ifndef QT_NO_COMPRESS
1960 int size = QPdfPage::chunkSize();
1963 zStruct.zalloc = Z_NULL;
1964 zStruct.zfree = Z_NULL;
1965 zStruct.opaque = Z_NULL;
1966 if (::deflateInit(&zStruct, Z_DEFAULT_COMPRESSION) != Z_OK) {
1967 qWarning("QPdfStream::writeCompressed: Error in deflateInit()");
1970 zStruct.avail_in = 0;
1973 while (!dev->atEnd() || zStruct.avail_in != 0) {
1974 if (zStruct.avail_in == 0) {
1975 in = dev->read(size);
1976 zStruct.avail_in = in.size();
1977 zStruct.next_in = reinterpret_cast<unsigned char*>(in.data());
1978 if (in.size() <= 0) {
1979 qWarning("QPdfStream::writeCompressed: Error in read()");
1980 ::deflateEnd(&zStruct);
1984 zStruct.next_out = reinterpret_cast<unsigned char*>(out.data());
1985 zStruct.avail_out = out.size();
1986 if (::deflate(&zStruct, 0) != Z_OK) {
1987 qWarning("QPdfStream::writeCompressed: Error in deflate()");
1988 ::deflateEnd(&zStruct);
1991 int written = out.size() - zStruct.avail_out;
1992 stream->writeRawData(out.constData(), written);
1993 streampos += written;
1998 zStruct.next_out = reinterpret_cast<unsigned char*>(out.data());
1999 zStruct.avail_out = out.size();
2000 ret = ::deflate(&zStruct, Z_FINISH);
2001 if (ret != Z_OK && ret != Z_STREAM_END) {
2002 qWarning("QPdfStream::writeCompressed: Error in deflate()");
2003 ::deflateEnd(&zStruct);
2006 int written = out.size() - zStruct.avail_out;
2007 stream->writeRawData(out.constData(), written);
2008 streampos += written;
2010 } while (ret == Z_OK);
2012 ::deflateEnd(&zStruct);
2020 while (!dev->atEnd()) {
2021 arr = dev->read(QPdfPage::chunkSize());
2022 stream->writeRawData(arr.constData(), arr.size());
2023 streampos += arr.size();
2030 int QPdfEnginePrivate::writeCompressed(const char *src, int len)
2032 #ifndef QT_NO_COMPRESS
2034 uLongf destLen = len + len/100 + 13; // zlib requirement
2035 Bytef* dest = new Bytef[destLen];
2036 if (Z_OK == ::compress(dest, &destLen, (const Bytef*) src, (uLongf)len)) {
2037 stream->writeRawData((const char*)dest, destLen);
2039 qWarning("QPdfStream::writeCompressed: Error in compress()");
2047 stream->writeRawData(src,len);
2053 int QPdfEnginePrivate::writeImage(const QByteArray &data, int width, int height, int depth,
2054 int maskObject, int softMaskObject, bool dct)
2056 int image = addXrefEntry(-1);
2061 "/Height %d\n", width, height);
2064 xprintf("/ImageMask true\n"
2067 xprintf("/BitsPerComponent 8\n"
2068 "/ColorSpace %s\n", (depth == 32) ? "/DeviceRGB" : "/DeviceGray");
2071 xprintf("/Mask %d 0 R\n", maskObject);
2072 if (softMaskObject > 0)
2073 xprintf("/SMask %d 0 R\n", softMaskObject);
2075 int lenobj = requestObject();
2076 xprintf("/Length %d 0 R\n", lenobj);
2077 if (interpolateImages)
2078 xprintf("/Interpolate true\n");
2081 //qDebug() << "DCT";
2082 xprintf("/Filter /DCTDecode\n>>\nstream\n");
2084 len = data.length();
2087 xprintf("/Filter /FlateDecode\n>>\nstream\n");
2089 xprintf(">>\nstream\n");
2090 len = writeCompressed(data);
2092 xprintf("endstream\n"
2094 addXrefEntry(lenobj);
2100 #ifdef USE_NATIVE_GRADIENTS
2101 int QPdfEnginePrivate::gradientBrush(const QBrush &b, const QMatrix &matrix, int *gStateObject)
2103 const QGradient *gradient = b.gradient();
2107 QTransform inv = matrix.inverted();
2108 QPointF page_rect[4] = { inv.map(QPointF(0, 0)),
2109 inv.map(QPointF(width_, 0)),
2110 inv.map(QPointF(0, height_)),
2111 inv.map(QPointF(width_, height_)) };
2113 bool opaque = b.isOpaque();
2116 QByteArray alphaShader;
2117 if (gradient->type() == QGradient::LinearGradient) {
2118 const QLinearGradient *lg = static_cast<const QLinearGradient *>(gradient);
2119 shader = QPdf::generateLinearGradientShader(lg, page_rect);
2121 alphaShader = QPdf::generateLinearGradientShader(lg, page_rect, true);
2126 int shaderObject = addXrefEntry(-1);
2130 QPdf::ByteStream s(&str);
2134 "/Shading " << shaderObject << "0 R\n"
2141 << matrix.dy() << "]\n";
2145 int patternObj = addXrefEntry(-1);
2147 currentPage->patterns.append(patternObj);
2151 QGradientStops stops = gradient->stops();
2152 int a = stops.at(0).second.alpha();
2153 for (int i = 1; i < stops.size(); ++i) {
2154 if (stops.at(i).second.alpha() != a) {
2160 *gStateObject = addConstantAlphaObject(stops.at(0).second.alpha());
2162 int alphaShaderObject = addXrefEntry(-1);
2166 QPdf::ByteStream c(&content);
2167 c << "/Shader" << alphaShaderObject << "sh\n";
2170 QPdf::ByteStream f(&form);
2174 "/BBox [0 0 " << width_ << height_ << "]\n"
2175 "/Group <</S /Transparency >>\n"
2177 "/Shading << /Shader" << alphaShaderObject << alphaShaderObject << "0 R >>\n"
2180 f << "/Length " << content.length() << "\n"
2187 int softMaskFormObject = addXrefEntry(-1);
2189 *gStateObject = addXrefEntry(-1);
2190 xprintf("<< /SMask << /S /Alpha /G %d 0 R >> >>\n"
2191 "endobj\n", softMaskFormObject);
2192 currentPage->graphicStates.append(*gStateObject);
2200 int QPdfEnginePrivate::addConstantAlphaObject(int brushAlpha, int penAlpha)
2202 if (brushAlpha == 255 && penAlpha == 255)
2204 int object = alphaCache.value(QPair<uint, uint>(brushAlpha, penAlpha), 0);
2206 object = addXrefEntry(-1);
2207 QByteArray alphaDef;
2208 QPdf::ByteStream s(&alphaDef);
2209 s << "<<\n/ca " << (brushAlpha/qreal(255.)) << '\n';
2210 s << "/CA " << (penAlpha/qreal(255.)) << "\n>>";
2211 xprintf("%s\nendobj\n", alphaDef.constData());
2212 alphaCache.insert(QPair<uint, uint>(brushAlpha, penAlpha), object);
2214 if (currentPage->graphicStates.indexOf(object) < 0)
2215 currentPage->graphicStates.append(object);
2220 int QPdfEnginePrivate::addBrushPattern(const QTransform &m, bool *specifyColor, int *gStateObject)
2222 int paintType = 2; // Uncolored tiling
2226 *specifyColor = true;
2229 QTransform matrix = m;
2230 matrix.translate(brushOrigin.x(), brushOrigin.y());
2231 matrix = matrix * pageMatrix();
2232 //qDebug() << brushOrigin << matrix;
2234 Qt::BrushStyle style = brush.style();
2235 if (style == Qt::LinearGradientPattern) {// && style <= Qt::ConicalGradientPattern) {
2236 #ifdef USE_NATIVE_GRADIENTS
2237 *specifyColor = false;
2238 return gradientBrush(b, matrix, gStateObject);
2244 if ((!brush.isOpaque() && brush.style() < Qt::LinearGradientPattern) || opacity != 1.0)
2245 *gStateObject = addConstantAlphaObject(qRound(brush.color().alpha() * opacity),
2246 qRound(pen.color().alpha() * opacity));
2248 int imageObject = -1;
2249 QByteArray pattern = QPdf::patternForBrush(brush);
2250 if (pattern.isEmpty()) {
2251 if (brush.style() != Qt::TexturePattern)
2253 QImage image = brush.texture().toImage();
2255 imageObject = addImage(image, &bitmap, brush.texture().cacheKey());
2256 if (imageObject != -1) {
2257 QImage::Format f = image.format();
2258 if (f != QImage::Format_MonoLSB && f != QImage::Format_Mono) {
2259 paintType = 1; // Colored tiling
2260 *specifyColor = false;
2264 QTransform m(w, 0, 0, -h, 0, h);
2265 QPdf::ByteStream s(&pattern);
2266 s << QPdf::generateMatrix(m);
2267 s << "/Im" << imageObject << " Do\n";
2272 QPdf::ByteStream s(&str);
2276 "/PaintType " << paintType << "\n"
2278 "/BBox [0 0 " << w << h << "]\n"
2279 "/XStep " << w << "\n"
2280 "/YStep " << h << "\n"
2287 << matrix.dy() << "]\n"
2288 "/Resources \n<< "; // open resource tree
2289 if (imageObject > 0) {
2290 s << "/XObject << /Im" << imageObject << ' ' << imageObject << "0 R >> ";
2293 "/Length " << pattern.length() << "\n"
2300 int patternObj = addXrefEntry(-1);
2302 currentPage->patterns.append(patternObj);
2307 * Adds an image to the pdf and return the pdf-object id. Returns -1 if adding the image failed.
2309 int QPdfEnginePrivate::addImage(const QImage &img, bool *bitmap, qint64 serial_no)
2314 int object = imageCache.value(serial_no);
2319 QImage::Format format = image.format();
2320 if (image.depth() == 1 && *bitmap && img.colorTable().size() == 2
2321 && img.colorTable().at(0) == QColor(Qt::black).rgba()
2322 && img.colorTable().at(1) == QColor(Qt::white).rgba())
2324 if (format == QImage::Format_MonoLSB)
2325 image = image.convertToFormat(QImage::Format_Mono);
2326 format = QImage::Format_Mono;
2329 if (format != QImage::Format_RGB32 && format != QImage::Format_ARGB32) {
2330 image = image.convertToFormat(QImage::Format_ARGB32);
2331 format = QImage::Format_ARGB32;
2335 int w = image.width();
2336 int h = image.height();
2337 int d = image.depth();
2339 if (format == QImage::Format_Mono) {
2340 int bytesPerLine = (w + 7) >> 3;
2342 data.resize(bytesPerLine * h);
2343 char *rawdata = data.data();
2344 for (int y = 0; y < h; ++y) {
2345 memcpy(rawdata, image.scanLine(y), bytesPerLine);
2346 rawdata += bytesPerLine;
2348 object = writeImage(data, w, h, d, 0, 0);
2350 QByteArray softMaskData;
2352 QByteArray imageData;
2353 bool hasAlpha = false;
2354 bool hasMask = false;
2356 if (QImageWriter::supportedImageFormats().contains("jpeg") && !grayscale) {
2357 QBuffer buffer(&imageData);
2358 QImageWriter writer(&buffer, "jpeg");
2359 writer.setQuality(94);
2360 writer.write(image);
2363 if (format != QImage::Format_RGB32) {
2364 softMaskData.resize(w * h);
2365 uchar *sdata = (uchar *)softMaskData.data();
2366 for (int y = 0; y < h; ++y) {
2367 const QRgb *rgb = (const QRgb *)image.scanLine(y);
2368 for (int x = 0; x < w; ++x) {
2369 uchar alpha = qAlpha(*rgb);
2371 hasMask |= (alpha < 255);
2372 hasAlpha |= (alpha != 0 && alpha != 255);
2378 imageData.resize(grayscale ? w * h : 3 * w * h);
2379 uchar *data = (uchar *)imageData.data();
2380 softMaskData.resize(w * h);
2381 uchar *sdata = (uchar *)softMaskData.data();
2382 for (int y = 0; y < h; ++y) {
2383 const QRgb *rgb = (const QRgb *)image.scanLine(y);
2385 for (int x = 0; x < w; ++x) {
2386 *(data++) = qGray(*rgb);
2387 uchar alpha = qAlpha(*rgb);
2389 hasMask |= (alpha < 255);
2390 hasAlpha |= (alpha != 0 && alpha != 255);
2394 for (int x = 0; x < w; ++x) {
2395 *(data++) = qRed(*rgb);
2396 *(data++) = qGreen(*rgb);
2397 *(data++) = qBlue(*rgb);
2398 uchar alpha = qAlpha(*rgb);
2400 hasMask |= (alpha < 255);
2401 hasAlpha |= (alpha != 0 && alpha != 255);
2406 if (format == QImage::Format_RGB32)
2407 hasAlpha = hasMask = false;
2410 int softMaskObject = 0;
2412 softMaskObject = writeImage(softMaskData, w, h, 8, 0, 0);
2413 } else if (hasMask) {
2414 // dither the soft mask to 1bit and add it. This also helps PDF viewers
2415 // without transparency support
2416 int bytesPerLine = (w + 7) >> 3;
2417 QByteArray mask(bytesPerLine * h, 0);
2418 uchar *mdata = (uchar *)mask.data();
2419 const uchar *sdata = (const uchar *)softMaskData.constData();
2420 for (int y = 0; y < h; ++y) {
2421 for (int x = 0; x < w; ++x) {
2423 mdata[x>>3] |= (0x80 >> (x&7));
2426 mdata += bytesPerLine;
2428 maskObject = writeImage(mask, w, h, 1, 0, 0);
2430 object = writeImage(imageData, w, h, grayscale ? 8 : 32,
2431 maskObject, softMaskObject, dct);
2433 imageCache.insert(serial_no, object);
2437 void QPdfEnginePrivate::drawTextItem(const QPointF &p, const QTextItemInt &ti)
2441 if (ti.charFormat.isAnchor()) {
2442 qreal size = ti.fontEngine->fontDef.pixelSize;
2443 int synthesized = ti.fontEngine->synthesized();
2444 qreal stretch = synthesized & QFontEngine::SynthesizedStretch ? ti.fontEngine->fontDef.stretch/100. : 1.;
2447 // Build text rendering matrix (Trm). We need it to map the text area to user
2448 // space units on the PDF page.
2449 trans = QTransform(size*stretch, 0, 0, size, 0, 0);
2450 // Apply text matrix (Tm).
2451 trans *= QTransform(1,0,0,-1,p.x(),p.y());
2452 // Apply page displacement (Identity for first page).
2453 trans *= stroker.matrix;
2454 // Apply Current Transformation Matrix (CTM)
2455 trans *= pageMatrix();
2456 qreal x1, y1, x2, y2;
2457 trans.map(0, 0, &x1, &y1);
2458 trans.map(ti.width.toReal()/size, (ti.ascent.toReal()-ti.descent.toReal())/size, &x2, &y2);
2460 uint annot = addXrefEntry(-1);
2461 #ifdef Q_DEBUG_PDF_LINKS
2462 xprintf("<<\n/Type /Annot\n/Subtype /Link\n/Rect [%f %f %f %f]\n/Border [16 16 1]\n/A <<\n",
2464 xprintf("<<\n/Type /Annot\n/Subtype /Link\n/Rect [%f %f %f %f]\n/Border [0 0 0]\n/A <<\n",
2466 static_cast<double>(x1),
2467 static_cast<double>(y1),
2468 static_cast<double>(x2),
2469 static_cast<double>(y2));
2470 xprintf("/Type /Action\n/S /URI\n/URI (%s)\n",
2471 ti.charFormat.anchorHref().toLatin1().constData());
2472 xprintf(">>\n>>\n");
2473 xprintf("endobj\n");
2475 if (!currentPage->annotations.contains(annot)) {
2476 currentPage->annotations.append(annot);
2480 QFontEngine *fe = ti.fontEngine;
2482 QFontEngine::FaceId face_id = fe->faceId();
2483 bool noEmbed = false;
2484 if (face_id.filename.isEmpty()
2485 || (!postscript && ((fe->fsType & 0x200) /* bitmap embedding only */
2486 || (fe->fsType == 2) /* no embedding allowed */))) {
2487 *currentPage << "Q\n";
2488 q->QPaintEngine::drawTextItem(p, ti);
2489 *currentPage << "q\n";
2490 if (face_id.filename.isEmpty())
2495 QFontSubset *font = fonts.value(face_id, 0);
2497 font = new QFontSubset(fe, requestObject());
2498 font->noEmbed = noEmbed;
2500 fonts.insert(face_id, font);
2502 if (!currentPage->fonts.contains(font->object_id))
2503 currentPage->fonts.append(font->object_id);
2505 qreal size = ti.fontEngine->fontDef.pixelSize;
2507 QVarLengthArray<glyph_t> glyphs;
2508 QVarLengthArray<QFixedPoint> positions;
2509 QTransform m = QTransform::fromTranslate(p.x(), p.y());
2510 ti.fontEngine->getGlyphPositions(ti.glyphs, m, ti.flags,
2512 if (glyphs.size() == 0)
2514 int synthesized = ti.fontEngine->synthesized();
2515 qreal stretch = synthesized & QFontEngine::SynthesizedStretch ? ti.fontEngine->fontDef.stretch/100. : 1.;
2517 *currentPage << "BT\n"
2518 << "/F" << font->object_id << size << "Tf "
2519 << stretch << (synthesized & QFontEngine::SynthesizedItalic
2520 ? "0 .3 -1 0 0 Tm\n"
2521 : "0 0 -1 0 0 Tm\n");
2525 // #### implement actual text for complex languages
2526 const unsigned short *logClusters = ti.logClusters;
2530 while (end < ti.num_chars && logClusters[end] == logClusters[pos])
2532 *currentPage << "/Span << /ActualText <FEFF";
2533 for (int i = pos; i < end; ++i) {
2534 s << toHex((ushort)ti.chars[i].unicode(), buf);
2536 *currentPage << "> >>\n"
2539 int ge = end == ti.num_chars ? ti.num_glyphs : logClusters[end];
2540 for (int gs = logClusters[pos]; gs < ge; ++gs)
2541 *currentPage << toHex((ushort)ti.glyphs[gs].glyph, buf);
2542 *currentPage << "> Tj\n"
2545 } while (pos < ti.num_chars);
2549 for (int i = 0; i < glyphs.size(); ++i) {
2550 qreal x = positions[i].x.toReal();
2551 qreal y = positions[i].y.toReal();
2552 if (synthesized & QFontEngine::SynthesizedItalic)
2556 int g = font->addGlyph(glyphs[i]);
2557 *currentPage << x - last_x << last_y - y << "Td <"
2558 << QPdf::toHex((ushort)g, buf) << "> Tj\n";
2562 if (synthesized & QFontEngine::SynthesizedBold) {
2563 *currentPage << stretch << (synthesized & QFontEngine::SynthesizedItalic
2564 ? "0 .3 -1 0 0 Tm\n"
2565 : "0 0 -1 0 0 Tm\n");
2566 *currentPage << "/Span << /ActualText <> >> BDC\n";
2567 last_x = 0.5*fe->lineThickness().toReal();
2569 for (int i = 0; i < glyphs.size(); ++i) {
2570 qreal x = positions[i].x.toReal();
2571 qreal y = positions[i].y.toReal();
2572 if (synthesized & QFontEngine::SynthesizedItalic)
2576 int g = font->addGlyph(glyphs[i]);
2577 *currentPage << x - last_x << last_y - y << "Td <"
2578 << QPdf::toHex((ushort)g, buf) << "> Tj\n";
2582 *currentPage << "EMC\n";
2586 *currentPage << "ET\n";
2589 QTransform QPdfEnginePrivate::pageMatrix() const
2591 qreal scale = 72./resolution;
2592 QTransform tmp(scale, 0.0, 0.0, -scale, 0.0, height());
2594 QRect r = pageRect();
2595 tmp.translate(r.left(), r.top());
2600 void QPdfEnginePrivate::newPage()
2602 if (currentPage && currentPage->pageSize.isEmpty())
2603 currentPage->pageSize = QSize(width(), height());
2607 currentPage = new QPdfPage;
2608 currentPage->pageSize = QSize(width(), height());
2609 stroker.stream = currentPage;
2610 pages.append(requestObject());
2612 *currentPage << "/GSa gs /CSp cs /CSp CS\n"
2613 << QPdf::generateMatrix(pageMatrix())