9#include "qplatformdefs.h"
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>
18#include <qcryptographichash.h>
22#include <qimagewriter.h>
24#include <qtemporaryfile.h>
27#include <qxmlstream.h>
28#include <QtCore/private/qenumindexedarray_p.h>
38static const bool do_compress =
false;
49 Q_INIT_RESOURCE(qpdf);
54using namespace Qt::StringLiterals;
58 QPaintEngine::PaintEngineFeatures f = QPaintEngine::AllFeatures;
59 f &= ~(QPaintEngine::PorterDuff
60 | QPaintEngine::PerspectiveTransform
61 | QPaintEngine::ObjectBoundingModeGradients
62 | QPaintEngine::ConicalGradientFill);
71 if (brush.style() == Qt::SolidPattern) {
72 QColor color = brush.color();
73 if (color.alpha() != 255) {
75 brush.setColor(color);
81 if (qt_isExtendedRadialGradient(brush)) {
82 brush = QBrush(Qt::black);
86 if (brush.style() == Qt::LinearGradientPattern
87 || brush.style() == Qt::RadialGradientPattern
88 || brush.style() == Qt::ConicalGradientPattern) {
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);
96 const_cast<QGradient*>(brush.gradient())->setStops(stops);
100 if (brush.style() == Qt::TexturePattern) {
109 const char *ret = buf;
111 if (!qIsFinite(val) || std::abs(val) > std::numeric_limits<quint32>::max()) {
122 qreal frac =
std::modf(val, &val);
125 int ifrac = (
int)(frac * 1000000000);
126 if (ifrac == 1000000000) {
133 output[i] =
'0' + (ival % 10);
137 int fact = 100000000;
142 *(buf++) = output[--i];
151 *(buf++) =
'0' + ((ifrac/fact) % 10);
161 const char *ret = buf;
169 output[i] =
'0' + (val % 10);
177 *(buf++) = output[--i];
188 fileBackingEnabled(fileBacking),
189 fileBackingActive(
false),
192 dev->open(QIODevice::ReadWrite | QIODevice::Append);
197 fileBackingEnabled(fileBacking),
198 fileBackingActive(
false),
201 dev->open(QIODevice::ReadWrite);
211 if (handleDirty) prepareBuffer();
218 if (handleDirty) prepareBuffer();
219 dev->write(str, strlen(str));
225 if (handleDirty) prepareBuffer();
232 Q_ASSERT(!src.dev->isSequential());
233 if (handleDirty) prepareBuffer();
237 qint64 pos = s.dev->pos();
239 while (!s.dev->atEnd()) {
249 qt_real_to_string(val, buf);
263 qt_real_to_string(p.x(), buf);
265 qt_real_to_string(p.y(), buf);
279 dev->open(QIODevice::ReadWrite | QIODevice::Truncate);
284 Q_ASSERT(!dev->isSequential());
285 qint64 size = dev->size();
286 if (fileBackingEnabled && !fileBackingActive
289 QTemporaryFile *newFile =
new QTemporaryFile;
290 if (newFile->open()) {
292 while (!dev->atEnd()) {
293 QByteArray buf = dev->read(chunkSize());
299 fileBackingActive =
true;
302 if (dev->pos() != size) {
309#define QT_PATH_ELEMENT(elm)
314 if (!path.elementCount())
320 for (
int i = 0; i < path.elementCount(); ++i) {
321 const QPainterPath::Element &elm = path.elementAt(i);
323 case QPainterPath::MoveToElement:
325 && path.elementAt(start).x == path.elementAt(i-1).x
326 && path.elementAt(start).y == path.elementAt(i-1).y)
328 s << matrix.map(QPointF(elm.x, elm.y)) <<
"m\n";
331 case QPainterPath::LineToElement:
332 s << matrix.map(QPointF(elm.x, elm.y)) <<
"l\n";
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))
344 qFatal(
"QPdf::generatePath(), unhandled type: %d", elm.type);
348 && path.elementAt(start).x == path.elementAt(path.elementCount()-1).x
349 && path.elementAt(start).y == path.elementAt(path.elementCount()-1).y)
352 Qt::FillRule fillRule = path.fillRule();
357 op = (fillRule == Qt::WindingFill) ?
"W n\n" :
"W* n\n";
360 op = (fillRule == Qt::WindingFill) ?
"f\n" :
"f*\n";
366 op = (fillRule == Qt::WindingFill) ?
"B\n" :
"B*\n";
393 QList<qreal> dasharray = pen.dashPattern();
394 qreal w = pen.widthF();
397 for (
int i = 0; i < dasharray.size(); ++i) {
398 qreal dw = dasharray.at(i)*w;
399 if (dw < 0.0001) dw = 0.0001;
403 s << pen.dashOffset() * w;
565 int style = b.style();
566 if (style > Qt::DiagCrossPattern)
578 t->matrix.map(x, y, &x, &y);
587 t->matrix.map(x, y, &x, &y);
592 qfixed c2x, qfixed c2y,
593 qfixed ex, qfixed ey,
598 t->matrix.map(c1x, c1y, &c1x, &c1y);
599 t->matrix.map(c2x, c2y, &c2x, &c2y);
600 t->matrix.map(ex, ey, &ex, &ey);
613 stroker = &basicStroker;
614 basicStroker.setMoveToHook(moveToHook);
615 basicStroker.setLineToHook(lineToHook);
616 basicStroker.setCubicToHook(cubicToHook);
618 basicStroker.setStrokeWidth(.1);
623 if (pen.style() == Qt::NoPen) {
627 qreal w = pen.widthF();
628 bool zeroWidth = w < 0.0001;
633 basicStroker.setStrokeWidth(w);
634 basicStroker.setCapStyle(pen.capStyle());
635 basicStroker.setJoinStyle(pen.joinStyle());
636 basicStroker.setMiterLimit(pen.miterLimit());
638 QList<qreal> dashpattern = pen.dashPattern();
640 for (
int i = 0; i < dashpattern.size(); ++i)
641 dashpattern[i] *= 10.;
643 if (!dashpattern.isEmpty()) {
644 dashStroker.setDashPattern(dashpattern);
645 dashStroker.setDashOffset(pen.dashOffset());
646 stroker = &dashStroker;
648 stroker = &basicStroker;
658 stroker->strokePath(path,
this, cosmeticPen ? matrix : QTransform());
664 int isize = input.size()/4*4;
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];
685 *(out++) = base[0] +
'!';
686 *(out++) = base[1] +
'!';
687 *(out++) = base[2] +
'!';
688 *(out++) = base[3] +
'!';
689 *(out++) = base[4] +
'!';
693 int remaining = input.size() - isize;
696 for (
int i = isize; i < input.size(); ++i)
697 val = (val << 8) + in[i];
698 val <<= 8*(4-remaining);
709 for (
int i = 0; i < remaining+1; ++i)
710 *(out++) = base[i] +
'!';
714 output.resize(out-output.data());
718const char *
QPdf::toHex(ushort u,
char *buffer)
722 ushort hex = (u & 0x000f);
726 buffer[i] =
'A'+(hex-0x0a);
738 ushort hex = (u & 0x000f);
742 buffer[i] =
'A'+(hex-0x0a);
756void QPdfPage::streamImage(
int w,
int h, uint object)
758 *
this << w <<
"0 0 " << -h <<
"0 " << h <<
"cm /Im" << object <<
" Do\n";
759 if (!images.contains(object))
760 images.append(object);
764QPdfEngine::QPdfEngine(QPdfEnginePrivate &dd)
765 : QPaintEngine(dd, qt_pdf_decide_features())
769QPdfEngine::QPdfEngine()
770 : QPaintEngine(*
new QPdfEnginePrivate(), qt_pdf_decide_features())
774void QPdfEngine::setOutputFilename(
const QString &filename)
777 d->outputFileName = filename;
781void QPdfEngine::drawPoints (
const QPointF *points,
int pointCount)
788 for (
int i=0; i!=pointCount;++i) {
790 p.lineTo(points[i] + QPointF(0, 0.001));
793 bool hadBrush = d->hasBrush;
796 d->hasBrush = hadBrush;
799void QPdfEngine::drawLines (
const QLineF *lines,
int lineCount)
806 for (
int i=0; i!=lineCount;++i) {
807 p.moveTo(lines[i].p1());
808 p.lineTo(lines[i].p2());
810 bool hadBrush = d->hasBrush;
813 d->hasBrush = hadBrush;
816void QPdfEngine::drawRects (
const QRectF *rects,
int rectCount)
823 if (d->clipEnabled && d->allClipped)
825 if (!d->hasPen && !d->hasBrush)
828 if ((d->simplePen && !d->needsTransform) || !d->hasPen) {
830 if (!d->hasPen && d->needsTransform)
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";
839 for (
int i=0; i!=rectCount; ++i)
845void QPdfEngine::drawPolygon(
const QPointF *points,
int pointCount, PolygonDrawMode mode)
849 if (!points || !pointCount)
852 bool hb = d->hasBrush;
857 p.setFillRule(Qt::OddEvenFill);
861 p.setFillRule(Qt::WindingFill);
871 for (
int i = 1; i < pointCount; ++i)
874 if (mode != PolylineMode)
881void QPdfEngine::drawPath (
const QPainterPath &p)
885 if (d->clipEnabled && d->allClipped)
887 if (!d->hasPen && !d->hasBrush)
892 *d->currentPage << QPdf::generatePath(p, d->needsTransform ? d->stroker.matrix : QTransform(),
893 d->hasBrush ? QPdf::FillAndStrokePath : QPdf::StrokePath);
896 *d->currentPage << QPdf::generatePath(p, d->stroker.matrix, QPdf::FillPath);
898 *d->currentPage <<
"q\n";
900 d->brush = d->pen.brush();
902 d->stroker.strokePath(p);
903 *d->currentPage <<
"Q\n";
909void QPdfEngine::drawPixmap (
const QRectF &rectangle,
const QPixmap &pixmap,
const QRectF &sr)
911 if (sr.isEmpty() || rectangle.isEmpty() || pixmap.isNull())
917 QRect sourceRect = sr.toRect();
918 QPixmap pm = sourceRect != pixmap.rect() ? pixmap.copy(sourceRect) : pixmap;
919 QImage image = pm.toImage();
921 const bool lossless = painter()->testRenderHint(QPainter::LosslessImageRendering);
922 const int object = d->addImage(image, &bitmap, lossless, pm.cacheKey());
926 *d->currentPage <<
"q\n";
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));
931 *d->currentPage <<
"/GState" << stateObject <<
"gs\n";
933 *d->currentPage <<
"/GSa gs\n";
935 *d->currentPage <<
"/GSa gs\n";
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));
943 d->brush = d->pen.brush();
946 d->currentPage->streamImage(image.width(), image.height(), object);
947 *d->currentPage <<
"Q\n";
952void QPdfEngine::drawImage(
const QRectF &rectangle,
const QImage &image,
const QRectF &sr, Qt::ImageConversionFlags)
954 if (sr.isEmpty() || rectangle.isEmpty() || image.isNull())
958 QRect sourceRect = sr.toRect();
959 QImage im = sourceRect != image.rect() ? image.copy(sourceRect) : image;
961 const bool lossless = painter()->testRenderHint(QPainter::LosslessImageRendering);
962 const int object = d->addImage(im, &bitmap, lossless, im.cacheKey());
966 *d->currentPage <<
"q\n";
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));
971 *d->currentPage <<
"/GState" << stateObject <<
"gs\n";
973 *d->currentPage <<
"/GSa gs\n";
975 *d->currentPage <<
"/GSa gs\n";
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));
982 d->currentPage->streamImage(im.width(), im.height(), object);
983 *d->currentPage <<
"Q\n";
986void QPdfEngine::drawTiledPixmap (
const QRectF &rectangle,
const QPixmap &pixmap,
const QPointF &point)
990 bool bitmap = (pixmap.depth() == 1);
992 QPointF bo = d->brushOrigin;
995 bool hb = d->hasBrush;
998 d->brush = QBrush(pixmap);
1001 d->brush.setColor(d->pen.color());
1003 d->brushOrigin = -point;
1004 *d->currentPage <<
"q\n";
1007 drawRects(&rectangle, 1);
1008 *d->currentPage <<
"Q\n";
1013 d->brushOrigin = bo;
1016void QPdfEngine::drawTextItem(
const QPointF &p,
const QTextItem &textItem)
1020 if (!d->hasPen || (d->clipEnabled && d->allClipped))
1023 if (d->stroker.matrix.type() >= QTransform::TxProject) {
1024 QPaintEngine::drawTextItem(p, textItem);
1028 *d->currentPage <<
"q\n";
1029 if (d->needsTransform)
1030 *d->currentPage << QPdf::generateMatrix(d->stroker.matrix);
1032 bool hp = d->hasPen;
1034 QBrush b = d->brush;
1035 d->brush = d->pen.brush();
1038 const QTextItemInt &ti =
static_cast<
const QTextItemInt &>(textItem);
1039 Q_ASSERT(ti.fontEngine->type() != QFontEngine::Multi);
1040 d->drawTextItem(p, ti);
1043 *d->currentPage <<
"Q\n";
1047void QPdfEngine::drawHyperlink(
const QRectF &r,
const QUrl &url)
1054 if (d->pdfVersion == QPdfEngine::PdfVersion::PdfVersion_X4)
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]);
1067 url_esc.append(
'\0');
1070 const QRectF rr = d->pageMatrix().mapRect(r);
1071 d->xprintf(
"<<\n/Type /Annot\n/Subtype /Link\n");
1073 if (d->pdfVersion == QPdfEngine::PdfVersion::PdfVersion_A1b)
1074 d->xprintf(
"/F 4\n");
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);
1088void QPdfEngine::updateState(
const QPaintEngineState &state)
1092 QPaintEngine::DirtyFlags flags = state.state();
1094 if (flags & DirtyHints)
1095 flags |= DirtyBrush;
1097 if (flags & DirtyTransform)
1098 d->stroker.matrix = state.transform();
1100 if (flags & DirtyPen) {
1101 if (d->pdfVersion == QPdfEngine::PdfVersion::PdfVersion_A1b) {
1102 QPen pen = state.pen();
1104 QColor penColor = pen.color();
1105 if (penColor.alpha() != 255)
1106 penColor.setAlpha(255);
1107 pen.setColor(penColor);
1109 QBrush penBrush = pen.brush();
1110 removeTransparencyFromBrush(penBrush);
1111 pen.setBrush(penBrush);
1115 d->pen = state.pen();
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());
1128 if (flags & DirtyBrush) {
1129 if (d->pdfVersion == QPdfEngine::PdfVersion::PdfVersion_A1b) {
1130 QBrush brush = state.brush();
1131 removeTransparencyFromBrush(brush);
1134 d->brush = state.brush();
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;
1140 if (flags & DirtyBrushOrigin) {
1141 d->brushOrigin = state.brushOrigin();
1142 flags |= DirtyBrush;
1144 if (flags & DirtyOpacity) {
1145 d->opacity = state.opacity();
1146 if (d->simplePen && d->opacity != 1.0) {
1147 d->simplePen =
false;
1148 flags |= DirtyTransform;
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;
1159 for (
const QRect &rect : state.clipRegion())
1161 updateClipPath(path, state.clipOperation());
1162 flags |= DirtyClipPath;
1163 }
else if (flags & DirtyClipEnabled) {
1164 d->clipEnabled = state.isClipEnabled();
1167 if (ce != d->clipEnabled)
1168 flags |= DirtyClipPath;
1169 else if (!d->clipEnabled)
1170 flags &= ~DirtyClipPath;
1172 setupGraphicsState(flags);
1175void QPdfEngine::setupGraphicsState(QPaintEngine::DirtyFlags flags)
1178 if (flags & DirtyClipPath)
1179 flags |= DirtyTransform|DirtyPen|DirtyBrush;
1181 if (flags & DirtyTransform) {
1182 *d->currentPage <<
"Q\n";
1183 flags |= DirtyPen|DirtyBrush;
1186 if (flags & DirtyClipPath) {
1187 *d->currentPage <<
"Q q\n";
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;
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);
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);
1212 d->needsTransform =
true;
1215 if (flags & DirtyBrush)
1217 if (d->simplePen && (flags & DirtyPen))
1221void QPdfEngine::updateClipPath(
const QPainterPath &p, Qt::ClipOperation op)
1224 QPainterPath path = d->stroker.matrix.map(p);
1229 d->clipEnabled =
false;
1232 case Qt::ReplaceClip:
1234 d->clips.append(path);
1236 case Qt::IntersectClip:
1237 d->clips.append(path);
1242void QPdfEngine::setPen()
1245 if (d->pen.style() == Qt::NoPen)
1247 QBrush b = d->pen.brush();
1248 Q_ASSERT(b.style() == Qt::SolidPattern && b.isOpaque());
1250 d->writeColor(QPdfEnginePrivate::ColorDomain::Stroking, b.color());
1251 *d->currentPage <<
"SCN\n";
1252 *d->currentPage << d->pen.widthF() <<
"w ";
1254 int pdfCapStyle = 0;
1255 switch(d->pen.capStyle()) {
1268 *d->currentPage << pdfCapStyle <<
"J ";
1270 int pdfJoinStyle = 0;
1271 switch(d->pen.joinStyle()) {
1273 case Qt::SvgMiterJoin:
1274 *d->currentPage << qMax(qreal(1.0), d->pen.miterLimit()) <<
"M ";
1286 *d->currentPage << pdfJoinStyle <<
"j ";
1288 *d->currentPage << QPdf::generateDashes(d->pen);
1292void QPdfEngine::setBrush()
1295 Qt::BrushStyle style = d->brush.style();
1296 if (style == Qt::NoBrush)
1300 int gStateObject = 0;
1301 int patternObject = d->addBrushPattern(d->stroker.matrix, &specifyColor, &gStateObject);
1302 if (!patternObject && !specifyColor)
1305 const auto domain = patternObject ? QPdfEnginePrivate::ColorDomain::NonStrokingPattern
1306 : QPdfEnginePrivate::ColorDomain::NonStroking;
1307 d->writeColor(domain, specifyColor ? d->brush.color() : QColor());
1309 *d->currentPage <<
"/Pat" << patternObject;
1310 *d->currentPage <<
"scn\n";
1313 *d->currentPage <<
"/GState" << gStateObject <<
"gs\n";
1315 *d->currentPage <<
"/GSa gs\n";
1319bool QPdfEngine::newPage()
1326 setupGraphicsState(DirtyBrush|DirtyPen|DirtyClipPath);
1327 QFile *outfile = qobject_cast<QFile*> (d->outDevice);
1328 if (outfile && outfile->error() != QFile::NoError)
1333QPaintEngine::Type QPdfEngine::type()
const
1335 return QPaintEngine::Pdf;
1338void QPdfEngine::setResolution(
int resolution)
1341 d->resolution = resolution;
1344int QPdfEngine::resolution()
const
1346 Q_D(
const QPdfEngine);
1347 return d->resolution;
1350void QPdfEngine::setPdfVersion(PdfVersion version)
1353 d->pdfVersion = version;
1356void QPdfEngine::setDocumentXmpMetadata(
const QByteArray &xmpMetadata)
1359 d->xmpDocumentMetadata = xmpMetadata;
1362QByteArray QPdfEngine::documentXmpMetadata()
const
1364 Q_D(
const QPdfEngine);
1365 return d->xmpDocumentMetadata;
1368void QPdfEngine::setPageLayout(
const QPageLayout &pageLayout)
1371 d->m_pageLayout = pageLayout;
1374void QPdfEngine::setPageSize(
const QPageSize &pageSize)
1377 d->m_pageLayout.setPageSize(pageSize);
1380void QPdfEngine::setPageOrientation(QPageLayout::Orientation orientation)
1383 d->m_pageLayout.setOrientation(orientation);
1386void QPdfEngine::setPageMargins(
const QMarginsF &margins, QPageLayout::Unit units)
1389 d->m_pageLayout.setUnits(units);
1390 d->m_pageLayout.setMargins(margins);
1393QPageLayout QPdfEngine::pageLayout()
const
1395 Q_D(
const QPdfEngine);
1396 return d->m_pageLayout;
1400int QPdfEngine::metric(QPaintDevice::PaintDeviceMetric metricType)
const
1402 Q_D(
const QPdfEngine);
1404 switch (metricType) {
1405 case QPaintDevice::PdmWidth:
1406 val = d->m_pageLayout.paintRectPixels(d->resolution).width();
1408 case QPaintDevice::PdmHeight:
1409 val = d->m_pageLayout.paintRectPixels(d->resolution).height();
1411 case QPaintDevice::PdmDpiX:
1412 case QPaintDevice::PdmDpiY:
1413 val = d->resolution;
1415 case QPaintDevice::PdmPhysicalDpiX:
1416 case QPaintDevice::PdmPhysicalDpiY:
1419 case QPaintDevice::PdmWidthMM:
1420 val = qRound(d->m_pageLayout.paintRect(QPageLayout::Millimeter).width());
1422 case QPaintDevice::PdmHeightMM:
1423 val = qRound(d->m_pageLayout.paintRect(QPageLayout::Millimeter).height());
1425 case QPaintDevice::PdmNumColors:
1428 case QPaintDevice::PdmDepth:
1431 case QPaintDevice::PdmDevicePixelRatio:
1434 case QPaintDevice::PdmDevicePixelRatioScaled:
1435 val = 1 * QPaintDevice::devicePixelRatioFScale();
1438 qWarning(
"QPdfWriter::metric: Invalid metric command");
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),
1450 m_pageLayout(QPageSize(QPageSize::A4), QPageLayout::Portrait, QMarginsF(10, 10, 10, 10))
1455 currentPage =
nullptr;
1456 stroker.stream =
nullptr;
1460 stream =
new QDataStream;
1463bool QPdfEngine::begin(QPaintDevice *pdev)
1468 if (!d->outDevice) {
1469 if (!d->outputFileName.isEmpty()) {
1470 QFile *file =
new QFile(d->outputFileName);
1471 if (!file->open(QFile::WriteOnly|QFile::Truncate)) {
1475 d->outDevice = file;
1479 d->ownsDevice =
true;
1482 d->currentObject = 1;
1484 d->currentPage =
new QPdfPage;
1485 d->stroker.stream = d->currentPage;
1488 d->stream->setDevice(d->outDevice);
1492 d->hasBrush =
false;
1493 d->clipEnabled =
false;
1494 d->allClipped =
false;
1496 d->xrefPositions.clear();
1500 d->attachmentsRoot = 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;
1511 d->imageCache.clear();
1512 d->alphaCache.clear();
1521bool QPdfEngine::end()
1526 d->stream->setDevice(
nullptr);
1528 qDeleteAll(d->fonts);
1530 delete d->currentPage;
1531 d->currentPage =
nullptr;
1533 if (d->outDevice && d->ownsDevice) {
1534 d->outDevice->close();
1535 delete d->outDevice;
1536 d->outDevice =
nullptr;
1539 d->destCache.clear();
1540 d->fileCache.clear();
1546void QPdfEngine::addFileAttachment(
const QString &fileName,
const QByteArray &data,
const QString &mimeType)
1549 d->fileCache.push_back({fileName, data, mimeType});
1552QPdfEnginePrivate::~QPdfEnginePrivate()
1559void QPdfEnginePrivate::writeHeader()
1561 addXrefEntry(0,
false);
1563 struct VersionString {
1565 Q_IMPLICIT
constexpr VersionString(
const char (&s)[4])
1566 : data{s[0], s[1], s[2], s[3]} {}
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" },
1574 const char *verStr = mapping[pdfVersion].data;
1576 xprintf(
"%%PDF-%s\n", verStr);
1577 xprintf(
"%%\303\242\303\243\n");
1579#if QT_CONFIG(timezone)
1580 const QDateTime now = QDateTime::currentDateTime(QTimeZone::systemTimeZone());
1582 const QDateTime now = QDateTime::currentDateTimeUtc();
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:
1593 case QPdfEngine::PdfVersion::PdfVersion_A1b:
1594 case QPdfEngine::PdfVersion::PdfVersion_X4:
1595 return writeOutputIntent();
1601 catalog = addXrefEntry(-1);
1602 pageRoot = requestObject();
1603 namesRoot = requestObject();
1608 QPdf::ByteStream s(&catalog);
1610 <<
"/Type /Catalog\n"
1611 <<
"/Pages " << pageRoot <<
"0 R\n"
1612 <<
"/Names " << namesRoot <<
"0 R\n";
1614 s <<
"/Metadata " << metaDataObj <<
"0 R\n";
1616 if (outputIntentObj >= 0)
1617 s <<
"/OutputIntents [" << outputIntentObj <<
"0 R]\n";
1626 graphicsState = addXrefEntry(-1);
1628 "/Type /ExtGState\n"
1639 patternColorSpaceRGB = addXrefEntry(-1);
1640 xprintf(
"[/Pattern /DeviceRGB]\n"
1642 patternColorSpaceGrayscale = addXrefEntry(-1);
1643 xprintf(
"[/Pattern /DeviceGray]\n"
1645 patternColorSpaceCMYK = addXrefEntry(-1);
1646 xprintf(
"[/Pattern /DeviceCMYK]\n"
1650QPdfEngine::ColorModel QPdfEnginePrivate::colorModelForColor(
const QColor &color)
const
1652 switch (colorModel) {
1653 case QPdfEngine::ColorModel::RGB:
1654 case QPdfEngine::ColorModel::Grayscale:
1655 case QPdfEngine::ColorModel::CMYK:
1657 case QPdfEngine::ColorModel::Auto:
1658 switch (color.spec()) {
1659 case QColor::Invalid:
1663 case QColor::ExtendedRgb:
1664 return QPdfEngine::ColorModel::RGB;
1666 return QPdfEngine::ColorModel::CMYK;
1672 Q_UNREACHABLE_RETURN(QPdfEngine::ColorModel::RGB);
1675void QPdfEnginePrivate::writeColor(ColorDomain domain,
const QColor &color)
1679 const QPdfEngine::ColorModel actualColorModel = colorModelForColor(color);
1681 switch (actualColorModel) {
1682 case QPdfEngine::ColorModel::RGB:
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;
1692 case QPdfEngine::ColorModel::Grayscale:
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;
1702 case QPdfEngine::ColorModel::CMYK:
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;
1712 case QPdfEngine::ColorModel::Auto:
1713 Q_UNREACHABLE_RETURN();
1717 if (!color.isValid())
1720 switch (actualColorModel) {
1721 case QPdfEngine::ColorModel::RGB:
1722 *currentPage << color.redF()
1726 case QPdfEngine::ColorModel::Grayscale: {
1727 const qreal gray = qGray(color.rgba()) / 255.;
1728 *currentPage << gray;
1731 case QPdfEngine::ColorModel::CMYK:
1732 *currentPage << color.cyanF()
1737 case QPdfEngine::ColorModel::Auto:
1738 Q_UNREACHABLE_RETURN();
1742void QPdfEnginePrivate::writeInfo(
const QDateTime &date)
1744 info = addXrefEntry(-1);
1745 write(
"<<\n/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));
1754 const QTime t = date.time();
1755 const QDate d = date.date();
1757 constexpr size_t formattedDateSize = 26;
1758 char formattedDate[formattedDateSize];
1759 const int year = qBound(0, d.year(), 9999);
1760 auto printedSize = std::snprintf(formattedDate,
1762 "(D:%04d%02d%02d%02d%02d%02d",
1769 const int offset = date.offsetFromUtc();
1770 const int hours = (offset / 60) / 60;
1771 const int mins = (offset / 60) % 60;
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);
1781 std::snprintf(formattedDate + printedSize,
1782 formattedDateSize - printedSize,
1786 write(
"\n/CreationDate ");
1787 write(formattedDate);
1788 write(
"\n/ModDate ");
1789 write(formattedDate);
1791 write(
"\n/Trapped /False\n"
1796int QPdfEnginePrivate::writeXmpDocumentMetaData(
const QDateTime &date)
1798 const int metaDataObj = addXrefEntry(-1);
1799 QByteArray metaDataContent;
1801 if (!xmpDocumentMetadata.isEmpty()) {
1802 metaDataContent = xmpDocumentMetadata;
1804 const QString producer(QString::fromLatin1(
"Qt " QT_VERSION_STR));
1805 const QString metaDataDate = date.toString(Qt::ISODate);
1807 using namespace Qt::Literals;
1808 constexpr QLatin1String xmlNS =
"http://www.w3.org/XML/1998/namespace"_L1;
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;
1819 QBuffer output(&metaDataContent);
1820 output.open(QIODevice::WriteOnly);
1821 output.write(
"<?xpacket begin='' id='W5M0MpCehiHzreSzNTczkc9d'?>");
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");
1834 w.writeStartElement(adobeNS,
"xmpmeta");
1835 w.writeStartElement(rdfNS,
"RDF");
1838
1839
1840
1841
1842
1843
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();
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();
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();
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();
1890 switch (pdfVersion) {
1891 case QPdfEngine::PdfVersion::PdfVersion_1_4:
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();
1900 case QPdfEngine::PdfVersion::PdfVersion_1_6:
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();
1910 w.writeEndElement();
1911 w.writeEndElement();
1913 w.writeEndDocument();
1914 output.write(
"<?xpacket end='w'?>");
1918 "/Type /Metadata /Subtype /XML\n"
1919 "/Length %" PRIdQSIZETYPE
"\n"
1921 "stream\n", metaDataContent.size());
1922 write(metaDataContent);
1923 xprintf(
"\nendstream\n"
1929int QPdfEnginePrivate::writeOutputIntent()
1931 const int colorProfileEntry = addXrefEntry(-1);
1933 const QColorSpace profile = outputIntent.outputProfile();
1934 const QByteArray colorProfileData = profile.iccProfile();
1937 QPdf::ByteStream s(&data);
1938 int length_object = requestObject();
1942 switch (profile.colorModel()) {
1943 case QColorSpace::ColorModel::Undefined:
1944 qWarning(
"QPdfEngine: undefined color model in the output intent profile, assuming RGB");
1946 case QColorSpace::ColorModel::Rgb:
1948 s <<
"/Alternate /DeviceRGB\n";
1950 case QColorSpace::ColorModel::Gray:
1952 s <<
"/Alternate /DeviceGray\n";
1954 case QColorSpace::ColorModel::Cmyk:
1956 s <<
"/Alternate /DeviceCMYK\n";
1960 s <<
"/Length " << length_object <<
"0 R\n";
1962 s <<
"/Filter /FlateDecode\n";
1966 const int len = writeCompressed(colorProfileData);
1967 write(
"\nendstream\n"
1969 addXrefEntry(length_object);
1974 const int outputIntentEntry = addXrefEntry(-1);
1977 write(
"/Type /OutputIntent\n");
1979 switch (pdfVersion) {
1980 case QPdfEngine::PdfVersion::PdfVersion_1_4:
1981 case QPdfEngine::PdfVersion::PdfVersion_1_6:
1984 case QPdfEngine::PdfVersion::PdfVersion_A1b:
1985 write(
"/S/GTS_PDFA1\n");
1987 case QPdfEngine::PdfVersion::PdfVersion_X4:
1988 write(
"/S/GTS_PDFX\n");
1992 xprintf(
"/DestOutputProfile %d 0 R\n", colorProfileEntry);
1993 write(
"/OutputConditionIdentifier ");
1994 printString(outputIntent.outputConditionIdentifier());
1998 printString(outputIntent.outputCondition());
2001 write(
"/OutputCondition ");
2002 printString(outputIntent.outputCondition());
2005 if (
const auto registryName = outputIntent.registryName(); !registryName.isEmpty()) {
2006 write(
"/RegistryName ");
2007 printString(registryName.toString());
2015 return outputIntentEntry;
2018void QPdfEnginePrivate::writePageRoot()
2020 addXrefEntry(pageRoot);
2026 int size = pages.size();
2027 for (
int i = 0; i < size; ++i)
2028 xprintf(
"%d 0 R\n", pages[i]);
2032 xprintf(
"/Count %" PRIdQSIZETYPE
"\n", pages.size());
2034 xprintf(
"/ProcSet [/PDF /Text /ImageB /ImageC]\n"
2039void QPdfEnginePrivate::writeDestsRoot()
2041 if (destCache.isEmpty())
2044 std::map<QString,
int> destObjects;
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);
2056 destsRoot = addXrefEntry(-1);
2057 xprintf(
"<<\n/Limits [");
2058 printString(destObjects.begin()->first);
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);
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2085 result.reserve(string.size() + 2);
2087 QStringIterator it(string);
2088 while (it.hasNext()) {
2089 const char32_t uc = it.next();
2091 if (uc >= 0x20 && uc <= 0x7e)
2093 if (c ==
'(' || c ==
')' || c ==
'\\')
2094 result.append(
'\\');
2101void QPdfEnginePrivate::writeAttachmentRoot()
2103 if (fileCache.isEmpty())
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);
2113 xprintf(
"/Filter /FlateDecode\n");
2115 const int lenobj = requestObject();
2116 xprintf(
"/Length %d 0 R\n", lenobj);
2118 xprintf(
">>\nstream\n");
2119 len = writeCompressed(attachment.data);
2120 xprintf(
"\nendstream\n"
2122 addXrefEntry(lenobj);
2126 attachments.push_back(addXrefEntry(-1));
2129 write(pdfFileSpecName(attachment.fileName));
2136 printString(attachment.fileName);
2138 xprintf(
"\n/EF <</F %d 0 R>>\n"
2141 if (!attachment.mimeType.isEmpty())
2142 xprintf(
"/Subtype/%s\n",
2143 attachment.mimeType.replace(
"/"_L1,
"#2F"_L1).toLatin1().constData());
2144 xprintf(
">>\nendobj\n");
2148 attachmentsRoot = addXrefEntry(-1);
2149 xprintf(
"<</Names[");
2150 for (
int i = 0; i < size; ++i) {
2151 auto attachment = fileCache.at(i);
2155 printString(attachment.fileName);
2156 xprintf(
"%d 0 R\n", attachments.at(i));
2162void QPdfEnginePrivate::writeNamesRoot()
2164 addXrefEntry(namesRoot);
2167 if (attachmentsRoot)
2168 xprintf(
"/EmbeddedFiles %d 0 R\n", attachmentsRoot);
2171 xprintf(
"/Dests %d 0 R\n", destsRoot);
2174 xprintf(
"endobj\n");
2181 const qsizetype length = qMin(input.size(), maxLength);
2183 output.reserve(length);
2184 for (qsizetype i = 0; i < length; ++i) {
2185 const uchar c = uchar(input.at(i));
2189 case '(':
case ')':
case '<':
case '>':
case '[':
case ']':
2190 case '{':
case '}':
case '/':
case '%':
case '#':
2193 if (c >
' ' && c < 0x7f) {
2201 output += QPdf::toHex(c, hex);
2206void QPdfEnginePrivate::embedFont(QFontSubset *font)
2209 int fontObject = font->object_id;
2210 QByteArray fontData = font->toTruetype();
2213 QString fileName(
"font%1.ttf");
2214 fileName = fileName.arg(i++);
2216 ff.open(QFile::WriteOnly);
2221 int fontDescriptor = requestObject();
2222 int fontstream = requestObject();
2223 int cidfont = requestObject();
2224 int toUnicode = requestObject();
2225 int cidset = requestObject();
2227 QFontEngine::Properties properties = font->fontEngine->properties();
2229 constexpr qsizetype MaxNameLength = 127;
2230 const qsizetype subsetTagLength = 7;
2231 const QByteArray postscriptName = qt_toPdfName(properties.postscriptName,
2232 MaxNameLength - subsetTagLength);
2235 qreal scale = 1000/properties.emSquare.toReal();
2236 addXrefEntry(fontDescriptor);
2237 QByteArray descriptor;
2238 QPdf::ByteStream s(&descriptor);
2239 s <<
"<< /Type /FontDescriptor\n"
2241 int tag = fontDescriptor;
2242 for (
int i = 0; i < 5; ++i) {
2243 s << (
char)(
'A' + (tag % 26));
2246 s <<
'+' << postscriptName <<
"\n"
2247 "/Flags " << 4 <<
"\n"
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"
2264 addXrefEntry(fontstream);
2266 QPdf::ByteStream s(&header);
2268 int length_object = requestObject();
2270 "/Length1 " << fontData.size() <<
"\n"
2271 "/Length " << length_object <<
"0 R\n";
2273 s <<
"/Filter /FlateDecode\n";
2277 int len = writeCompressed(fontData);
2278 write(
"\nendstream\n"
2280 addXrefEntry(length_object);
2285 addXrefEntry(cidfont);
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() <<
2300 addXrefEntry(toUnicode);
2301 QByteArray touc = font->createToUnicodeMap();
2302 xprintf(
"<< /Length %" PRIdQSIZETYPE
" >>\n"
2303 "stream\n", touc.size());
2305 write(
"\nendstream\n"
2309 addXrefEntry(fontObject);
2311 QPdf::ByteStream s(&font);
2312 s <<
"<< /Type /Font\n"
2314 "/BaseFont /" << postscriptName <<
"\n"
2315 "/Encoding /Identity-H\n"
2316 "/DescendantFonts [" << cidfont <<
"0 R]\n"
2317 "/ToUnicode " << toUnicode <<
"0 R"
2323 QByteArray cidSetStream(font->nGlyphs() / 8 + 1, 0);
2324 int byteCounter = 0;
2326 for (qsizetype i = 0; i < font->nGlyphs(); ++i) {
2327 cidSetStream.data()[byteCounter] |= (1 << (7 - bitCounter));
2330 if (bitCounter == 8) {
2336 addXrefEntry(cidset);
2338 xprintf(
"/Length %" PRIdQSIZETYPE
"\n", cidSetStream.size());
2340 xprintf(
"stream\n");
2341 write(cidSetStream);
2342 xprintf(
"\nendstream\n");
2343 xprintf(
"endobj\n");
2347qreal QPdfEnginePrivate::calcUserUnit()
const
2350 if (pdfVersion < QPdfEngine::PdfVersion::PdfVersion_1_6)
2353 const int maxLen = qMax(currentPage->pageSize.width(), currentPage->pageSize.height());
2354 if (maxLen <= 14400)
2358 return qMin(maxLen / 14400.0, 75000.0);
2361void QPdfEnginePrivate::writeFonts()
2363 for (QHash<QFontEngine::FaceId, QFontSubset *>::iterator it = fonts.begin(); it != fonts.end(); ++it) {
2370void QPdfEnginePrivate::writePage()
2375 *currentPage <<
"Q Q\n";
2377 uint pageStream = requestObject();
2378 uint pageStreamLength = requestObject();
2379 uint resources = requestObject();
2380 uint annots = requestObject();
2382 qreal userUnit = calcUserUnit();
2384 addXrefEntry(pages.constLast());
2387 const QByteArray formattedPageWidth = QByteArray::number(currentPage->pageSize.width() / userUnit,
'f');
2388 const QByteArray formattedPageHeight = QByteArray::number(currentPage->pageSize.height() / userUnit,
'f');
2393 "/Contents %d 0 R\n"
2394 "/Resources %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());
2404 if (pdfVersion >= QPdfEngine::PdfVersion::PdfVersion_1_6)
2405 xprintf(
"/UserUnit %s\n", QByteArray::number(userUnit,
'f').constData());
2410 addXrefEntry(resources);
2415 "/PCSpcmyk %d 0 R\n"
2417 "/CSpg /DeviceGray\n"
2418 "/CSpcmyk /DeviceCMYK\n"
2422 patternColorSpaceRGB,
2423 patternColorSpaceGrayscale,
2424 patternColorSpaceCMYK,
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));
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));
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]);
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));
2450 addXrefEntry(annots);
2452 for (
int i = 0; i<currentPage->annotations.size(); ++i) {
2453 xprintf(
"%d 0 R ", currentPage->annotations.at(i));
2455 xprintf(
"]\nendobj\n");
2457 addXrefEntry(pageStream);
2459 "/Length %d 0 R\n", pageStreamLength);
2461 xprintf(
"/Filter /FlateDecode\n");
2464 xprintf(
"stream\n");
2465 QIODevice *content = currentPage->stream();
2466 int len = writeCompressed(content);
2467 xprintf(
"\nendstream\n"
2470 addXrefEntry(pageStreamLength);
2471 xprintf(
"%d\nendobj\n",len);
2474void QPdfEnginePrivate::writeTail()
2480 writeAttachmentRoot();
2483 addXrefEntry(xrefPositions.size(),
false);
2485 "0 %" PRIdQSIZETYPE
"\n"
2486 "%010d 65535 f \n", xrefPositions.size()-1, xrefPositions[0]);
2488 for (
int i = 1; i < xrefPositions.size()-1; ++i)
2489 xprintf(
"%010d 00000 n \n", xrefPositions[i]);
2493 QPdf::ByteStream s(&trailer);
2497 <<
"/Size " << xrefPositions.size() - 1 <<
"\n"
2498 <<
"/Info " << info <<
"0 R\n"
2499 <<
"/Root " << catalog <<
"0 R\n";
2501 const QByteArray id = documentId.toString(QUuid::WithoutBraces).toUtf8().toHex();
2502 s <<
"/ID [ <" << id <<
"> <" << id <<
"> ]\n";
2505 <<
"startxref\n" << xrefPositions.constLast() <<
"\n"
2512int QPdfEnginePrivate::addXrefEntry(
int object,
bool printostr)
2515 object = requestObject();
2517 if (object>=xrefPositions.size())
2518 xrefPositions.resize(object+1);
2520 xrefPositions[object] = streampos;
2522 xprintf(
"%d 0 obj\n",object);
2527void QPdfEnginePrivate::printString(QStringView string)
2529 if (string.isEmpty()) {
2537 QByteArray array(
"(\xfe\xff");
2538 const char16_t *utf16 = string.utf16();
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] ==
'\\')
2545 array.append(part[j]);
2553void QPdfEnginePrivate::xprintf(
const char* fmt, ...)
2558 const int msize = 10000;
2562 va_start(args, fmt);
2563 int bufsize = std::vsnprintf(buf, msize, fmt, args);
2566 if (Q_LIKELY(bufsize < msize)) {
2567 stream->writeRawData(buf, bufsize);
2570 QScopedArrayPointer<
char> tmpbuf(
new char[bufsize + 1]);
2571 va_start(args, fmt);
2572 bufsize = std::vsnprintf(tmpbuf.data(), bufsize + 1, fmt, args);
2574 stream->writeRawData(tmpbuf.data(), bufsize);
2576 streampos += bufsize;
2579int QPdfEnginePrivate::writeCompressed(QIODevice *dev)
2581#ifndef QT_NO_COMPRESS
2583 int size = QPdfPage::chunkSize();
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()");
2593 zStruct.avail_in = 0;
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);
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);
2614 int written = out.size() - zStruct.avail_out;
2615 stream->writeRawData(out.constData(), written);
2616 streampos += written;
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);
2629 int written = out.size() - zStruct.avail_out;
2630 stream->writeRawData(out.constData(), written);
2631 streampos += written;
2633 }
while (ret == Z_OK);
2635 ::deflateEnd(&zStruct);
2643 while (!dev->atEnd()) {
2644 arr = dev->read(QPdfPage::chunkSize());
2645 stream->writeRawData(arr.constData(), arr.size());
2646 streampos += arr.size();
2653int QPdfEnginePrivate::writeCompressed(
const char *src,
int len)
2655#ifndef QT_NO_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;
2663 qWarning(
"QPdfStream::writeCompressed: Error in compress()");
2669 stream->writeRawData(src,len);
2675int QPdfEnginePrivate::writeImage(
const QByteArray &data,
int width,
int height, WriteImageOption option,
2676 int maskObject,
int softMaskObject,
bool dct,
bool isMono)
2678 int image = addXrefEntry(-1);
2683 "/Height %d\n", width, height);
2686 case WriteImageOption::Monochrome:
2688 xprintf(
"/ImageMask true\n"
2691 xprintf(
"/BitsPerComponent 1\n"
2692 "/ColorSpace /DeviceGray\n");
2695 case WriteImageOption::Grayscale:
2696 xprintf(
"/BitsPerComponent 8\n"
2697 "/ColorSpace /DeviceGray\n");
2699 case WriteImageOption::RGB:
2700 xprintf(
"/BitsPerComponent 8\n"
2701 "/ColorSpace /DeviceRGB\n");
2703 case WriteImageOption::CMYK:
2704 xprintf(
"/BitsPerComponent 8\n"
2705 "/ColorSpace /DeviceCMYK\n");
2710 xprintf(
"/Mask %d 0 R\n", maskObject);
2711 if (softMaskObject > 0)
2712 xprintf(
"/SMask %d 0 R\n", softMaskObject);
2714 int lenobj = requestObject();
2715 xprintf(
"/Length %d 0 R\n", lenobj);
2716 if (interpolateImages)
2717 xprintf(
"/Interpolate true\n");
2721 xprintf(
"/Filter /DCTDecode\n>>\nstream\n");
2726 xprintf(
"/Filter /FlateDecode\n>>\nstream\n");
2728 xprintf(
">>\nstream\n");
2729 len = writeCompressed(data);
2731 xprintf(
"\nendstream\n"
2733 addXrefEntry(lenobj);
2747void QPdfEnginePrivate::ShadingFunctionResult::writeColorSpace(QPdf::ByteStream *stream)
const
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;
2762QPdfEnginePrivate::ShadingFunctionResult
2763QPdfEnginePrivate::createShadingFunction(
const QGradient *gradient,
int from,
int to,
bool reflect,
bool alpha)
2765 QGradientStops stops = gradient->stops();
2766 if (stops.isEmpty()) {
2767 stops << QGradientStop(0, Qt::black);
2768 stops << QGradientStop(1, Qt::white);
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));
2776 const QColor referenceColor = stops.constFirst().second;
2778 switch (colorModel) {
2779 case QPdfEngine::ColorModel::RGB:
2780 case QPdfEngine::ColorModel::Grayscale:
2781 case QPdfEngine::ColorModel::CMYK:
2783 case QPdfEngine::ColorModel::Auto: {
2786 const QColor::Spec referenceSpec = referenceColor.spec();
2787 bool warned =
false;
2788 for (QGradientStop &stop : stops) {
2789 if (stop.second.spec() != referenceSpec) {
2791 qWarning(
"QPdfEngine: unable to create a gradient between colors of different spec");
2794 stop.second = stop.second.convertTo(referenceSpec);
2801 ShadingFunctionResult result;
2802 result.colorModel = colorModelForColor(referenceColor);
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);
2810 QPdf::ByteStream s(&data);
2816 s <<
"/C0 [" << stops.at(i).second.alphaF() <<
"]\n"
2817 "/C1 [" << stops.at(i + 1).second.alphaF() <<
"]\n";
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";
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";
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";
2841 case QPdfEngine::ColorModel::Auto:
2853 QList<QGradientBound> gradientBounds;
2854 gradientBounds.reserve((to - from) * (numStops - 1));
2856 for (
int step = from; step < to; ++step) {
2857 if (reflect && step % 2) {
2858 for (
int i = numStops - 1; i > 0; --i) {
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);
2864 gradientBounds << b;
2867 for (
int i = 0; i < numStops - 1; ++i) {
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);
2873 gradientBounds << b;
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;
2888 if (gradientBounds.size() > 1) {
2889 function = addXrefEntry(-1);
2891 QPdf::ByteStream s(&data);
2896 for (
int i = 1; i < gradientBounds.size(); ++i)
2897 s << gradientBounds.at(i).start;
2900 for (
int i = 0; i < gradientBounds.size(); ++i)
2901 s << (gradientBounds.at(i).reverse ?
"1 0 " :
"0 1 ");
2904 for (
int i = 0; i < gradientBounds.size(); ++i)
2905 s << gradientBounds.at(i).function <<
"0 R ";
2911 function = functions.at(0);
2913 result.function = function;
2917int QPdfEnginePrivate::generateLinearGradientShader(
const QLinearGradient *gradient,
const QTransform &matrix,
bool alpha)
2919 QPointF start = gradient->start();
2920 QPointF stop = gradient->finalStop();
2921 QPointF offset = stop - start;
2922 Q_ASSERT(gradient->coordinateMode() == QGradient::LogicalMode);
2926 bool reflect =
false;
2927 switch (gradient->spread()) {
2928 case QGradient::PadSpread:
2930 case QGradient::ReflectSpread:
2933 case QGradient::RepeatSpread: {
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()) };
2942 qreal length = offset.x()*offset.x() + offset.y()*offset.y();
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));
2954 stop = start + to * offset;
2955 start = start + from * offset;
2960 const auto shadingFunctionResult = createShadingFunction(gradient, from, to, reflect, alpha);
2963 QPdf::ByteStream s(&shader);
2968 s <<
"/ColorSpace /DeviceGray\n";
2970 shadingFunctionResult.writeColorSpace(&s);
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"
2978 int shaderObject = addXrefEntry(-1);
2980 return shaderObject;
2983int QPdfEnginePrivate::generateRadialGradientShader(
const QRadialGradient *gradient,
const QTransform &matrix,
bool alpha)
2985 QPointF p1 = gradient->center();
2986 qreal r1 = gradient->centerRadius();
2987 QPointF p0 = gradient->focalPoint();
2988 qreal r0 = gradient->focalRadius();
2990 Q_ASSERT(gradient->coordinateMode() == QGradient::LogicalMode);
2994 bool reflect =
false;
2995 switch (gradient->spread()) {
2996 case QGradient::PadSpread:
2998 case QGradient::ReflectSpread:
3001 case QGradient::RepeatSpread: {
3002 Q_ASSERT(qFuzzyIsNull(r0));
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()) };
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;
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) {
3027 p1 = QPointF(p0.x() + to*(p1.x() - p0.x()), p0.y() + to*(p1.y() - p0.y()));
3028 r1 = r0 + to*(r1 - r0);
3033 const auto shadingFunctionResult = createShadingFunction(gradient, from, to, reflect, alpha);
3036 QPdf::ByteStream s(&shader);
3041 s <<
"/ColorSpace /DeviceGray\n";
3043 shadingFunctionResult.writeColorSpace(&s);
3045 s <<
"/AntiAlias true\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"
3052 int shaderObject = addXrefEntry(-1);
3054 return shaderObject;
3057int QPdfEnginePrivate::generateGradientShader(
const QGradient *gradient,
const QTransform &matrix,
bool alpha)
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:
3067 case QGradient::NoGradient:
3073int QPdfEnginePrivate::gradientBrush(
const QBrush &b,
const QTransform &matrix,
int *gStateObject)
3075 const QGradient *gradient = b.gradient();
3077 if (!gradient || gradient->coordinateMode() != QGradient::LogicalMode)
3080 QRectF pageRect = m_pageLayout.fullRectPixels(resolution);
3082 QTransform m = b.transform() * matrix;
3083 int shaderObject = generateGradientShader(gradient, m);
3086 QPdf::ByteStream s(&str);
3090 "/Shading " << shaderObject <<
"0 R\n"
3101 int patternObj = addXrefEntry(-1);
3103 currentPage->patterns.append(patternObj);
3105 if (!b.isOpaque()) {
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) {
3116 *gStateObject = addConstantAlphaObject(stops.at(0).second.alpha());
3118 int alphaShaderObject = generateGradientShader(gradient, m,
true);
3121 QPdf::ByteStream c(&content);
3122 c <<
"/Shader" << alphaShaderObject <<
"sh\n";
3125 QPdf::ByteStream f(&form);
3129 "/BBox [0 0 " << pageRect.width() << pageRect.height() <<
"]\n"
3130 "/Group <</S /Transparency >>\n"
3132 "/Shading << /Shader" << alphaShaderObject << alphaShaderObject <<
"0 R >>\n"
3135 f <<
"/Length " << content.size() <<
"\n"
3142 int softMaskFormObject = addXrefEntry(-1);
3144 *gStateObject = addXrefEntry(-1);
3145 xprintf(
"<< /SMask << /S /Alpha /G %d 0 R >> >>\n"
3146 "endobj\n", softMaskFormObject);
3147 currentPage->graphicStates.append(*gStateObject);
3154int QPdfEnginePrivate::addConstantAlphaObject(
int brushAlpha,
int penAlpha)
3156 if (brushAlpha == 255 && penAlpha == 255)
3158 uint object = alphaCache.value(std::pair<uint, uint>(brushAlpha, penAlpha), 0);
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);
3168 if (currentPage->graphicStates.indexOf(object) < 0)
3169 currentPage->graphicStates.append(object);
3175int QPdfEnginePrivate::addBrushPattern(
const QTransform &m,
bool *specifyColor,
int *gStateObject)
3183 *specifyColor =
true;
3186 const Qt::BrushStyle style = brush.style();
3187 const bool isCosmetic = style >= Qt::Dense1Pattern && style <= Qt::DiagCrossPattern
3188 && !q->painter()->testRenderHint(QPainter::NonCosmeticBrushPatterns);
3192 matrix.translate(brushOrigin.x(), brushOrigin.y());
3193 matrix = matrix * pageMatrix();
3195 if (style == Qt::LinearGradientPattern || style == Qt::RadialGradientPattern) {
3196 *specifyColor =
false;
3197 return gradientBrush(brush, matrix, gStateObject);
3201 matrix = brush.transform() * matrix;
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));
3207 int imageObject = -1;
3208 QByteArray pattern = QPdf::patternForBrush(brush);
3209 if (pattern.isEmpty()) {
3210 if (brush.style() != Qt::TexturePattern)
3212 QImage image = brush.textureImage();
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) {
3220 *specifyColor =
false;
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";
3232 QPdf::ByteStream s(&str);
3236 "/PaintType " << paintType <<
"\n"
3238 "/BBox [0 0 " << w << h <<
"]\n"
3239 "/XStep " << w <<
"\n"
3240 "/YStep " << h <<
"\n"
3247 << matrix.dy() <<
"]\n"
3249 if (imageObject > 0) {
3250 s <<
"/XObject << /Im" << imageObject <<
' ' << imageObject <<
"0 R >> ";
3253 "/Length " << pattern.size() <<
"\n"
3260 int patternObj = addXrefEntry(-1);
3262 currentPage->patterns.append(patternObj);
3268 return colorTable.size() == 2
3269 && colorTable.at(0) == QColor(Qt::black).rgba()
3270 && colorTable.at(1) == QColor(Qt::white).rgba()
3275
3276
3277
3278int QPdfEnginePrivate::addImage(
const QImage &img,
bool *bitmap,
bool lossless, qint64 serial_no)
3283 int object = imageCache.value(serial_no);
3288 QImage::Format format = image.format();
3289 const bool grayscale = (colorModel == QPdfEngine::ColorModel::Grayscale);
3291 if (pdfVersion == QPdfEngine::PdfVersion::PdfVersion_A1b) {
3292 if (image.hasAlphaChannel()) {
3296 QImage alphaLessImage(image.width(), image.height(), QImage::Format_RGB32);
3297 alphaLessImage.setDevicePixelRatio(image.devicePixelRatioF());
3298 alphaLessImage.fill(Qt::white);
3300 QPainter p(&alphaLessImage);
3301 p.drawImage(0, 0, image);
3303 image = alphaLessImage;
3304 format = image.format();
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;
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;
3320 int w = image.width();
3321 int h = image.height();
3323 if (format == QImage::Format_Mono) {
3324 int bytesPerLine = (w + 7) >> 3;
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;
3332 object = writeImage(data, w, h, WriteImageOption::Monochrome, 0, 0,
false, is_monochrome(img.colorTable()));
3334 QByteArray softMaskData;
3336 QByteArray imageData;
3337 bool hasAlpha =
false;
3338 bool hasMask =
false;
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) {
3346 writer.setSubType(
"CMYK");
3348 writer.write(image);
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);
3359 hasMask |= (alpha < 255);
3360 hasAlpha |= (alpha != 0 && alpha != 255);
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();
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());
3377 for (
int y = 0; y < h; ++y) {
3378 uchar *start = data + y * w * 4;
3379 memcpy(start, image.constScanLine(y), bytesPerLine);
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);
3390 for (
int x = 0; x < w; ++x) {
3391 *(data++) = qGray(*rgb);
3392 uchar alpha = qAlpha(*rgb);
3394 hasMask |= (alpha < 255);
3395 hasAlpha |= (alpha != 0 && alpha != 255);
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);
3405 hasMask |= (alpha < 255);
3406 hasAlpha |= (alpha != 0 && alpha != 255);
3412 if (format == QImage::Format_RGB32 || format == QImage::Format_CMYK8888)
3413 hasAlpha = hasMask =
false;
3416 int softMaskObject = 0;
3418 softMaskObject = writeImage(softMaskData, w, h, WriteImageOption::Grayscale, 0, 0);
3419 }
else if (hasMask) {
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) {
3429 mdata[x>>3] |= (0x80 >> (x&7));
3432 mdata += bytesPerLine;
3434 maskObject = writeImage(mask, w, h, WriteImageOption::Monochrome, 0, 0);
3437 const WriteImageOption option = [&]() {
3439 return WriteImageOption::Grayscale;
3440 if (format == QImage::Format_CMYK8888)
3441 return WriteImageOption::CMYK;
3442 return WriteImageOption::RGB;
3445 object = writeImage(imageData, w, h, option,
3446 maskObject, softMaskObject, dct);
3448 imageCache.insert(serial_no, object);
3452void QPdfEnginePrivate::drawTextItem(
const QPointF &p,
const QTextItemInt &ti)
3456 const bool isLink = ti.charFormat.hasProperty(QTextFormat::AnchorHref);
3457 const bool isAnchor = ti.charFormat.hasProperty(QTextFormat::AnchorName);
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));
3471 trans = QTransform(size*stretch, 0, 0, size, 0, 0);
3473 trans *= QTransform(1,0,0,-1,p.x(),p.y());
3475 trans *= stroker.matrix;
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);
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");
3492 if (pdfVersion == QPdfEngine::PdfVersion::PdfVersion_A1b)
3496 write(rectData.constData());
3497#ifdef Q_DEBUG_PDF_LINKS
3498 xprintf(
"]\n/Border [16 16 1]\n");
3500 xprintf(
"]\n/Border [0 0 0]\n");
3502 const QString link = ti.charFormat.anchorHref();
3503 const bool isInternal = link.startsWith(QLatin1Char(
'#'));
3506 xprintf(
"/Type /Action\n/S /URI\n/URI (%s)\n", link.toLatin1().constData());
3510 printString(link.sliced(1));
3514 xprintf(
"endobj\n");
3516 if (!currentPage->annotations.contains(annot)) {
3517 currentPage->annotations.append(annot);
3520 const QString anchor = ti.charFormat.anchorNames().constFirst();
3521 const uint curPage = pages.last();
3522 destCache.append(DestInfo({ anchor, curPage, QPointF(x1, y2) }));
3526 QFontEngine *fe = ti.fontEngine;
3528 QFontEngine::FaceId face_id = fe->faceId();
3529 bool noEmbed =
false;
3531 || face_id.filename.isEmpty()
3532 || fe->fsType & 0x200
3534 || fe->isColorFont()) {
3535 *currentPage <<
"Q\n";
3536 q->QPaintEngine::drawTextItem(p, ti);
3537 *currentPage <<
"q\n";
3541 if (face_id.filename.isEmpty() || fe->isColorFont())
3546 QFontSubset *font = fonts.value(face_id,
nullptr);
3548 font =
new QFontSubset(fe, requestObject());
3549 font->noEmbed = noEmbed;
3551 fonts.insert(face_id, font);
3553 if (!currentPage->fonts.contains(font->object_id))
3554 currentPage->fonts.append(font->object_id);
3556 qreal size = ti.fontEngine->fontDef.pixelSize;
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,
3563 if (glyphs.size() == 0)
3565 int synthesized = ti.fontEngine->synthesized();
3566 qreal stretch = synthesized & QFontEngine::SynthesizedStretch ? ti.fontEngine->fontDef.stretch/100. : 1.;
3567 Q_ASSERT(stretch > qreal(0));
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");
3578 const unsigned short *logClusters = ti.logClusters;
3582 while (end < ti.num_chars && logClusters[end] == logClusters[pos])
3584 *currentPage <<
"/Span << /ActualText <FEFF";
3585 for (
int i = pos; i < end; ++i) {
3586 s << toHex((ushort)ti.chars[i].unicode(), buf);
3588 *currentPage <<
"> >>\n"
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"
3597 }
while (pos < ti.num_chars);
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)
3608 qsizetype g = font->addGlyph(glyphs[i]);
3609 *currentPage << x - last_x << last_y - y <<
"Td <"
3610 << QPdf::toHex((ushort)g, buf) <<
"> Tj\n";
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();
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)
3628 qsizetype g = font->addGlyph(glyphs[i]);
3629 *currentPage << x - last_x << last_y - y <<
"Td <"
3630 << QPdf::toHex((ushort)g, buf) <<
"> Tj\n";
3634 *currentPage <<
"EMC\n";
3638 *currentPage <<
"ET\n";
3641QTransform QPdfEnginePrivate::pageMatrix()
const
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());
3653void QPdfEnginePrivate::newPage()
3655 if (currentPage && currentPage->pageSize.isEmpty())
3656 currentPage->pageSize = m_pageLayout.fullRectPoints().size();
3660 currentPage =
new QPdfPage;
3661 currentPage->pageSize = m_pageLayout.fullRectPoints().size();
3662 stroker.stream = currentPage;
3663 pages.append(requestObject());
3665 *currentPage <<
"/GSa gs /CSp cs /CSp CS\n"
3666 << QPdf::generateMatrix(pageMatrix())
ByteStream(QByteArray *ba, bool fileBacking=false)
ByteStream(bool fileBacking=false)
static int maxMemorySize()
const char * toHex(ushort u, char *buffer)
QByteArray generatePath(const QPainterPath &path, const QTransform &matrix, PathFlags flags)
QByteArray ascii85Encode(const QByteArray &input)
QByteArray generateDashes(const QPen &pen)
QByteArray patternForBrush(const QBrush &b)
QByteArray generateMatrix(const QTransform &matrix)
Q_GUI_EXPORT bool qt_isExtendedRadialGradient(const QBrush &brush)
const char * qt_int_to_string(int val, char *buf)
static void initResources()
static bool is_monochrome(const QList< QRgb > &colorTable)
Q_DECLARE_TYPEINFO(QGradientBound, Q_PRIMITIVE_TYPE)
static void removeTransparencyFromBrush(QBrush &brush)
static void lineToHook(qfixed x, qfixed y, void *data)
static QByteArray qt_toPdfName(const QByteArray &input, qsizetype maxLength)
static QByteArray pdfFileSpecName(QStringView string)
const char * qt_real_to_string(qreal val, char *buf)
constexpr QPaintEngine::PaintEngineFeatures qt_pdf_decide_features()
static const bool interpolateImages
static void moveToHook(qfixed x, qfixed y, void *data)
static const char *const pattern_for_brush[]
static void cubicToHook(qfixed c1x, qfixed c1y, qfixed c2x, qfixed c2y, qfixed ex, qfixed ey, void *data)
static const bool do_compress
void setPen(const QPen &pen, QPainter::RenderHints hints)
void strokePath(const QPainterPath &path)