Rev 22388 |
Rev 22622 |
Go to most recent revision |
Blame |
Compare with Previous |
Last modification |
View Log
| RSS feed
/*
For general Scribus (>=1.3.2) copyright and licensing information please refer
to the COPYING file provided with the program. Following this notice may exist
a copyright and/or license notice that predates the release of Scribus 1.3.2
for which a new license (GPL+exception) is in place.
*/
/***************************************************************************
pdflib_core.cpp - description
-------------------
begin : Sat Jan 19 2002
copyright : (C) 2002 by Franz Schmid
email : Franz.Schmid@altmuehlnet.de
***************************************************************************/
/***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
#if defined(_MSC_VER) && !defined(_USE_MATH_DEFINES)
#define _USE_MATH_DEFINES
#endif
#include "pdflib_core.h"
#include "scconfig.h"
#include <cmath>
#include <cstdlib>
#include <string>
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif
#include "rc4.h"
#include <QByteArray>
#include <QDateTime>
#include <QDataStream>
#include <QDebug>
#include <QDir>
#include <QFileInfo>
#include <QImage>
#include <QList>
#include <QPainterPath>
#include <QPixmap>
#include <QRect>
#include <QRegExp>
#include <QStack>
#include <QString>
#include <QTextCodec>
#include <QScopedPointer>
#include "bookmwin.h"
#include "bookmarkpalette.h"
#include "cmsettings.h"
#include "commonstrings.h"
#include "multiprogressdialog.h"
#include "page.h"
#include "pageitem.h"
#include "pageitem_textframe.h"
#include "pdfoptions.h"
#include "prefscontext.h"
#include "prefsmanager.h"
#include "sccolor.h"
#include "sccolorengine.h"
#include "scfonts.h"
#include "scpaths.h"
#include "scpattern.h"
#include "scribus.h"
#include "scribuscore.h"
#include "scribusdoc.h"
#include "scstreamfilter_flate.h"
#include "scstreamfilter_rc4.h"
#include "text/nlsconfig.h"
#include "util.h"
#include "util_file.h"
#include "util_formats.h"
#include "util_math.h"
#include "util_ghostscript.h"
using namespace std;
#if defined(_WIN32)
#undef GetObject
#endif
PDFLibCore::PDFLibCore(ScribusDoc & docu)
: QObject(&docu),
doc(docu),
ActPageP(0),
Options(doc.PDF_Options),
Bvie(0),
ucs2Codec(0),
ObjCounter(7),
ResNam("RE"),
ResCount(0),
NDnam("LI"),
NDnum(0),
KeyGen(""),
OwnerKey(""),
UserKey(""),
FileID(""),
EncryKey(""),
Encrypt(0),
KeyLen(5),
colorsToUse(),
spotNam("Spot"),
spotCount(0),
progressDialog(0),
abortExport(false),
usingGUI(ScCore->usingGUI())
{
KeyGen.resize(32);
OwnerKey.resize(32);
UserKey.resize(32);
FileID.resize(16);
EncryKey.resize(5);
Catalog.Outlines = 2;
Catalog.PageTree = 3;
Catalog.Dest = 4;
Outlines.First = 0;
Outlines.Last = 0;
Outlines.Count = 0;
Seite.ObjNum = 0;
Seite.Thumb = 0;
int kg_array[] = {0x28, 0xbf, 0x4e, 0x5e, 0x4e, 0x75, 0x8a, 0x41, 0x64, 0x00, 0x4e, 0x56, 0xff, 0xfa,
0x01, 0x08, 0x2e, 0x2e, 0x00, 0xb6, 0xd0, 0x68, 0x3e, 0x80, 0x2f, 0x0c, 0xa9, 0xfe,
0x64, 0x53, 0x69, 0x7a};
for (int a = 0; a < 32; ++a)
KeyGen[a] = kg_array[a];
if (usingGUI)
{
progressDialog = new MultiProgressDialog( tr("Saving PDF"), CommonStrings::tr_Cancel, doc.scMW());
Q_CHECK_PTR(progressDialog);
QStringList barNames, barTexts;
barNames << "EMP" << "EP" << "ECPI";
barTexts << tr("Exporting Master Page:") << tr("Exporting Page:") << tr("Exporting Items on Current Page:");
QList<bool> barsNumeric;
barsNumeric << true << true << false;
progressDialog->addExtraProgressBars(barNames, barTexts, barsNumeric);
connect(progressDialog, SIGNAL(canceled()), this, SLOT(cancelRequested()));
}
}
PDFLibCore::~PDFLibCore()
{
delete progressDialog;
}
static inline QString FToStr(double c)
{
return QString::number(c, 'f', 5);
};
bool PDFLibCore::PDF_IsPDFX()
{
if (Options.Version == PDFOptions::PDFVersion_X1a)
return true;
if (Options.Version == PDFOptions::PDFVersion_X3)
return true;
return false;
}
bool PDFLibCore::PDF_IsPDFX(PDFOptions::PDFVersion ver)
{
if (ver == PDFOptions::PDFVersion_X1a)
return true;
if (ver == PDFOptions::PDFVersion_X3)
return true;
return false;
}
bool PDFLibCore::doExport(const QString& fn, const QString& nam, int Components,
const std::vector<int> & pageNs, const QMap<int,QPixmap> & thumbs)
{
QPixmap pm;
bool ret = false, error = false;
int pc_exportpages=0;
int pc_exportmasterpages=0;
if (usingGUI)
progressDialog->show();
QMap<QString, QMap<uint, FPointArray> > usedFonts;
usedFonts.clear();
doc.getUsedFonts(usedFonts);
ucs2Codec = QTextCodec::codecForName("UTF-16");
if (!ucs2Codec)
{
// FIXME : Replace by PDF_Error() after 1.3.5 release
qDebug() << "Qt build miss UTF-16 text codec, pdf export is not possible";
return false;
}
if (PDF_Begin_Doc(fn, PrefsManager::instance()->appPrefs.AvailFonts, usedFonts, doc.scMW()->bookmarkPalette->BView))
{
QMap<int, int> pageNsMpa;
for (uint a = 0; a < pageNs.size(); ++a)
{
pageNsMpa.insert(doc.MasterNames[doc.DocPages.at(pageNs[a]-1)->MPageNam], 0);
}
if (usingGUI)
{
progressDialog->setOverallTotalSteps(pageNsMpa.count()+pageNs.size());
progressDialog->setTotalSteps("EMP", pageNsMpa.count());
progressDialog->setTotalSteps("EP", pageNs.size());
progressDialog->setOverallProgress(0);
progressDialog->setProgress("EMP", 0);
progressDialog->setProgress("EP", 0);
}
for (int ap = 0; ap < doc.MasterPages.count() && !abortExport; ++ap)
{
if (doc.MasterItems.count() != 0)
{
if (pageNsMpa.contains(ap))
{
qApp->processEvents();
if (!PDF_TemplatePage(doc.MasterPages.at(ap)))
error = abortExport = true;
++pc_exportmasterpages;
}
}
if (usingGUI)
{
progressDialog->setProgress("EMP", pc_exportmasterpages);
progressDialog->setOverallProgress(pc_exportmasterpages+pc_exportpages);
}
}
for (uint a = 0; a < pageNs.size() && !abortExport; ++a)
{
if (doc.PDF_Options.Thumbnails)
pm = thumbs[pageNs[a]];
qApp->processEvents();
if (abortExport) break;
PDF_Begin_Page(doc.DocPages.at(pageNs[a]-1), pm);
qApp->processEvents();
if (abortExport) break;
if (!PDF_ProcessPage(doc.DocPages.at(pageNs[a]-1), pageNs[a]-1, doc.PDF_Options.doClip))
error = abortExport = true;
qApp->processEvents();
if (abortExport) break;
PDF_End_Page(a);
pc_exportpages++;
if (usingGUI)
{
progressDialog->setProgress("EP", pc_exportpages);
progressDialog->setOverallProgress(pc_exportmasterpages+pc_exportpages);
}
}
ret = true;//Even when aborting we return true. Dont want that "couldnt write msg"
if (!abortExport)
{
if (PDF_IsPDFX(doc.PDF_Options.Version))
ret = PDF_End_Doc(ScCore->PrinterProfiles[doc.PDF_Options.PrintProf], nam, Components);
else
ret = PDF_End_Doc();
}
else
closeAndCleanup();
}
if (usingGUI)
progressDialog->close();
return (ret && !error);
}
const QString& PDFLibCore::errorMessage(void) const
{
return ErrorMessage;
}
bool PDFLibCore::exportAborted(void) const
{
return abortExport;
}
void PDFLibCore::StartObj(int nr)
{
for (int i=XRef.size(); i < nr; ++i)
XRef.append(0);
XRef[nr-1] = bytesWritten();
PutDoc(QString::number(nr)+ " 0 obj\n");
}
// Encode a string for inclusion in a
// PDF (literal) .
static QString PDFEncode(const QString & in)
{
QString tmp("");
for (int d = 0; d < in.length(); ++d)
{
QChar cc(in.at(d));
if ((cc == '(') || (cc == ')') || (cc == '\\'))
tmp += '\\';
else if ((cc == '\r') || (cc == '\n'))
{
tmp += (cc == '\r') ? "\\r" : "\\n";
continue;
}
tmp += cc;
}
return tmp;
}
static QString blendMode(int code)
{
switch (code)
{
case 0:
return("Normal");
break;
case 1:
return("Darken");
break;
case 2:
return("Lighten");
break;
case 3:
return("Multiply");
break;
case 4:
return("Screen");
break;
case 5:
return("Overlay");
break;
case 6:
return("HardLight");
break;
case 7:
return("SoftLight");
break;
case 8:
return("Difference");
break;
case 9:
return("Exclusion");
break;
case 10:
return("ColorDodge");
break;
case 11:
return("ColorBurn");
break;
case 12:
return("Hue");
break;
case 13:
return("Saturation");
break;
case 14:
return("Color");
break;
case 15:
return("Luminosity");
break;
default:
return "";
}
}
int PDFLibCore::fromPDFDocEncoding(int code)
{
if (code <= 23
|| (code >= 32 && code <= 127)
|| (code >= 161))
{
return code;
}
if (code == 24) return 0x02d8;
if (code == 25) return 0x02c7;
if (code == 26) return 0x02c6;
if (code == 27) return 0x02d9;
if (code == 28) return 0x02dd;
if (code == 29) return 0x02db;
if (code == 30) return 0x02da;
if (code == 31) return 0x02dc;
if (code == 128) return 0x2022;
if (code == 129) return 0x2020;
if (code == 130) return 0x2021;
if (code == 131) return 0x2026;
if (code == 132) return 0x2014;
if (code == 133) return 0x2013;
if (code == 134) return 0x0192;
if (code == 135) return 0x2044;
if (code == 136) return 0x2039;
if (code == 137) return 0x203a;
if (code == 138) return 0x2212;
if (code == 139) return 0x2030;
if (code == 140) return 0x201e;
if (code == 141) return 0x201c;
if (code == 142) return 0x201d;
if (code == 143) return 0x2018;
if (code == 144) return 0x2019;
if (code == 145) return 0x201a;
if (code == 146) return 0x2122;
if (code == 147) return 0xfb01;
if (code == 148) return 0xfb02;
if (code == 149) return 0x0141;
if (code == 150) return 0x0152;
if (code == 151) return 0x0160;
if (code == 152) return 0x0178;
if (code == 153) return 0x017d;
if (code == 154) return 0x0131;
if (code == 155) return 0x0142;
if (code == 156) return 0x0153;
if (code == 157) return 0x0161;
if (code == 158) return 0x017e;
if (code == 160) return 0x20ac;
return 0;
}
QByteArray PDFLibCore::EncodeUTF16(const QString &in)
{
// QString tmp("");
// for (int d = 0; d < in.length(); ++d)
// {
// QChar cc(in.at(d));
// if ((cc == '(') || (cc == ')') || (cc == '\\'))
// tmp += '\\';
// tmp += cc;
// }
QString tmp = in;
QByteArray cres = ucs2Codec->fromUnicode( tmp );
#ifndef WORDS_BIGENDIAN
// on little endian systems we need to swap bytes:
uchar sw;
for(int d = 0; d < cres.size()-1; d += 2)
{
sw = cres[d];
cres[d] = cres[d+1];
cres[d+1] = sw;
}
#endif
return cres;
}
QString PDFLibCore::EncStream(const QString & in, int ObjNum)
{
if (in.length() < 1)
return QString("");
else if (!Options.Encrypt)
return in;
rc4_context_t rc4;
QString tmp(in);
QByteArray us(tmp.length(), ' ');
QByteArray ou(tmp.length(), ' ');
for (int a = 0; a < tmp.length(); ++a)
us[a] = QChar(tmp.at(a)).cell();
QByteArray step1 = ComputeRC4Key(ObjNum);
rc4_init(&rc4, reinterpret_cast<uchar*>(step1.data()), qMin(KeyLen+5, 16));
rc4_encrypt(&rc4, reinterpret_cast<uchar*>(us.data()), reinterpret_cast<uchar*>(ou.data()), tmp.length());
QString uk = "";
for (int cl = 0; cl < tmp.length(); ++cl)
uk += QChar(ou[cl]);
return uk;
}
QString PDFLibCore::EncString(const QString & in, int ObjNum)
{
QString tmp;
if (in.length() < 1)
return "<>";
if (!Options.Encrypt)
{
tmp = "(" + PDFEncode(in) + ")";
return tmp;
}
rc4_context_t rc4;
QByteArray us(in.length(), ' ');
QByteArray ou(in.length(), ' ');
for (int a = 0; a < in.length(); ++a)
us[a] = static_cast<uchar>(QChar(in.at(a)).cell());
QByteArray step1 = ComputeRC4Key(ObjNum);
rc4_init(&rc4, reinterpret_cast<uchar*>(step1.data()), qMin(KeyLen+5, 16));
rc4_encrypt(&rc4, reinterpret_cast<uchar*>(us.data()), reinterpret_cast<uchar*>(ou.data()), in.length());
QString uk = "";
for (int cl = 0; cl < in.length(); ++cl)
uk += QChar(ou[cl]);
tmp = "<"+String2Hex(&uk, false)+">";
return tmp;
}
QString PDFLibCore::EncStringUTF16(const QString & in, int ObjNum)
{
if (in.length() < 1)
return "<>";
if (!Options.Encrypt)
{
QByteArray us = EncodeUTF16(in);
QString uk = "";
for (int cl = 0; cl < us.size(); ++cl)
uk += QChar(us[cl]);
return "<"+String2Hex(&uk, false)+">";
}
rc4_context_t rc4;
QByteArray us = EncodeUTF16(in);
QByteArray ou(us.size(), ' ');
QByteArray step1 = ComputeRC4Key(ObjNum);
rc4_init(&rc4, reinterpret_cast<uchar*>(step1.data()), qMin(KeyLen+5, 16));
rc4_encrypt(&rc4, reinterpret_cast<uchar*>(us.data()), reinterpret_cast<uchar*>(ou.data()), ou.size());
QString uk = "";
for (int cl = 0; cl < ou.size(); ++cl)
uk += QChar(ou[cl]);
QString tmp = "<"+String2Hex(&uk, false)+">";
return tmp;
}
bool PDFLibCore::EncodeArrayToStream(const QByteArray& in, int ObjNum)
{
if (in.size() < 1)
return true;
bool succeed = false;
if (Options.Encrypt)
{
QByteArray step1 = ComputeRC4Key(ObjNum);
ScRC4EncodeFilter rc4Encode(&outStream, step1.data(), qMin(KeyLen+5, 16));
if (rc4Encode.openFilter())
{
succeed = rc4Encode.writeData(in.data(), in.size());
succeed &= rc4Encode.closeFilter();
}
}
else
outStream.writeRawData(in, in.size());
return (outStream.status() == QDataStream::Ok);
}
int PDFLibCore::WriteImageToStream(ScImage& image, int ObjNum, bool cmyk, bool gray, bool precal)
{
bool succeed = false;
int bytesWritten = 0;
if (Options.Encrypt)
{
QByteArray step1 = ComputeRC4Key(ObjNum);
ScRC4EncodeFilter rc4Encode(&outStream, step1.data(), qMin(KeyLen+5, 16));
if (rc4Encode.openFilter())
{
if (gray)
succeed = image.writeGrayDataToFilter(&rc4Encode, precal);
else if (cmyk)
succeed = image.writeCMYKDataToFilter(&rc4Encode);
else
succeed = image.writeRGBDataToFilter(&rc4Encode);
succeed &= rc4Encode.closeFilter();
bytesWritten = rc4Encode.writtenToStream();
}
}
else
{
ScNullEncodeFilter nullEncode(&outStream);
if (nullEncode.openFilter())
{
if (gray)
succeed = image.writeGrayDataToFilter(&nullEncode, precal);
else if (cmyk)
succeed = image.writeCMYKDataToFilter(&nullEncode);
else
succeed = image.writeRGBDataToFilter(&nullEncode);
succeed &= nullEncode.closeFilter();
bytesWritten = nullEncode.writtenToStream();
}
}
return (succeed ? bytesWritten : 0);
}
int PDFLibCore::WriteJPEGImageToStream(ScImage& image, const QString& fn, int ObjNum, bool cmyk,
bool gray, bool sameFile, bool precal)
{
bool succeed = true;
int bytesWritten = 0;
QFileInfo fInfo(fn);
QString ext = fInfo.suffix().toLower();
QString jpgFileName, tmpFile;
if (extensionIndicatesJPEG(ext) && sameFile)
jpgFileName = fn;
else
{
tmpFile = QDir::toNativeSeparators(ScPaths::getTempFileDir() + "sc.jpg");
if ((gray) && (!precal))
image.convertToGray();
if (image.Convert2JPG(tmpFile, Options.Quality, cmyk, gray))
jpgFileName = tmpFile;
}
if (jpgFileName.isEmpty())
return 0;
if (Options.Encrypt)
{
succeed = false;
QByteArray step1 = ComputeRC4Key(ObjNum);
ScRC4EncodeFilter rc4Encode(&outStream, step1.data(), qMin(KeyLen+5, 16));
if (rc4Encode.openFilter())
{
succeed = copyFileToFilter(jpgFileName, rc4Encode);
succeed &= rc4Encode.closeFilter();
bytesWritten = rc4Encode.writtenToStream();
}
}
else
{
succeed &= copyFileToStream(jpgFileName, outStream);
QFileInfo jpgInfo(jpgFileName);
bytesWritten = jpgInfo.size();
}
if (!tmpFile.isEmpty() && QFile::exists(tmpFile))
QFile::remove(tmpFile);
return (succeed ? bytesWritten : 0);
}
int PDFLibCore::WriteFlateImageToStream(ScImage& image, int ObjNum, bool cmyk, bool gray, bool precal)
{
bool succeed = false;
int bytesWritten = 0;
if (Options.Encrypt)
{
QByteArray step1 = ComputeRC4Key(ObjNum);
ScRC4EncodeFilter rc4Encode(&outStream, step1.data(), qMin(KeyLen+5, 16));
ScFlateEncodeFilter flateEncode(&rc4Encode);
if (flateEncode.openFilter())
{
if (gray)
succeed = image.writeGrayDataToFilter(&flateEncode, precal);
else if (cmyk)
succeed = image.writeCMYKDataToFilter(&flateEncode);
else
succeed = image.writeRGBDataToFilter(&flateEncode);
succeed &= flateEncode.closeFilter();
bytesWritten = flateEncode.writtenToStream();
}
}
else
{
ScFlateEncodeFilter flateEncode(&outStream);
if (flateEncode.openFilter())
{
if (gray)
succeed = image.writeGrayDataToFilter(&flateEncode, precal);
else if (cmyk)
succeed = image.writeCMYKDataToFilter(&flateEncode);
else
succeed = image.writeRGBDataToFilter(&flateEncode);
succeed &= flateEncode.closeFilter();
bytesWritten = flateEncode.writtenToStream();
}
}
return (succeed ? bytesWritten : 0);
}
QString PDFLibCore::FitKey(const QString & pass)
{
QString pw(pass);
if (pw.length() < 32)
{
uint l = pw.length();
for (uint a = 0; a < 32 - l; ++a)
pw += QChar(KeyGen[a]);
}
else
pw = pw.left(32);
return pw;
}
void PDFLibCore::CalcOwnerKey(const QString & Owner, const QString & User)
{
rc4_context_t rc4;
QString pw(FitKey(User));
QString pw2(FitKey(Owner.isEmpty() ? User : Owner));
QByteArray step1(16, ' ');
step1 = ComputeMD5(pw2);
if (KeyLen > 5)
{
for (int kl = 0; kl < 50; ++kl)
step1 = ComputeMD5Sum(&step1);
}
QByteArray us(32, ' ');
QByteArray enk(16, ' ');
if (KeyLen > 5)
{
for (uint a2 = 0; a2 < 32; ++a2)
OwnerKey[a2] = QChar(pw.at(a2)).cell();
for (int rl = 0; rl < 20; rl++)
{
for (int j = 0; j < 16; j ++)
enk[j] = step1[j] ^ rl;
rc4_init(&rc4, reinterpret_cast<uchar*>(enk.data()), 16);
rc4_encrypt(&rc4, reinterpret_cast<uchar*>(OwnerKey.data()),
reinterpret_cast<uchar*>(OwnerKey.data()), 32);
}
}
else
{
for (uint a = 0; a < 32; ++a)
us[a] = static_cast<uchar>(QChar(pw.at(a)).cell());
rc4_init(&rc4, reinterpret_cast<uchar*>(step1.data()), 5);
rc4_encrypt(&rc4, reinterpret_cast<uchar*>(us.data()),
reinterpret_cast<uchar*>(OwnerKey.data()), 32);
}
}
void PDFLibCore::CalcUserKey(const QString & User, int Permission)
{
rc4_context_t rc4;
QString pw(FitKey(User));
QByteArray step1(16, ' ');
QByteArray perm(4, ' ');
uint perm_value = static_cast<uint>(Permission);
perm[0] = perm_value;
perm[1] = perm_value >> 8;
perm[2] = perm_value >> 16;
perm[3] = perm_value >> 24;
for (uint a = 0; a < 32; ++a)
pw += QChar(OwnerKey[a]);
for (uint a1 = 0; a1 < 4; ++a1)
pw += QChar(perm[a1]);
for (uint a3 = 0; a3 < 16; ++a3)
pw += QChar(FileID[a3]);
step1 = ComputeMD5(pw);
if (KeyLen > 5)
{
for (int kl = 0; kl < 50; ++kl)
step1 = ComputeMD5Sum(&step1);
EncryKey.resize(16);
}
for (int a2 = 0; a2 < KeyLen; ++a2)
EncryKey[a2] = step1[a2];
if (KeyLen > 5)
{
QString pr2("");
for (int kl3 = 0; kl3 < 32; ++kl3)
pr2 += QChar(KeyGen[kl3]);
for (uint a4 = 0; a4 < 16; ++a4)
pr2 += QChar(FileID[a4]);
step1 = ComputeMD5(pr2);
QByteArray enk(16, ' ');
for (uint a3 = 0; a3 < 16; ++a3)
UserKey[a3] = step1[a3];
for (int rl = 0; rl < 20; rl++)
{
for (int j = 0; j < 16; j ++)
enk[j] = EncryKey[j] ^ rl;
rc4_init(&rc4, reinterpret_cast<uchar*>(enk.data()), 16);
rc4_encrypt(&rc4, reinterpret_cast<uchar*>(UserKey.data()), reinterpret_cast<uchar*>(UserKey.data()), 16);
}
}
else
{
rc4_init(&rc4, reinterpret_cast<uchar*>(step1.data()), 5);
rc4_encrypt(&rc4, reinterpret_cast<uchar*>(KeyGen.data()), reinterpret_cast<uchar*>(UserKey.data()), 32);
}
}
QByteArray PDFLibCore::ComputeMD5(const QString& in)
{
uint inlen=in.length();
QByteArray TBytes(inlen, ' ');
for (uint a = 0; a < inlen; ++a)
TBytes[a] = static_cast<uchar>(QChar(in.at(a)).cell());
return ComputeMD5Sum(&TBytes);
}
QByteArray PDFLibCore::ComputeRC4Key(int ObjNum)
{
int dlen = 0;
QByteArray data(10, ' ');
if (KeyLen > 5)
data.resize(21);
for (int cd = 0; cd < KeyLen; ++cd)
{
data[cd] = EncryKey[cd];
dlen++;
}
data[dlen++] = ObjNum;
data[dlen++] = ObjNum >> 8;
data[dlen++] = ObjNum >> 16;
data[dlen++] = 0;
data[dlen++] = 0;
QByteArray rc4Key(16, ' ');
rc4Key = ComputeMD5Sum(&data);
rc4Key.resize(qMin(KeyLen+5, 16));
return rc4Key;
}
bool PDFLibCore::PDF_Begin_Doc(const QString& fn, SCFonts &AllFonts, QMap<QString, QMap<uint, FPointArray> > DocFonts, BookMView* vi)
{
Spool.setFileName(fn);
if (!Spool.open(QIODevice::WriteOnly))
return false;
outStream.setDevice(&Spool);
QString tmp;
QString ok = "";
QString uk = "";
QFileInfo fd;
QString fext;
int a;
int openActionObj = 0;
inPattern = 0;
Bvie = vi;
BookMinUse = false;
UsedFontsP.clear();
UsedFontsF.clear();
if ((Options.Version == PDFOptions::PDFVersion_15) && (Options.useLayers))
ObjCounter = 10;
else
ObjCounter = 9;
switch (Options.Version)
{
case PDFOptions::PDFVersion_X1a:
case PDFOptions::PDFVersion_X3:
case PDFOptions::PDFVersion_13:
PutDoc("%PDF-1.3\n");
break;
case PDFOptions::PDFVersion_14:
PutDoc("%PDF-1.4\n");
break;
case PDFOptions::PDFVersion_15:
PutDoc("%PDF-1.5\n");
break;
}
if ((Options.Version == PDFOptions::PDFVersion_X1a) || (Options.Version == PDFOptions::PDFVersion_X3))
ObjCounter++;
PutDoc("%\xc7\xec\x8f\xa2\n");
StartObj(1);
PutDoc("<<\n/Type /Catalog\n/Outlines 3 0 R\n/Pages 4 0 R\n/Dests 5 0 R\n/AcroForm 6 0 R\n/Names 7 0 R\n/Threads 8 0 R\n");
if ((Options.Version == PDFOptions::PDFVersion_15) && (Options.useLayers))
PutDoc("/OCProperties 9 0 R\n");
if ((Options.Version == PDFOptions::PDFVersion_X1a) || (Options.Version == PDFOptions::PDFVersion_X3))
PutDoc("/OutputIntents [ "+QString::number(ObjCounter-1)+" 0 R ]\n");
PutDoc("/PageLayout ");
switch (Options.PageLayout)
{
case PDFOptions::SinglePage:
PutDoc("/SinglePage\n");
break;
case PDFOptions::OneColumn:
PutDoc("/OneColumn\n");
break;
case PDFOptions::TwoColumnLeft:
PutDoc("/TwoColumnLeft\n");
break;
case PDFOptions::TwoColumnRight:
PutDoc("/TwoColumnRight\n");
break;
}
if (Options.displayBookmarks)
PutDoc("/PageMode /UseOutlines\n");
else if (Options.displayFullscreen)
PutDoc("/PageMode /FullScreen\n");
else if (Options.displayThumbs)
PutDoc("/PageMode /UseThumbs\n");
else if ((Options.Version == PDFOptions::PDFVersion_15) && (Options.displayLayers))
PutDoc("/PageMode /UseOC\n");
if (!Options.openAction.isEmpty())
{
openActionObj = newObject();
PutDoc("/OpenAction << /S /JavaScript /JS " + QString::number(openActionObj) + " 0 R >>\n");
}
QDate d = QDate::currentDate();
Datum = "D:";
tmp.sprintf("%4d", d.year());
tmp.replace(QRegExp(" "), "0");
Datum += tmp;
tmp.sprintf("%2d", d.month());
tmp.replace(QRegExp(" "), "0");
Datum += tmp;
tmp.sprintf("%2d", d.day());
tmp.replace(QRegExp(" "), "0");
Datum += tmp;
tmp = QTime::currentTime().toString();
tmp.replace(QRegExp(":"), "");
Datum += tmp;
/* The following code makes the resulting PDF "Reader enabled" in Acrobat Reader 8
but sadly it doesn't work with newer version, because its based on a bug in AR 8
PutDoc("/Perms\n");
PutDoc("<<\n");
PutDoc("/UR3\n");
PutDoc("<<\n");
PutDoc("/M ("+Datum+")\n");
PutDoc("/Name (Scribus "+QString(VERSION)+")\n");
PutDoc("/Reference [\n");
PutDoc("<<\n");
PutDoc("/TransformParams\n");
PutDoc("<<\n");
PutDoc("/Type /TransformParams\n");
PutDoc("/V /2.2\n");
PutDoc("/Document [/FullSave]\n");
PutDoc("/Annots [/Create/Delete/Modify/Copy/Import/Export]\n");
PutDoc("/Form [/Add/Delete/FillIn/Import/Export/SubmitStandalone/SpawnTemplate]\n");
PutDoc("/Signature [/Modify]\n");
PutDoc(">>\n");
PutDoc("/TransformMethod /UR3\n");
PutDoc("/Type /SigRef\n");
PutDoc(">>\n");
PutDoc("]\n");
PutDoc("/Type /Sig\n");
PutDoc(">>\n");
PutDoc(">>\n");
*/
PutDoc("/ViewerPreferences\n<<\n/PageDirection ");
PutDoc( Options.Binding == 0 ? "/L2R\n" : "/R2L\n");
if (Options.hideToolBar)
PutDoc("/HideToolbar true\n");
if (Options.hideMenuBar)
PutDoc("/HideMenubar true\n");
if (Options.fitWindow)
PutDoc("/FitWindow true\n");
PutDoc(" >>\n>>\nendobj\n");
QString IDg(Datum);
IDg += Options.fileName;
IDg += "Scribus "+QString(VERSION);
IDg += "Scribus PDF Library "+QString(VERSION);
IDg += doc.documentInfo.getTitle();
IDg += doc.documentInfo.getAuthor();
IDg += "/False";
FileID = ComputeMD5(IDg);
if (Options.Encrypt)
{
if ((Options.Version == PDFOptions::PDFVersion_14) || (Options.Version == PDFOptions::PDFVersion_15))
KeyLen = 16;
else
KeyLen = 5;
CalcOwnerKey(Options.PassOwner, Options.PassUser);
CalcUserKey(Options.PassUser, Options.Permissions);
for (uint cl2 = 0; cl2 < 32; ++cl2)
ok += QChar(OwnerKey[cl2]);
if (KeyLen > 5)
{
for (uint cl3 = 0; cl3 < 16; ++cl3)
uk += QChar(UserKey[cl3]);
for (uint cl3r = 0; cl3r < 16; ++cl3r)
uk += QChar(KeyGen[cl3r]);
}
else
{
for (uint cl = 0; cl < 32; ++cl)
uk += QChar(UserKey[cl]);
}
}
StartObj(2);
PutDoc("<<\n/Creator " + EncString("Scribus "+QString(VERSION), 2) + "\n");
PutDoc("/Producer " + EncString("Scribus PDF Library "+QString(VERSION), 2) + "\n");
QString docTitle = doc.documentInfo.getTitle();
if ((PDF_IsPDFX()) && (docTitle.isEmpty()))
PutDoc("/Title " + EncStringUTF16(doc.DocName, 2) + "\n");
else
PutDoc("/Title " + EncStringUTF16(doc.documentInfo.getTitle(), 2) + "\n");
PutDoc("/Author " + EncStringUTF16(doc.documentInfo.getAuthor(), 2) + "\n");
PutDoc("/Subject " + EncStringUTF16(doc.documentInfo.getSubject(), 2) + "\n");
PutDoc("/Keywords " + EncStringUTF16(doc.documentInfo.getKeywords(), 2) + "\n");
PutDoc("/CreationDate " + EncString(Datum, 2) + "\n");
PutDoc("/ModDate " + EncString(Datum, 2) + "\n");
if (Options.Version == PDFOptions::PDFVersion_X1a)
{
PutDoc("/GTS_PDFXVersion (PDF/X-1:2001)\n");
PutDoc("/GTS_PDFXConformance (PDF/X-1a:2001)\n");
}
if (Options.Version == PDFOptions::PDFVersion_X3)
PutDoc("/GTS_PDFXVersion (PDF/X-3:2002)\n");
PutDoc("/Trapped /False\n>>\nendobj\n");
for (int t = 0; t < 6; ++t)
XRef.append(bytesWritten());
if ((Options.Version == PDFOptions::PDFVersion_15) && (Options.useLayers))
XRef.append(bytesWritten());
if ((Options.Version == PDFOptions::PDFVersion_X1a) || (Options.Version == PDFOptions::PDFVersion_X3))
XRef.append(bytesWritten());
if (Options.Encrypt)
{
Encrypt = newObject();
StartObj(Encrypt);
PutDoc("<<\n/Filter /Standard\n");
PutDoc( KeyLen > 5 ? "/R 3\n/V 2\n/Length 128\n" : "/R 2\n/V 1\n");
PutDoc("/O <"+String2Hex(&ok)+">\n");
PutDoc("/U <"+String2Hex(&uk)+">\n");
PutDoc("/P "+QString::number(Options.Permissions)+"\n>>\nendobj\n");
}
if (openActionObj)
{
WritePDFString("this." + Options.openAction + "()", openActionObj);
}
QMap<QString, QMap<uint, FPointArray> > ReallyUsed;
ReallyUsed.clear();
PageItem* pgit;
QMap<int, QString> ind2PDFabr;
const QString tmpf[] = {"/Courier", "/Courier-Bold", "/Courier-Oblique", "/Courier-BoldOblique",
"/Helvetica", "/Helvetica-Bold", "/Helvetica-Oblique", "/Helvetica-BoldOblique",
"/Times-Roman", "/Times-Bold", "/Times-Italic", "/Times-BoldItalic",
"/ZapfDingbats", "/Symbol"};
size_t ar = sizeof(tmpf) / sizeof(*tmpf);
for (uint ax = 0; ax < ar; ++ax)
ind2PDFabr[ax] = tmpf[ax];
for (int c = 0; c < doc.FrameItems.count(); ++c)
{
pgit = doc.FrameItems.at(c);
if ((pgit->itemType() == PageItem::TextFrame) || (pgit->itemType() == PageItem::PathText))
{
if (pgit->isAnnotation())
{
int annotType = pgit->annotation().Type();
bool mustEmbed = ((annotType >= 2) && (annotType <= 6) && (annotType != 4));
if (pgit->annotation().Type() == 4)
StdFonts.insert("/ZapfDingbats", "");
if (pgit->itemText.length() > 0 || mustEmbed)
{
if (Options.Version < PDFOptions::PDFVersion_14)
StdFonts.insert(ind2PDFabr[pgit->annotation().Font()], "");
ReallyUsed.insert(pgit->itemText.defaultStyle().charStyle().font().replacementName(), DocFonts[pgit->itemText.defaultStyle().charStyle().font().replacementName()]);
}
}
uint start = pgit->isTextFrame() ? (uint) pgit->firstInFrame() : 0;
uint stop = pgit->isTextFrame() ? (uint) pgit->lastInFrame() + 1 : (uint) pgit->itemText.length();
for (uint e = start; e < stop; ++e)
{
ReallyUsed.insert(pgit->itemText.charStyle(e).font().replacementName(), DocFonts[pgit->itemText.charStyle(e).font().replacementName()]);
}
}
}
for (int c = 0; c < doc.MasterItems.count(); ++c)
{
pgit = doc.MasterItems.at(c);
if ((pgit->itemType() == PageItem::TextFrame) || (pgit->itemType() == PageItem::PathText))
{
if (pgit->isAnnotation())
{
int annotType = pgit->annotation().Type();
bool mustEmbed = ((annotType >= 2) && (annotType <= 6) && (annotType != 4));
if (pgit->annotation().Type() == 4)
StdFonts.insert("/ZapfDingbats", "");
if (pgit->itemText.length() > 0 || mustEmbed)
{
if (Options.Version < PDFOptions::PDFVersion_14)
StdFonts.insert(ind2PDFabr[pgit->annotation().Font()], "");
ReallyUsed.insert(pgit->itemText.defaultStyle().charStyle().font().replacementName(), DocFonts[pgit->itemText.defaultStyle().charStyle().font().replacementName()]);
}
}
uint start = pgit->isTextFrame() ? (uint) pgit->firstInFrame() : 0;
uint stop = pgit->isTextFrame() ? (uint) pgit->lastInFrame() + 1 : (uint) pgit->itemText.length();
for (uint e = start; e < stop; ++e)
{
ReallyUsed.insert(pgit->itemText.charStyle(e).font().replacementName(), DocFonts[pgit->itemText.charStyle(e).font().replacementName()]);
}
}
}
for (int d = 0; d < doc.DocItems.count(); ++d)
{
pgit = doc.DocItems.at(d);
if ((pgit->itemType() == PageItem::TextFrame) || (pgit->itemType() == PageItem::PathText))
{
if (pgit->isAnnotation())
{
int annotType = pgit->annotation().Type();
bool mustEmbed = ((annotType >= 2) && (annotType <= 6) && (annotType != 4));
if (pgit->annotation().Type() == 4)
StdFonts.insert("/ZapfDingbats", "");
if (pgit->itemText.length() > 0 || mustEmbed)
{
if (Options.Version < PDFOptions::PDFVersion_14)
StdFonts.insert(ind2PDFabr[pgit->annotation().Font()], "");
ReallyUsed.insert(pgit->itemText.defaultStyle().charStyle().font().replacementName(), DocFonts[pgit->itemText.defaultStyle().charStyle().font().replacementName()]);
}
}
uint start = pgit->isTextFrame() ? (uint) pgit->firstInFrame() : 0;
uint stop = pgit->isTextFrame() ? (uint) pgit->lastInFrame() + 1 : (uint) pgit->itemText.length();
for (uint e = start; e < stop; ++e)
{
ReallyUsed.insert(pgit->itemText.charStyle(e).font().replacementName(), DocFonts[pgit->itemText.charStyle(e).font().replacementName()]);
}
}
}
/* if (Options.docInfoMarks)
{
StdFonts.insert("/Helvetica", "");
} */
QStringList patterns = doc.getUsedPatterns();
for (int c = 0; c < patterns.count(); ++c)
{
ScPattern pa = doc.docPatterns[patterns[c]];
for (int o = 0; o < pa.items.count(); o++)
{
pgit = pa.items.at(o);
if ((pgit->itemType() == PageItem::TextFrame) || (pgit->itemType() == PageItem::PathText))
{
if (pgit->isAnnotation())
{
if (pgit->annotation().Type() == 4)
StdFonts.insert("/ZapfDingbats", "");
if (pgit->itemText.length() > 0)
{
if (Options.Version < PDFOptions::PDFVersion_14)
StdFonts.insert(ind2PDFabr[pgit->annotation().Font()], "");
ReallyUsed.insert(pgit->itemText.defaultStyle().charStyle().font().replacementName(), DocFonts[pgit->itemText.defaultStyle().charStyle().font().replacementName()]);
}
}
uint start = pgit->isTextFrame() ? (uint) pgit->firstInFrame() : 0;
uint stop = pgit->isTextFrame() ? (uint) pgit->lastInFrame() + 1 : (uint) pgit->itemText.length();
for (uint e = start; e < stop; ++e)
{
ReallyUsed.insert(pgit->itemText.charStyle(e).font().replacementName(), DocFonts[pgit->itemText.charStyle(e).font().replacementName()]);
}
}
}
}
a = 0;
QMap<QString, QString>::Iterator itStd;
for (itStd = StdFonts.begin(); itStd != StdFonts.end(); ++itStd)
{
uint fontObject = newObject();
StartObj(fontObject);
PutDoc("<<\n/Type /Font\n/Subtype /Type1\n");
PutDoc("/Name /FoStd"+QString::number(a)+"\n");
PutDoc("/BaseFont "+itStd.key()+"\n");
if (itStd.key() != "/ZapfDingbats")
{
PutDoc("/Encoding << \n");
PutDoc("/Differences [ \n");
PutDoc("24 /breve /caron /circumflex /dotaccent /hungarumlaut /ogonek /ring /tilde\n");
PutDoc("39 /quotesingle 96 /grave 128 /bullet /dagger /daggerdbl /ellipsis /emdash /endash /florin /fraction /guilsinglleft /guilsinglright\n");
PutDoc("/minus /perthousand /quotedblbase /quotedblleft /quotedblright /quoteleft /quoteright /quotesinglbase /trademark /fi /fl /Lslash /OE /Scaron\n");
PutDoc("/Ydieresis /Zcaron /dotlessi /lslash /oe /scaron /zcaron 160 /Euro 164 /currency 166 /brokenbar 168 /dieresis /copyright /ordfeminine 172 /logicalnot\n");
PutDoc("/.notdef /registered /macron /degree /plusminus /twosuperior /threesuperior /acute /mu 183 /periodcentered /cedilla /onesuperior /ordmasculine\n");
PutDoc("188 /onequarter /onehalf /threequarters 192 /Agrave /Aacute /Acircumflex /Atilde /Adieresis /Aring /AE /Ccedilla /Egrave /Eacute /Ecircumflex\n");
PutDoc("/Edieresis /Igrave /Iacute /Icircumflex /Idieresis /Eth /Ntilde /Ograve /Oacute /Ocircumflex /Otilde /Odieresis /multiply /Oslash\n");
PutDoc("/Ugrave /Uacute /Ucircumflex /Udieresis /Yacute /Thorn /germandbls /agrave /aacute /acircumflex /atilde /adieresis /aring /ae /ccedilla\n");
PutDoc("/egrave /eacute /ecircumflex /edieresis /igrave /iacute /icircumflex /idieresis /eth /ntilde /ograve /oacute /ocircumflex /otilde /odieresis\n");
PutDoc("/divide /oslash /ugrave /uacute /ucircumflex /udieresis /yacute /thorn /ydieresis\n");
PutDoc("] >>\n");
}
PutDoc(">>\nendobj\n");
Seite.FObjects["FoStd"+QString::number(a)] = fontObject;
itStd.value() = "FoStd"+QString::number(a);
a++;
}
QMap<QString,QMap<uint, FPointArray> >::Iterator it;
a = 0;
for (it = ReallyUsed.begin(); it != ReallyUsed.end(); ++it)
{
ScFace& face(AllFonts[it.key()]);
ScFace::FontFormat fformat = face.format();
if ((!face.hasNames()) || (Options.SubsetList.contains(it.key())))
{
if (face.hasNames())
{
UsedFontsP.insert(it.key(), "/Fo"+QString::number(a));
uint SubFonts = 0;
int glyphCount = 0;
double minx = 99999.9;
double miny = 99999.9;
double maxx = -99999.9;
double maxy = -99999.9;
QList<uint> glyphWidths;
QStringList charProcs;
QString encoding = "<< /Type /Encoding\n/Differences [ 0\n";
QString fon("");
QMap<uint, uint> glyphMapping;
QMap<uint,std::pair<QChar,QString> > gl;
face.glyphNames(gl);
QMap<uint,FPointArray>& RealGlyphs(it.value());
QMap<uint,FPointArray>::Iterator ig;
for (ig = RealGlyphs.begin(); ig != RealGlyphs.end(); ++ig)
{
FPoint np, np1, np2;
bool nPath = true;
fon = "";
if (ig.value().size() > 3)
{
FPointArray gly = ig.value();
QMatrix mat;
mat.scale(100.0, -100.0);
gly.map(mat);
gly.translate(0, 1000);
for (uint poi = 0; poi < gly.size()-3; poi += 4)
{
if (gly.point(poi).x() > 900000)
{
fon += "h\n";
nPath = true;
continue;
}
if (nPath)
{
np = gly.point(poi);
fon += FToStr(np.x())+" "+FToStr(np.y())+" m\n";
nPath = false;
}
np = gly.point(poi+1);
np1 = gly.point(poi+3);
np2 = gly.point(poi+2);
fon += FToStr(np.x()) + " " + FToStr(np.y()) + " " + FToStr(np1.x()) + " " + FToStr(np1.y()) + " " + FToStr(np2.x()) + " " + FToStr(np2.y()) + " c\n";
}
fon += "h f*\n";
np = getMinClipF(&gly);
np1 = getMaxClipF(&gly);
}
else
{
fon = "h";
np = FPoint(0, 0);
np1 = FPoint(0, 0);
}
fon.prepend(QString::number(qRound(np1.x())) + " 0 "+QString::number(qRound(np.x()))+" "+QString::number(qRound(np.y()))+" "+QString::number(qRound(np1.x()))+ " "+QString::number(qRound(np1.y()))+" d1\n");
minx = qMin(minx, np.x());
miny = qMin(miny, np.y());
maxx = qMax(maxx, np1.x());
maxy = qMax(maxy, np1.y());
glyphWidths.append(qRound(np1.x()));
uint charProcObject = newObject();
charProcs.append("/"+gl[ig.key()].second+" "+QString::number(charProcObject)+" 0 R\n");
encoding += "/"+gl[ig.key()].second+" ";
glyphMapping.insert(ig.key(), glyphCount + SubFonts * 256);
StartObj(charProcObject);
if (Options.Compress)
fon = CompressStr(&fon);
PutDoc("<< /Length "+QString::number(fon.length()+1));
if (Options.Compress)
PutDoc("\n/Filter /FlateDecode");
PutDoc("\n>>\nstream\n"+EncStream(fon, charProcObject)+"\nendstream\nendobj\n");
glyphCount++;
int glyphsLeft = RealGlyphs.count() - SubFonts * 256;
if ((glyphCount > 255) || (glyphCount == glyphsLeft))
{
uint fontWidths = newObject();
StartObj(fontWidths);
PutDoc("[ ");
for (int ww = 0; ww < glyphWidths.count(); ++ww)
{
PutDoc(QString::number(qRound(glyphWidths[ww]))+" ");
}
PutDoc("]\nendobj\n");
uint fontCharProcs = newObject();
StartObj(fontCharProcs);
PutDoc("<<\n");
for (int ww = 0; ww < charProcs.count(); ++ww)
{
PutDoc(charProcs[ww]);
}
PutDoc(">>\nendobj\n");
uint fontEncoding = newObject();
StartObj(fontEncoding);
PutDoc(encoding);
PutDoc("]\n");
PutDoc(">>\nendobj\n");
uint font3Object = newObject();
StartObj(font3Object);
PutDoc("<<\n/Type /Font\n/Subtype /Type3\n");
PutDoc("/Name /Fo"+QString::number(a)+"S"+QString::number(SubFonts)+"\n");
PutDoc("/FirstChar 0\n");
PutDoc("/LastChar "+QString::number(glyphCount-1)+"\n");
PutDoc("/Widths "+QString::number(fontWidths)+" 0 R\n");
PutDoc("/CharProcs "+QString::number(fontCharProcs)+" 0 R\n");
PutDoc("/FontBBox ["+QString::number(qRound(minx))+" "+QString::number(qRound(miny))+" "+QString::number(qRound(maxx))+ " "+QString::number(qRound(maxy))+"]\n");
PutDoc("/FontMatrix [0.001 0 0 0.001 0 0]\n");
PutDoc("/Encoding "+QString::number(fontEncoding)+" 0 R\n");
PutDoc(">>\nendobj\n");
Seite.FObjects["Fo"+QString::number(a)+"S"+QString::number(SubFonts)] = font3Object;
charProcs.clear();
glyphWidths.clear();
// glyphMapping.clear();
glyphCount = 0;
++SubFonts;
minx = 99999.9;
miny = 99999.9;
maxx = -99999.9;
maxy = -99999.9;
encoding = "<< /Type /Encoding\n/Differences [ 0\n";
}
}
Type3Fonts.insert("/Fo"+QString::number(a), glyphMapping);
}
else
{
QString fon("");
QMap<uint,FPointArray>& RealGlyphs(it.value());
QMap<uint,FPointArray>::Iterator ig;
for (ig = RealGlyphs.begin(); ig != RealGlyphs.end(); ++ig)
{
FPoint np, np1, np2;
bool nPath = true;
fon = "";
if (ig.value().size() > 3)
{
FPointArray gly = ig.value();
QMatrix mat;
mat.scale(0.1, 0.1);
gly.map(mat);
for (uint poi = 0; poi < gly.size()-3; poi += 4)
{
if (gly.point(poi).x() > 900000)
{
fon += "h\n";
nPath = true;
continue;
}
if (nPath)
{
np = gly.point(poi);
fon += FToStr(np.x())+" "+FToStr(-np.y())+" m\n";
nPath = false;
}
np = gly.point(poi+1);
np1 = gly.point(poi+3);
np2 = gly.point(poi+2);
fon += FToStr(np.x()) + " " + FToStr(-np.y()) + " " +
FToStr(np1.x()) + " " + FToStr(-np1.y()) + " " +
FToStr(np2.x()) + " " + FToStr(-np2.y()) + " c\n";
}
fon += "h f*\n";
np = getMinClipF(&gly);
np1 = getMaxClipF(&gly);
}
else
{
fon = "h";
np = FPoint(0, 0);
np1 = FPoint(0, 0);
}
uint fontGlyphXForm = newObject();
StartObj(fontGlyphXForm);
PutDoc("<<\n/Type /XObject\n/Subtype /Form\n/FormType 1\n");
PutDoc("/BBox [ "+FToStr(np.x())+" "+FToStr(-np.y())+" "+FToStr(np1.x())+ " "+FToStr(-np1.y())+" ]\n");
PutDoc("/Resources << /ProcSet [/PDF /Text /ImageB /ImageC /ImageI]\n");
PutDoc(">>\n");
if (Options.Compress)
fon = CompressStr(&fon);
PutDoc("/Length "+QString::number(fon.length()+1));
if (Options.Compress)
PutDoc("\n/Filter /FlateDecode");
PutDoc(" >>\nstream\n"+EncStream(fon, fontGlyphXForm)+"\nendstream\nendobj\n");
Seite.XObjects[face.psName().replace( QRegExp("[\\s\\/\\{\\[\\]\\}\\<\\>\\(\\)\\%]"), "_" )+QString::number(ig.key())] = fontGlyphXForm;
}
}
}
else
{
UsedFontsP.insert(it.key(), "/Fo"+QString::number(a));
uint embeddedFontObject = 0;
if ((fformat == ScFace::PFB) && (Options.EmbedList.contains(it.key())))
{
QString fon("");
QByteArray bb;
embeddedFontObject = newObject();
StartObj(embeddedFontObject);
face.RawData(bb);
int posi;
for (posi = 6; posi < bb.size(); ++posi)
{
if ((bb[posi] == static_cast<char>(0x80)) && (static_cast<int>(bb[posi+1]) == 2))
break;
fon += QChar(bb[posi]);
}
int len1 = fon.length();
int ulen;
ulen = bb[posi+2] & 0xff;
ulen |= (bb[posi+3] << 8) & 0xff00;
ulen |= (bb[posi+4] << 16) & 0xff0000;
ulen |= (bb[posi+5] << 24) & 0xff000000;
if (ulen > bb.size())
ulen = bb.size()-7;
posi += 6;
for (int j = 0; j < ulen; ++j)
fon += QChar(bb[posi++]);
posi += 6;
int len2 = fon.length()-len1;
for (int j = posi; j < bb.size(); ++j)
{
if ((bb[j] == static_cast<char>(0x80)) && (static_cast<int>(bb[j+1]) == 3))
break;
if (bb[j] == '\r')
fon += "\n";
else
fon += QChar(bb[j]);
}
int len3 = fon.length()-len2-len1;
if (Options.Compress)
fon = CompressStr(&fon);
PutDoc("<<\n/Length "+QString::number(fon.length()+1)+"\n");
PutDoc("/Length1 "+QString::number(len1)+"\n");
PutDoc("/Length2 "+QString::number(len2)+"\n");
PutDoc("/Length3 "+QString::number(len3)+"\n");
if (Options.Compress)
PutDoc("/Filter /FlateDecode\n");
PutDoc(">>\nstream\n"+EncStream(fon,embeddedFontObject)+"\nendstream\nendobj\n");
}
if ((fformat == ScFace::PFA) && (Options.EmbedList.contains(it.key())))
{
QString fon("");
QString fon2("");
QString tm("");
uint value;
bool ok = true;
embeddedFontObject = newObject();
StartObj(embeddedFontObject);
face.EmbedFont(fon);
int len1 = fon.indexOf("eexec")+5;
fon2 = fon.left(len1)+"\n";
int len2 = fon.indexOf("0000000000000000000000000");
if (len2 == -1)
len2 = fon.length()+1;
int count = 0;
for (int xx = len1; xx < len2-1; ++xx)
{
tm = fon.at(xx);
if ((tm == QChar(13)) || (tm == QChar(10)))
continue;
xx++;
count++;
tm += fon.at(xx);
value = tm.toUInt(&ok, 16);
fon2 += QChar(value);
}
fon2 += fon.mid(len2);
if (Options.Compress)
fon2 = CompressStr(&fon2);
PutDoc("<<\n/Length "+QString::number(fon2.length()+1)+"\n");
PutDoc("/Length1 "+QString::number(len1+1)+"\n");
PutDoc("/Length2 "+QString::number(count)+"\n");
PutDoc(static_cast<int>(fon.length()-len2) == -1 ? QString("/Length3 0\n") : "/Length3 "+QString::number(fon.length()-len2)+"\n");
if (Options.Compress)
PutDoc("/Filter /FlateDecode\n");
PutDoc(">>\nstream\n"+EncStream(fon2, embeddedFontObject)+"\nendstream\nendobj\n");
}
if ((fformat == ScFace::SFNT || fformat == ScFace::TTCF) && (Options.EmbedList.contains(it.key())))
{
QString fon("");
QByteArray bb;
embeddedFontObject = newObject();
StartObj(embeddedFontObject);
face.RawData(bb);
//AV: += and append() dont't work because they stop at '\0' :-(
for (int i=0; i < bb.size(); i++)
fon += QChar(bb[i]);
int len = fon.length();
if (Options.Compress)
fon = CompressStr(&fon);
//qDebug() << QString("sfnt data: size=%1 before=%2 compressed=%3").arg(bb.size()).arg(len).arg(fon.length());
PutDoc("<<\n/Length "+QString::number(fon.length()+1)+"\n");
PutDoc("/Length1 "+QString::number(len)+"\n");
if (Options.Compress)
PutDoc("/Filter /FlateDecode\n");
PutDoc(">>\nstream\n"+EncStream(fon, embeddedFontObject)+"\nendstream\nendobj\n");
}
uint fontDescriptor = newObject();
StartObj(fontDescriptor);
// TODO: think about QByteArray ScFace::getFontDescriptor() -- AV
PutDoc("<<\n/Type /FontDescriptor\n");
PutDoc("/FontName /" + face.psName().replace( QRegExp("[\\s\\/\\{\\[\\]\\}\\<\\>\\(\\)\\%]"), "_" ) + "\n");
PutDoc("/FontBBox [ " + face.pdfFontBBoxAsString()+" ]\n");
PutDoc("/Flags ");
//FIXME: isItalic() should be queried from ScFace, not from Qt -- AV
//QFontInfo fo = QFontInfo(it.data());
int pfl = 0;
if (face.isFixedPitch())
pfl = pfl ^ 1;
//if (fo.italic())
if (face.italicAngleAsString() != "0")
pfl = pfl ^ 64;
// pfl = pfl ^ 4;
pfl = pfl ^ 32;
PutDoc(QString::number(pfl)+"\n");
PutDoc("/Ascent " + face.pdfAscentAsString()+"\n");
PutDoc("/Descent " + face.pdfDescentAsString()+"\n");
PutDoc("/CapHeight " + face.pdfCapHeightAsString()+"\n");
PutDoc("/ItalicAngle " + face.italicAngleAsString()+"\n");
PutDoc("/StemV 1\n");
if ((fformat == ScFace::SFNT || fformat == ScFace::TTCF) && (Options.EmbedList.contains(it.key())))
PutDoc("/FontFile2 "+QString::number(embeddedFontObject)+" 0 R\n");
if ((fformat == ScFace::PFB) && (Options.EmbedList.contains(it.key())))
PutDoc("/FontFile "+QString::number(embeddedFontObject)+" 0 R\n");
if ((fformat == ScFace::PFA) && (Options.EmbedList.contains(it.key())))
PutDoc("/FontFile "+QString::number(embeddedFontObject)+" 0 R\n");
PutDoc(">>\nendobj\n");
QMap<uint,std::pair<QChar,QString> > gl;
face.glyphNames(gl);
int nglyphs = 0;
QMap<uint,std::pair<QChar,QString> >::Iterator gli;
for (gli = gl.begin(); gli != gl.end(); ++gli)
{
if (gli.key() > static_cast<uint>(nglyphs))
nglyphs = gli.key();
}
++nglyphs;
// qDebug() << QString("pdflib: nglyphs %1 max %2").arg(nglyphs).arg(face.maxGlyph());
uint FontDes = fontDescriptor;
if (face.isSymbolic() && (fformat == ScFace::SFNT || fformat == ScFace::TTCF))
{
uint fontWidths2 = newObject();
StartObj(fontWidths2);
QStringList toUnicodeMaps;
QList<int> toUnicodeMapsCount;
QString toUnicodeMap = "";
int toUnicodeMapCounter = 0;
PutDoc("[ ");
QList<uint> keys = gl.uniqueKeys();
QList<uint>::iterator git;
for (git = keys.begin(); git != keys.end(); ++git)
{
PutDoc(QString::number(*git)+" ["+QString::number(static_cast<int>(face.glyphWidth(*git)* 1000))+"] " );
QString tmp, tmp2;
tmp.sprintf("%04X", *git);
tmp2.sprintf("%04X", gl.value(*git).first.unicode());
toUnicodeMap += QString("<%1> <%2>\n").arg(tmp).arg((tmp2));
toUnicodeMapCounter++;
if (toUnicodeMapCounter == 100)
{
toUnicodeMaps.append(toUnicodeMap);
toUnicodeMapsCount.append(toUnicodeMapCounter);
toUnicodeMap = "";
toUnicodeMapCounter = 0;
}
}
PutDoc("]\nendobj\n");
if (toUnicodeMapCounter != 0)
{
toUnicodeMaps.append(toUnicodeMap);
toUnicodeMapsCount.append(toUnicodeMapCounter);
}
QString toUnicodeMapStream = "";
toUnicodeMapStream += "/CIDInit /ProcSet findresource begin\n";
toUnicodeMapStream += "12 dict begin\n";
toUnicodeMapStream += "begincmap\n";
toUnicodeMapStream += "/CIDSystemInfo <<\n";
toUnicodeMapStream += "/Registry (Adobe)\n";
toUnicodeMapStream += "/Ordering (UCS)\n";
toUnicodeMapStream += "/Supplement 0\n";
toUnicodeMapStream += ">> def\n";
toUnicodeMapStream += "/CMapName /Adobe-Identity-UCS def\n";
toUnicodeMapStream += "/CMapType 2 def\n";
toUnicodeMapStream += "1 begincodespacerange\n";
toUnicodeMapStream += "<0000> <FFFF>\n";
toUnicodeMapStream += "endcodespacerange\n";
for (int uniC = 0; uniC < toUnicodeMaps.count(); uniC++)
{
toUnicodeMapStream += QString("%1 beginbfchar\n").arg(toUnicodeMapsCount[uniC]);
toUnicodeMapStream += toUnicodeMaps[uniC];
toUnicodeMapStream += "endbfchar\n";
}
toUnicodeMapStream += "endcmap\n";
toUnicodeMapStream += "CMapName currentdict /CMap defineresource pop\n";
toUnicodeMapStream += "end\n";
toUnicodeMapStream += "end\n";
uint fontToUnicode2 = WritePDFStream(toUnicodeMapStream);
uint fontObject2 = newObject();
StartObj(fontObject2);
PutDoc("<<\n/Type /Font\n/Subtype /Type0\n");
PutDoc("/Name /Fo"+QString::number(a)+"\n");
PutDoc("/BaseFont /"+face.psName().replace( QRegExp("[\\s\\/\\{\\[\\]\\}\\<\\>\\(\\)\\%]"), "_" )+"\n");
PutDoc("/Encoding /Identity-H\n");
PutDoc("/ToUnicode "+QString::number(fontToUnicode2)+" 0 R\n");
PutDoc("/DescendantFonts [");
PutDoc("<</Type /Font");
PutDoc("/Subtype /CIDFontType2");
PutDoc("/BaseFont /"+face.psName().replace( QRegExp("[\\s\\/\\{\\[\\]\\}\\<\\>\\(\\)\\%]"), "_" ));
PutDoc("/FontDescriptor "+QString::number(FontDes)+" 0 R");
PutDoc("/CIDSystemInfo <</Ordering(Identity)/Registry(Adobe)/Supplement 0>>");
PutDoc("/DW 1000");
PutDoc("/W "+QString::number(fontWidths2)+" 0 R");
PutDoc("/CIDToGIDMap /Identity");
PutDoc(">>"); // close CIDFont dictionary
PutDoc("]\n"); // close DescendantFonts array
PutDoc(">>\nendobj\n");
Seite.FObjects["Fo"+QString::number(a)] = fontObject2;
}
else
{
uint Fcc = nglyphs / 224;
if ((nglyphs % 224) != 0)
Fcc += 1;
for (uint Fc = 0; Fc < Fcc; ++Fc)
{
uint fontWidths2 = newObject();
StartObj(fontWidths2);
int chCount = 32;
PutDoc("[ 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 ");
for (int ww = 32; ww < 256; ++ww)
{
uint glyph = 224 * Fc + ww - 32;
if (gl.contains(glyph))
PutDoc(QString::number(static_cast<int>(face.glyphWidth(glyph)* 1000))+" ");
else
PutDoc("0 ");
chCount++;
if (signed(glyph) == nglyphs-1)
break;
}
PutDoc("]\nendobj\n");
uint fontEncoding2 = newObject();
StartObj(fontEncoding2);
QStringList toUnicodeMaps;
QList<int> toUnicodeMapsCount;
QString toUnicodeMap = "";
int toUnicodeMapCounter = 0;
PutDoc("<< /Type /Encoding\n");
PutDoc("/Differences [ \n");
int crc = 0;
bool startOfSeq = true;
for (int ww2 = 32; ww2 < 256; ++ww2)
{
uint glyph = 224 * Fc + ww2 - 32;
QMap<uint,std::pair<QChar,QString> >::Iterator glIt = gl.find(glyph);
if (glIt != gl.end() && !glIt.value().second.isEmpty())
{
if (startOfSeq)
{
PutDoc(QString::number(ww2)+" ");
startOfSeq = false;
}
PutDoc("/"+glIt.value().second+" ");
QString tmp, tmp2;
tmp.sprintf("%02X", ww2);
tmp2.sprintf("%04X", glIt.value().first.unicode());
toUnicodeMap += QString("<%1> <%2>\n").arg(tmp).arg((tmp2));
toUnicodeMapCounter++;
if (toUnicodeMapCounter == 100)
{
toUnicodeMaps.append(toUnicodeMap);
toUnicodeMapsCount.append(toUnicodeMapCounter);
toUnicodeMap = "";
toUnicodeMapCounter = 0;
}
crc++;
}
else
{
startOfSeq = true;
}
if (signed(glyph) == nglyphs-1)
break;
if (crc > 8)
{
PutDoc("\n");
crc = 0;
}
}
if (toUnicodeMapCounter != 0)
{
toUnicodeMaps.append(toUnicodeMap);
toUnicodeMapsCount.append(toUnicodeMapCounter);
}
PutDoc("]\n");
PutDoc(">>\nendobj\n");
QString toUnicodeMapStream = "";
toUnicodeMapStream += "/CIDInit /ProcSet findresource begin\n";
toUnicodeMapStream += "12 dict begin\n";
toUnicodeMapStream += "begincmap\n";
toUnicodeMapStream += "/CIDSystemInfo <<\n";
toUnicodeMapStream += "/Registry (Adobe)\n";
toUnicodeMapStream += "/Ordering (UCS)\n";
toUnicodeMapStream += "/Supplement 0\n";
toUnicodeMapStream += ">> def\n";
toUnicodeMapStream += "/CMapName /Adobe-Identity-UCS def\n";
toUnicodeMapStream += "/CMapType 2 def\n";
toUnicodeMapStream += "1 begincodespacerange\n";
toUnicodeMapStream += "<0000> <FFFF>\n";
toUnicodeMapStream += "endcodespacerange\n";
for (int uniC = 0; uniC < toUnicodeMaps.count(); uniC++)
{
toUnicodeMapStream += QString("%1 beginbfchar\n").arg(toUnicodeMapsCount[uniC]);
toUnicodeMapStream += toUnicodeMaps[uniC];
toUnicodeMapStream += "endbfchar\n";
}
toUnicodeMapStream += "endcmap\n";
toUnicodeMapStream += "CMapName currentdict /CMap defineresource pop\n";
toUnicodeMapStream += "end\n";
toUnicodeMapStream += "end\n";
uint fontToUnicode2 = WritePDFStream(toUnicodeMapStream);
uint fontObject2 = newObject();
StartObj(fontObject2);
PutDoc("<<\n/Type /Font\n/Subtype ");
PutDoc((fformat == ScFace::SFNT || fformat == ScFace::TTCF) ? "/TrueType\n" : "/Type1\n");
PutDoc("/Name /Fo"+QString::number(a)+"S"+QString::number(Fc)+"\n");
PutDoc("/BaseFont /"+face.psName().replace( QRegExp("[\\s\\/\\{\\[\\]\\}\\<\\>\\(\\)\\%]"), "_" )+"\n");
PutDoc("/FirstChar 0\n");
PutDoc("/LastChar "+QString::number(chCount-1)+"\n");
PutDoc("/Widths "+QString::number(fontWidths2)+" 0 R\n");
PutDoc("/Encoding "+QString::number(fontEncoding2)+" 0 R\n");
PutDoc("/ToUnicode "+QString::number(fontToUnicode2)+" 0 R\n");
PutDoc("/FontDescriptor "+QString::number(FontDes)+" 0 R\n");
PutDoc(">>\nendobj\n");
Seite.FObjects["Fo"+QString::number(a)+"S"+QString::number(Fc)] = fontObject2;
} // for(Fc)
uint fontWidthsForm = newObject();
StartObj(fontWidthsForm);
PutDoc("[ 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 ");
for (int ww = 32; ww < 256; ++ww)
{
int unicode = fromPDFDocEncoding(ww);
uint glyph = face.char2CMap(QChar(unicode));
if (gl.contains(glyph))
PutDoc(QString::number(static_cast<int>(face.glyphWidth(glyph)* 1000))+" ");
else
PutDoc("0 ");
}
PutDoc("]\nendobj\n");
uint fontObjectForm = newObject();
StartObj(fontObjectForm);
PutDoc("<<\n/Type /Font\n/Subtype ");
PutDoc((fformat == ScFace::SFNT || fformat == ScFace::TTCF) ? "/TrueType\n" : "/Type1\n");
// if (fformat == ScFace::SFNT || fformat == ScFace::TTCF)
// {
// PutDoc("/TrueType\n");
PutDoc("/Name /Fo"+QString::number(a)+"Form"+"\n");
Seite.FObjects["Fo"+QString::number(a)+"Form"] = fontObjectForm;
UsedFontsF.insert(it.key(), "/Fo"+QString::number(a)+"Form");
/* }
else
{
PutDoc("/Type1\n");
PutDoc("/Name /"+face.psName().replace( QRegExp("[\\s\\/\\{\\[\\]\\}\\<\\>\\(\\)\\%]"), "_" )+"\n");
Seite.FObjects[face.psName().replace( QRegExp("[\\s\\/\\{\\[\\]\\}\\<\\>\\(\\)\\%]"), "_" )] = ObjCounter;
UsedFontsF.insert(it.key(), "/"+face.psName().replace( QRegExp("[\\s\\/\\{\\[\\]\\}\\<\\>\\(\\)\\%]"), "_" ));
} */
PutDoc("/BaseFont /"+face.psName().replace( QRegExp("[\\s\\/\\{\\[\\]\\}\\<\\>\\(\\)\\%]"), "_" )+"\n");
PutDoc("/Encoding << \n");
PutDoc("/Differences [ \n");
PutDoc("24 /breve /caron /circumflex /dotaccent /hungarumlaut /ogonek /ring /tilde\n");
PutDoc("39 /quotesingle 96 /grave 128 /bullet /dagger /daggerdbl /ellipsis /emdash /endash /florin /fraction /guilsinglleft /guilsinglright\n");
PutDoc("/minus /perthousand /quotedblbase /quotedblleft /quotedblright /quoteleft /quoteright /quotesinglbase /trademark /fi /fl /Lslash /OE /Scaron\n");
PutDoc("/Ydieresis /Zcaron /dotlessi /lslash /oe /scaron /zcaron 160 /Euro 164 /currency 166 /brokenbar 168 /dieresis /copyright /ordfeminine 172 /logicalnot\n");
PutDoc("/.notdef /registered /macron /degree /plusminus /twosuperior /threesuperior /acute /mu 183 /periodcentered /cedilla /onesuperior /ordmasculine\n");
PutDoc("188 /onequarter /onehalf /threequarters 192 /Agrave /Aacute /Acircumflex /Atilde /Adieresis /Aring /AE /Ccedilla /Egrave /Eacute /Ecircumflex\n");
PutDoc("/Edieresis /Igrave /Iacute /Icircumflex /Idieresis /Eth /Ntilde /Ograve /Oacute /Ocircumflex /Otilde /Odieresis /multiply /Oslash\n");
PutDoc("/Ugrave /Uacute /Ucircumflex /Udieresis /Yacute /Thorn /germandbls /agrave /aacute /acircumflex /atilde /adieresis /aring /ae /ccedilla\n");
PutDoc("/egrave /eacute /ecircumflex /edieresis /igrave /iacute /icircumflex /idieresis /eth /ntilde /ograve /oacute /ocircumflex /otilde /odieresis\n");
PutDoc("/divide /oslash /ugrave /uacute /ucircumflex /udieresis /yacute /thorn /ydieresis\n");
PutDoc("] >>\n");
PutDoc("/FirstChar 0\n");
PutDoc("/LastChar 255\n");
PutDoc("/Widths "+QString::number(fontWidthsForm)+" 0 R\n");
PutDoc("/FontDescriptor "+QString::number(FontDes)+" 0 R\n");
PutDoc(">>\nendobj\n");
}
}
a++;
}
if (Options.UseLPI)
{
uint halftones = newObject();
StartObj(halftones);
PutDoc("<<\n/Type /Halftone\n/HalftoneType 5\n");
QMap<QString,LPIData>::const_iterator itlp;
for (itlp = Options.LPISettings.constBegin(); itlp != Options.LPISettings.constEnd(); ++itlp)
{
PutDoc("/"+itlp.key()+"\n<<\n/Type /Halftone\n/HalftoneType 1\n/Frequency ");
PutDoc(QString::number(itlp.value().Frequency)+"\n/Angle "+QString::number(itlp.value().Angle)+"\n/SpotFunction ");
QString func ("");
switch (itlp.value().SpotFunc)
{
case 0:
func = "/SimpleDot";
break;
case 1:
func = "/Line";
break;
case 2:
func = "/Round";
break;
case 3:
func = "/Ellipse";
break;
default:
func = "/SimpleDot";
break;
}
PutDoc(func+"\n>>\n");
}
PutDoc("/Default\n<<\n/Type /Halftone\n/HalftoneType 1\n/Frequency 50\n/Angle 45\n/SpotFunction /Round\n>>\n");
PutDoc(">>\nendobj\n");
HTName = ResNam+QString::number(ResCount);
Transpar[HTName] = writeGState("/HT "+QString::number(halftones)+" 0 R\n");
ResCount++;
}
if ((doc.HasCMS) && (Options.UseProfiles) && (Options.Version != PDFOptions::PDFVersion_X1a))
{
uint iccProfileObject = newObject();
StartObj(iccProfileObject);
QByteArray dataP;
struct ICCD dataD;
loadRawBytes(ScCore->InputProfiles[Options.SolidProf], dataP);
PutDoc("<<\n");
if (Options.Compress)
{
QByteArray compData = CompressArray(dataP);
if (compData.size() > 0)
{
PutDoc("/Filter /FlateDecode\n");
dataP = compData;
}
}
PutDoc("/Length "+QString::number(dataP.size()+1)+"\n");
PutDoc("/N "+QString::number(Options.SComp)+"\n");
PutDoc(">>\nstream\n");
EncodeArrayToStream(dataP, iccProfileObject);
PutDoc("\nendstream\nendobj\n");
uint iccColorspace = newObject();
StartObj(iccColorspace);
dataD.ResName = ResNam+QString::number(ResCount);
dataD.ICCArray = "[ /ICCBased "+QString::number(iccProfileObject)+" 0 R ]";
dataD.ResNum = iccColorspace;
dataD.components = Options.SComp;
ICCProfiles[Options.SolidProf] = dataD;
PutDoc("[ /ICCBased "+QString::number(iccProfileObject)+" 0 R ]\n");
PutDoc("endobj\n");
ResCount++;
}
if (((Options.isGrayscale == false) && (Options.UseRGB == false)) && (Options.UseSpotColors))
{
doc.getUsedColors(colorsToUse);
ColorList::Iterator itf;
for (itf = colorsToUse.begin(); itf != colorsToUse.end(); ++itf)
{
if ((colorsToUse[itf.key()].isSpotColor()) || (colorsToUse[itf.key()].isRegistrationColor()))
{
CMYKColor cmykValues;
int cc, cm, cy, ck;
struct SpotC spotD;
ScColorEngine::getCMYKValues(colorsToUse[itf.key()], &doc, cmykValues);
cmykValues.getValues(cc, cm, cy, ck);
QString colorDesc = "{\ndup "+FToStr(static_cast<double>(cc) / 255)+"\nmul exch dup ";
colorDesc += FToStr(static_cast<double>(cm) / 255)+"\nmul exch dup ";
colorDesc += FToStr(static_cast<double>(cy) / 255)+"\nmul exch ";
colorDesc += FToStr(static_cast<double>(ck) / 255)+" mul }";
uint separationFunction = newObject();
StartObj(separationFunction);
PutDoc("<<\n/FunctionType 4\n");
PutDoc("/Domain [0.0 1.0]\n");
PutDoc("/Range [0.0 1.0 0.0 1.0 0.0 1.0 0.0 1.0]\n");
PutDoc("/Length "+QString::number(colorDesc.length()+1)+"\n");
PutDoc(">>\nstream\n"+EncStream(colorDesc, separationFunction)+"\nendstream\nendobj\n");
uint separationColorspace= newObject();
StartObj(separationColorspace);
PutDoc("[ /Separation /");
if (colorsToUse[itf.key()].isRegistrationColor())
PutDoc("All");
else
PutDoc(itf.key().simplified().replace("#", "#23").replace( QRegExp("[\\s\\/\\{\\[\\]\\}\\<\\>\\(\\)\\%]"), "#20" ));
PutDoc(" /DeviceCMYK "+QString::number(separationFunction)+" 0 R ]\nendobj\n");
spotD.ResName = spotNam+QString::number(spotCount);
spotD.ResNum = separationColorspace;
spotMap.insert(itf.key(), spotD);
spotCount++;
}
}
}
if ((Options.cropMarks) || (Options.bleedMarks) || (Options.registrationMarks) || (Options.colorMarks) || (Options.docInfoMarks))
{
struct SpotC spotD;
uint registrationColorspace = newObject();
StartObj(registrationColorspace);
PutDoc("[ /Separation /All /DeviceCMYK\n");
PutDoc("<<\n/FunctionType 2\n");
PutDoc("/Domain [0.0 1.0]\n");
PutDoc("/Range [0.0 1.0 0.0 1.0 0.0 1.0 0.0 1.0]\n");
PutDoc("/C0 [0 0 0 0] \n");
PutDoc("/C1 [1 1 1 1] \n");
PutDoc("/N 1\n");
PutDoc(">>\n]\nendobj\n");
spotD.ResName = spotNam+QString::number(spotCount);
spotD.ResNum = registrationColorspace;
spotMapReg.insert("Register", spotD);
spotCount++;
}
if ((Options.Version == PDFOptions::PDFVersion_15) && (Options.useLayers))
{
ScLayer ll;
struct OCGInfo ocg;
ll.isPrintable = false;
ll.LNr = 0;
int Lnr = 0;
QString ocgNam("oc");
uint docLayersCount=doc.Layers.count();
for (uint la = 0; la < docLayersCount; ++la)
{
uint optionalContent = newObject();
QString tmp("");
doc.Layers.levelToLayer(ll, Lnr);
ocg.Name = ocgNam+tmp.setNum(ll.LNr);
ocg.ObjNum = optionalContent;
ocg.visible = ll.isViewable;
OCGEntries.insert(ll.Name, ocg);
StartObj(optionalContent);
PutDoc("<<\n");
PutDoc("/Type /OCG\n");
PutDoc("/Name ");
PutDoc(EncStringUTF16(ll.Name, optionalContent));
PutDoc("\n");
PutDoc("/Usage <</Print <</PrintState ");
if (ll.isPrintable)
PutDoc("/ON");
else
PutDoc("/OFF");
PutDoc(">> /View <</ViewState ");
if (ll.isViewable)
PutDoc("/ON");
else
PutDoc("/OFF");
PutDoc(">>>>");
PutDoc("\n");
PutDoc(">>\nendobj\n");
Lnr++;
}
}
return true;
}
bool PDFLibCore::PDF_TemplatePage(const Page* pag, bool )
{
QString tmp, tmpOut;
ActPageP = pag;
PageItem* ite;
QList<PageItem*> PItems;
int Lnr = 0;
ScLayer ll;
ll.isPrintable = false;
ll.LNr = 0;
Content = "";
Seite.AObjects.clear();
for (int la = 0; la < doc.Layers.count(); ++la)
{
doc.Layers.levelToLayer(ll, Lnr);
PItems = doc.MasterItems;
if ((ll.isPrintable) || ((Options.Version == PDFOptions::PDFVersion_15) && (Options.useLayers)))
{
if ((Options.Version == PDFOptions::PDFVersion_15) && (Options.useLayers))
PutPage("/OC /"+OCGEntries[ll.Name].Name+" BDC\n");
for (int a = 0; a < PItems.count(); ++a)
{
Content = "";
ite =PItems.at(a);
if (ite->LayerNr != ll.LNr)
continue;
double bLeft, bRight, bBottom, bTop;
getBleeds(pag, bLeft, bRight, bBottom, bTop);
double x = pag->xOffset() - bLeft;
double y = pag->yOffset() - bTop;
double w = pag->width() + bLeft + bRight;
double h1 = pag->height() + bBottom + bTop;
double ilw= ite->lineWidth();
double x2 = ite->BoundingX - ilw / 2.0;
double y2 = ite->BoundingY - ilw / 2.0;
double w2 = ite->BoundingW + ilw;
double h2 = ite->BoundingH + ilw;
if (!( qMax( x, x2 ) <= qMin( x+w, x2+w2 ) && qMax( y, y2 ) <= qMin( y+h1, y2+h2 )))
continue;
if (ite->ChangedMasterItem)
continue;
if ((!pag->pageName().isEmpty()) && (ite->OwnPage != static_cast<int>(pag->pageNr())) && (ite->OwnPage != -1))
continue;
PutPage("q\n");
if ((ite->doOverprint) && (!Options.UseRGB))
{
QString ShName = ResNam+QString::number(ResCount);
ResCount++;
Transpar[ShName] = writeGState("/OP true\n"
"/op true\n"
"/OPM 1\n");
PutPage("/"+ShName+" gs\n");
}
/* Bookmarks on Master Pages do not make any sense */
// if ((ite->isBookmark) && (Options.Bookmarks))
// PDF_Bookmark(ite, pag->height() - (ite->yPos() - pag->yOffset()));
if (!ite->printEnabled() || ((ite->itemType() == PageItem::TextFrame) && (!pag->pageName().isEmpty())))
{
PutPage("Q\n");
continue;
}
if (ite->fillColor() != CommonStrings::None)
PutPage(putColor(ite->fillColor(), ite->fillShade(), true));
if (ite->lineColor() != CommonStrings::None)
PutPage(putColor(ite->lineColor(), ite->lineShade(), false));
Content += FToStr(fabs(ite->lineWidth()))+" w\n";
if (ite->DashValues.count() != 0)
{
PutPage("[ ");
QVector<double>::iterator it;
for ( it = ite->DashValues.begin(); it != ite->DashValues.end(); ++it )
{
double da = *it;
// #8758: Custom dotted lines don't export properly to pdf
// Null values have to be exported if line end != flat
if ((da != 0) || (ite->lineEnd() != Qt::FlatCap))
PutPage(QString::number(da)+" ");
}
PutPage("] "+QString::number(ite->DashOffset)+" d\n");
}
else
PutPage("["+getDashString(ite->PLineArt, ite->lineWidth())+"] 0 d\n");
switch (ite->PLineEnd)
{
case Qt::FlatCap:
PutPage("0 J\n");
break;
case Qt::SquareCap:
PutPage("2 J\n");
break;
case Qt::RoundCap:
PutPage("1 J\n");
break;
default:
PutPage("0 J\n");
break;
}
switch (ite->PLineJoin)
{
case Qt::MiterJoin:
PutPage("0 j\n");
break;
case Qt::BevelJoin:
PutPage("2 j\n");
break;
case Qt::RoundJoin:
PutPage("1 j\n");
break;
default:
PutPage("0 j\n");
break;
}
PutPage("1 0 0 1 "+FToStr(ite->xPos() - pag->xOffset())+" "+FToStr(pag->height() - (ite->yPos() - pag->yOffset()))+" cm\n");
if (ite->rotation() != 0)
{
double sr = sin(-ite->rotation()* M_PI / 180.0);
double cr = cos(-ite->rotation()* M_PI / 180.0);
if ((cr * cr) < 0.000001)
cr = 0;
if ((sr * sr) < 0.000001)
sr = 0;
PutPage(FToStr(cr)+" "+FToStr(sr)+" "+FToStr(-sr)+" "+FToStr(cr)+" 0 0 cm\n");
}
switch (ite->itemType())
{
case PageItem::ImageFrame:
case PageItem::LatexFrame:
// Same functions as for ImageFrames work for LatexFrames too
if (((ite->fillTransparency() != 0) || (ite->fillBlendmode() != 0)) && (Options.Version >= PDFOptions::PDFVersion_14))
PutPage(PDF_TransparenzFill(ite));
if ((ite->fillColor() != CommonStrings::None) || (ite->GrType != 0))
{
if (ite->GrType != 0)
{
if (!PDF_Gradient(tmpOut, ite))
return false;
PutPage(tmpOut);
}
else
{
PutPage(SetClipPath(ite));
PutPage(ite->fillRule ? "h\nf*\n" : "h\nf\n");
}
}
PutPage("q\n");
if (ite->imageClip.size() != 0)
{
PutPage(SetClipPathImage(ite));
PutPage("h\nW*\nn\n");
}
PutPage(SetClipPath(ite));
PutPage("h\nW*\nn\n");
if (ite->imageFlippedH())
PutPage("-1 0 0 1 "+FToStr(ite->width())+" 0 cm\n");
if (ite->imageFlippedV())
PutPage("1 0 0 -1 0 "+FToStr(-ite->height())+" cm\n");
if ((ite->PictureIsAvailable) && (!ite->Pfile.isEmpty()))
{
if (!PDF_Image(ite, ite->Pfile, ite->imageXScale(), ite->imageYScale(), ite->imageXOffset(), -ite->imageYOffset(), false, ite->IProfile, ite->UseEmbedded, ite->IRender, &tmpOut))
return false;
PutPage(tmpOut);
}
PutPage("Q\n");
if (((ite->lineColor() != CommonStrings::None) || (!ite->NamedLStyle.isEmpty())) && (!ite->isTableItem))
{
if (((ite->lineTransparency() != 0) || (ite->lineBlendmode() != 0)) && (Options.Version >= PDFOptions::PDFVersion_14))
PutPage(PDF_TransparenzStroke(ite));
if ((ite->NamedLStyle.isEmpty()) && (ite->lineWidth() != 0.0))
{
PutPage(SetClipPath(ite));
PutPage("h\nS\n");
}
else
{
multiLine ml = doc.MLineStyles[ite->NamedLStyle];
for (int it = ml.size()-1; it > -1; it--)
{
if ((ml[it].Color != CommonStrings::None) && (ml[it].Width != 0))
{
PutPage(setStrokeMulti(&ml[it]));
PutPage(SetClipPath(ite));
PutPage("h\nS\n");
}
}
}
}
break;
case PageItem::TextFrame:
break;
case PageItem::Line:
if (((ite->lineTransparency() != 0) || (ite->lineBlendmode() != 0)) && (Options.Version >= PDFOptions::PDFVersion_14))
PutPage(PDF_TransparenzStroke(ite));
if (ite->NamedLStyle.isEmpty())
{
PutPage("0 0 m\n");
PutPage(FToStr(ite->width())+" 0 l\n");
PutPage("S\n");
}
else
{
multiLine ml = doc.MLineStyles[ite->NamedLStyle];
for (int it = ml.size()-1; it > -1; it--)
{
if ((ml[it].Color != CommonStrings::None) && (ml[it].Width != 0))
{
PutPage(setStrokeMulti(&ml[it]));
PutPage("0 0 m\n");
PutPage(FToStr(ite->width())+" 0 l\n");
PutPage("S\n");
}
}
}
if (ite->startArrowIndex() != 0)
{
QMatrix arrowTrans;
arrowTrans.scale(-1,1);
PutPage(drawArrow(ite, arrowTrans, ite->startArrowIndex()));
}
if (ite->endArrowIndex() != 0)
{
QMatrix arrowTrans;
arrowTrans.translate(ite->width(), 0);
PutPage(drawArrow(ite, arrowTrans, ite->endArrowIndex()));
}
break;
case PageItem::ItemType1:
case PageItem::ItemType3:
case PageItem::Polygon:
if (((ite->fillTransparency() != 0) || (ite->fillBlendmode() != 0)) && (Options.Version >= PDFOptions::PDFVersion_14))
PutPage(PDF_TransparenzFill(ite));
if (ite->GrType != 0)
{
if (!PDF_Gradient(tmpOut, ite))
return false;
PutPage(tmpOut);
}
else
{
if (ite->fillColor() != CommonStrings::None)
{
PutPage(SetClipPath(ite));
PutPage(ite->fillRule ? "h\nf*\n" : "h\nf\n");
}
}
if ((ite->lineColor() != CommonStrings::None) || (!ite->NamedLStyle.isEmpty()))
{
if (((ite->lineTransparency() != 0) || (ite->lineBlendmode() != 0)) && (Options.Version >= PDFOptions::PDFVersion_14))
PutPage(PDF_TransparenzStroke(ite));
if ((ite->NamedLStyle.isEmpty()) && (ite->lineWidth() != 0.0))
{
PutPage(SetClipPath(ite));
PutPage("h\nS\n");
}
else
{
multiLine ml = doc.MLineStyles[ite->NamedLStyle];
for (int it = ml.size()-1; it > -1; it--)
{
if ((ml[it].Color != CommonStrings::None) && (ml[it].Width != 0))
{
PutPage(setStrokeMulti(&ml[it]));
PutPage(SetClipPath(ite));
PutPage("h\nS\n");
}
}
}
}
break;
case PageItem::PolyLine:
if (ite->PoLine.size() > 4) // && ((ite->PoLine.point(0) != ite->PoLine.point(1)) || (ite->PoLine.point(2) != ite->PoLine.point(3))))
{
if (((ite->fillTransparency() != 0) || (ite->fillBlendmode() != 0)) && (Options.Version >= PDFOptions::PDFVersion_14))
PutPage(PDF_TransparenzFill(ite));
if (ite->GrType != 0)
{
if (!PDF_Gradient(tmpOut, ite))
return false;
PutPage(tmpOut);
}
else
{
if (ite->fillColor() != CommonStrings::None)
{
PutPage(SetClipPath(ite));
PutPage(ite->fillRule ? "h\nf*\n" : "h\nf\n");
}
}
}
if ((ite->lineColor() != CommonStrings::None) || (!ite->NamedLStyle.isEmpty()))
{
if (((ite->lineTransparency() != 0) || (ite->lineBlendmode() != 0)) && (Options.Version >= PDFOptions::PDFVersion_14))
PutPage(PDF_TransparenzStroke(ite));
if ((ite->NamedLStyle.isEmpty()) && (ite->lineWidth() != 0.0))
{
PutPage(SetClipPath(ite, false));
PutPage("S\n");
}
else
{
multiLine ml = doc.MLineStyles[ite->NamedLStyle];
for (int it = ml.size()-1; it > -1; it--)
{
if ((ml[it].Color != CommonStrings::None) && (ml[it].Width != 0))
{
PutPage(setStrokeMulti(&ml[it]));
PutPage(SetClipPath(ite, false));
PutPage("S\n");
}
}
}
}
if (ite->startArrowIndex() != 0)
{
FPoint Start = ite->PoLine.point(0);
for (uint xx = 1; xx < ite->PoLine.size(); xx += 2)
{
FPoint Vector = ite->PoLine.point(xx);
if ((Start.x() != Vector.x()) || (Start.y() != Vector.y()))
{
double r = atan2(Start.y()-Vector.y(),Start.x()-Vector.x())*(180.0/M_PI);
QMatrix arrowTrans;
arrowTrans.translate(Start.x(), Start.y());
arrowTrans.rotate(r);
PutPage(drawArrow(ite, arrowTrans, ite->startArrowIndex()));
break;
}
}
}
if (ite->endArrowIndex() != 0)
{
FPoint End = ite->PoLine.point(ite->PoLine.size()-2);
for (uint xx = ite->PoLine.size()-1; xx > 0; xx -= 2)
{
FPoint Vector = ite->PoLine.point(xx);
if ((End.x() != Vector.x()) || (End.y() != Vector.y()))
{
double r = atan2(End.y()-Vector.y(),End.x()-Vector.x())*(180.0/M_PI);
QMatrix arrowTrans;
arrowTrans.translate(End.x(), End.y());
arrowTrans.rotate(r);
PutPage(drawArrow(ite, arrowTrans, ite->endArrowIndex()));
break;
}
}
}
break;
case PageItem::PathText:
if (ite->PoShow)
{
if (ite->PoLine.size() > 3)
{
PutPage("q\n");
if ((ite->lineColor() != CommonStrings::None) || (!ite->NamedLStyle.isEmpty()))
{
if (((ite->lineTransparency() != 0) || (ite->lineBlendmode() != 0)) && (Options.Version >= PDFOptions::PDFVersion_14))
PutPage(PDF_TransparenzStroke(ite));
if ((ite->NamedLStyle.isEmpty()) && (ite->lineWidth() != 0.0))
{
PutPage(SetClipPath(ite, false));
PutPage("S\n");
}
else
{
multiLine ml = doc.MLineStyles[ite->NamedLStyle];
for (int it = ml.size()-1; it > -1; it--)
{
if ((ml[it].Color != CommonStrings::None) && (ml[it].Width != 0))
{
PutPage(setStrokeMulti(&ml[it]));
PutPage(SetClipPath(ite, false));
PutPage("S\n");
}
}
}
}
PutPage("Q\n");
}
}
if (((ite->fillTransparency() != 0) || (ite->fillBlendmode() != 0)) && (Options.Version >= PDFOptions::PDFVersion_14))
PutPage(PDF_TransparenzFill(ite));
PutPage(setTextSt(ite, pag->pageNr(), pag));
break;
case PageItem::Multiple:
Q_ASSERT(false);
break;
}
PutPage("Q\n");
uint templateObject = newObject();
StartObj(templateObject);
PutDoc("<<\n/Type /XObject\n/Subtype /Form\n/FormType 1\n");
double bleedRight = 0.0;
double bleedLeft = 0.0;
getBleeds(ActPageP, bleedLeft, bleedRight);
double maxBoxX = ActPageP->width()+bleedRight+bleedLeft;
double maxBoxY = ActPageP->height()+Options.bleeds.Top+Options.bleeds.Bottom;
PutDoc("/BBox [ "+FToStr(-bleedLeft)+" "+FToStr(-Options.bleeds.Bottom)+" "+FToStr(maxBoxX)+" "+FToStr(maxBoxY)+" ]\n");
// PutDoc("/BBox [ 0 0 "+FToStr(ActPageP->width())+" "+FToStr(ActPageP->height())+" ]\n");
PutDoc("/Resources << /ProcSet [/PDF /Text /ImageB /ImageC /ImageI]\n");
if (Seite.ImgObjects.count() != 0)
{
PutDoc("/XObject <<\n");
QMap<QString,int>::Iterator it;
for (it = Seite.ImgObjects.begin(); it != Seite.ImgObjects.end(); ++it)
PutDoc("/"+it.key()+" "+QString::number(it.value())+" 0 R\n");
PutDoc(">>\n");
}
if (Seite.FObjects.count() != 0)
{
PutDoc("/Font << \n");
QMap<QString,int>::Iterator it2;
for (it2 = Seite.FObjects.begin(); it2 != Seite.FObjects.end(); ++it2)
PutDoc("/"+it2.key()+" "+QString::number(it2.value())+" 0 R\n");
PutDoc(">>\n");
}
if (Shadings.count() != 0)
{
PutDoc("/Shading << \n");
QMap<QString,int>::Iterator it3;
for (it3 = Shadings.begin(); it3 != Shadings.end(); ++it3)
PutDoc("/"+it3.key()+" "+QString::number(it3.value())+" 0 R\n");
PutDoc(">>\n");
}
if (Patterns.count() != 0)
{
PutDoc("/Pattern << \n");
QMap<QString,int>::Iterator it3p;
for (it3p = Patterns.begin(); it3p != Patterns.end(); ++it3p)
PutDoc("/"+it3p.key()+" "+QString::number(it3p.value())+" 0 R\n");
PutDoc(">>\n");
}
if (Transpar.count() != 0)
{
PutDoc("/ExtGState << \n");
QMap<QString,int>::Iterator it3t;
for (it3t = Transpar.begin(); it3t != Transpar.end(); ++it3t)
PutDoc("/"+it3t.key()+" "+QString::number(it3t.value())+" 0 R\n");
PutDoc(">>\n");
}
if ((ICCProfiles.count() != 0) || (spotMap.count() != 0))
{
PutDoc("/ColorSpace << \n");
QMap<QString,ICCD>::Iterator it3c;
if (ICCProfiles.count() != 0)
{
for (it3c = ICCProfiles.begin(); it3c != ICCProfiles.end(); ++it3c)
PutDoc("/"+it3c.value().ResName+" "+QString::number(it3c.value().ResNum)+" 0 R\n");
}
QMap<QString,SpotC>::Iterator it3sc;
if (spotMap.count() != 0)
{
for (it3sc = spotMap.begin(); it3sc != spotMap.end(); ++it3sc)
PutDoc("/"+it3sc.value().ResName+" "+QString::number(it3sc.value().ResNum)+" 0 R\n");
}
PutDoc(">>\n");
}
PutDoc(">>\n");
if (Options.Compress)
Content = CompressStr(&Content);
PutDoc("/Length "+QString::number(Content.length()+1));
if (Options.Compress)
PutDoc("\n/Filter /FlateDecode");
PutDoc(" >>\nstream\n"+EncStream(Content, templateObject)+"\nendstream\nendobj\n");
int pIndex = doc.MasterPages.indexOf((Page* const) pag) + 1;
QString name = QString("master_page_obj_%1_%2").arg(pIndex).arg(ite->ItemNr);
Seite.XObjects[name] = templateObject;
}
if ((Options.Version == PDFOptions::PDFVersion_15) && (Options.useLayers))
PutPage("EMC\n");
}
Lnr++;
}
return true;
}
void PDFLibCore::PDF_Begin_Page(const Page* pag, QPixmap pm)
{
QString tmp;
ActPageP = pag;
Content = "";
Seite.AObjects.clear();
if (Options.Thumbnails)
{
ScImage img(pm.toImage());
bool compDataAvail = false;
QByteArray array = img.ImageToArray();
if (Options.Compress)
{
QByteArray compArray = CompressArray(array);
if (compArray.size() > 0)
{
array = compArray;
compDataAvail = true;
}
}
uint thumbnail = newObject();
StartObj(thumbnail);
PutDoc("<<\n/Width "+QString::number(img.width())+"\n");
PutDoc("/Height "+QString::number(img.height())+"\n");
PutDoc("/ColorSpace /DeviceRGB\n/BitsPerComponent 8\n");
PutDoc("/Length "+QString::number(array.size()+1)+"\n");
if (Options.Compress && compDataAvail)
PutDoc("/Filter /FlateDecode\n");
PutDoc(">>\nstream\n");
EncodeArrayToStream(array, thumbnail);
PutDoc("\nendstream\nendobj\n");
Seite.Thumb = thumbnail;
}
}
void PDFLibCore::PDF_End_Page(int physPage)
{
uint PgNr = ActPageP->pageNr();
double markOffs = 0.0;
if ((Options.cropMarks) || (Options.bleedMarks) || (Options.registrationMarks) || (Options.colorMarks) || (Options.docInfoMarks))
markOffs = 20.0 + Options.markOffset;
double bleedRight, bleedLeft;
getBleeds(ActPageP, bleedLeft, bleedRight);
double maxBoxX = ActPageP->width()+bleedLeft+bleedRight+markOffs*2.0;
double maxBoxY = ActPageP->height()+Options.bleeds.Bottom+Options.bleeds.Top+markOffs*2.0;
// (JG) Fix #5977 and #6075 (invalid restore)
//PutPage("Q\n");
if ((Options.cropMarks) || (Options.bleedMarks) || (Options.registrationMarks) || (Options.colorMarks) || (Options.docInfoMarks))
{
PutPage("0.5 w 0 j 0 J [] 0 d\n");
PutPage("/"+spotMapReg["Register"].ResName+" CS 1 SCN\n");
if (Options.cropMarks)
{
// Bottom Left
PutPage("0 "+FToStr(markOffs+Options.bleeds.Bottom)+" m\n");
PutPage(FToStr(20.0)+" "+FToStr(markOffs+Options.bleeds.Bottom)+" l\n");
PutPage("S\n");
PutPage(FToStr(markOffs+bleedLeft)+" 0 m\n");
PutPage(FToStr(markOffs+bleedLeft)+" 20 l\n");
PutPage("S\n");
// Top Left
PutPage("0 "+FToStr(maxBoxY-Options.bleeds.Top-markOffs)+" m\n");
PutPage(FToStr(20.0)+" "+FToStr(maxBoxY-Options.bleeds.Top-markOffs)+" l\n");
PutPage("S\n");
PutPage(FToStr(markOffs+bleedLeft)+" "+FToStr(maxBoxY)+" m\n");
PutPage(FToStr(markOffs+bleedLeft)+" "+FToStr(maxBoxY-20.0)+" l\n");
PutPage("S\n");
// Bottom Right
PutPage(FToStr(maxBoxX)+" "+FToStr(markOffs+Options.bleeds.Bottom)+" m\n");
PutPage(FToStr(maxBoxX-20.0)+" "+FToStr(markOffs+Options.bleeds.Bottom)+" l\n");
PutPage("S\n");
PutPage(FToStr(maxBoxX-bleedRight-markOffs)+" "+FToStr(0.0)+" m\n");
PutPage(FToStr(maxBoxX-bleedRight-markOffs)+" "+FToStr(20.0)+" l\n");
PutPage("S\n");
// Top Right
PutPage(FToStr(maxBoxX)+" "+FToStr(maxBoxY-Options.bleeds.Top-markOffs)+" m\n");
PutPage(FToStr(maxBoxX-20.0)+" "+FToStr(maxBoxY-Options.bleeds.Top-markOffs)+" l\n");
PutPage("S\n");
PutPage(FToStr(maxBoxX-bleedRight-markOffs)+" "+FToStr(maxBoxY)+" m\n");
PutPage(FToStr(maxBoxX-bleedRight-markOffs)+" "+FToStr(maxBoxY-20.0)+" l\n");
PutPage("S\n");
}
if (Options.bleedMarks)
{
PutPage("q\n");
PutPage("[3 1 1 1] 0 d\n");
// Bottom Left
PutPage("0 "+FToStr(markOffs)+" m\n");
PutPage(FToStr(20.0)+" "+FToStr(markOffs)+" l\n");
PutPage("S\n");
PutPage(FToStr(markOffs)+" 0 m\n");
PutPage(FToStr(markOffs)+" 20 l\n");
PutPage("S\n");
// Top Left
PutPage("0 "+FToStr(maxBoxY-markOffs)+" m\n");
PutPage(FToStr(20.0)+" "+FToStr(maxBoxY-markOffs)+" l\n");
PutPage("S\n");
PutPage(FToStr(markOffs)+" "+FToStr(maxBoxY)+" m\n");
PutPage(FToStr(markOffs)+" "+FToStr(maxBoxY-20.0)+" l\n");
PutPage("S\n");
// Bottom Right
PutPage(FToStr(maxBoxX)+" "+FToStr(markOffs)+" m\n");
PutPage(FToStr(maxBoxX-20.0)+" "+FToStr(markOffs)+" l\n");
PutPage("S\n");
PutPage(FToStr(maxBoxX-markOffs)+" "+FToStr(0.0)+" m\n");
PutPage(FToStr(maxBoxX-markOffs)+" "+FToStr(20.0)+" l\n");
PutPage("S\n");
// Top Right
PutPage(FToStr(maxBoxX)+" "+FToStr(maxBoxY-markOffs)+" m\n");
PutPage(FToStr(maxBoxX-20.0)+" "+FToStr(maxBoxY-markOffs)+" l\n");
PutPage("S\n");
PutPage(FToStr(maxBoxX-markOffs)+" "+FToStr(maxBoxY)+" m\n");
PutPage(FToStr(maxBoxX-markOffs)+" "+FToStr(maxBoxY-20.0)+" l\n");
PutPage("S\n");
PutPage("Q\n");
}
if (Options.registrationMarks)
{
QString regCross = "0 7 m\n14 7 l\nh\n7 0 m\n7 14 l\nh\n13 7 m\n13 10.31383 10.31383 13 7 13 c\n3.68629 13 1 10.31383 1 7 c\n1 3.68629 3.68629 1 7 1 c\n";
regCross += "10.31383 1 13 3.68629 13 7 c\nh\n10.5 7 m\n10.5 8.93307 8.93307 10.5 7 10.5 c\n5.067 10.5 3.5 8.93307 3.5 7 c\n";
regCross += "3.5 5.067 5.067 3.5 7 3.5 c\n8.93307 3.5 10.5 5.067 10.5 7 c\nh\nS\n";
PutPage("q\n");
PutPage("1 0 0 1 "+FToStr(maxBoxX / 2.0 - 7.0)+" 3 cm\n");
PutPage(regCross);
PutPage("Q\n");
PutPage("q\n");
PutPage("1 0 0 1 3 "+FToStr(maxBoxY / 2.0 - 7.0)+" cm\n");
PutPage(regCross);
PutPage("Q\n");
PutPage("q\n");
PutPage("1 0 0 1 "+FToStr(maxBoxX / 2.0 - 7.0)+" "+FToStr(maxBoxY - 17.0)+" cm\n");
PutPage(regCross);
PutPage("Q\n");
PutPage("q\n");
PutPage("1 0 0 1 "+FToStr(maxBoxX - 17.0)+" "+FToStr(maxBoxY / 2.0 - 7.0)+" cm\n");
PutPage(regCross);
PutPage("Q\n");
}
if (Options.colorMarks)
{
double startX = markOffs+bleedLeft+6.0;
double startY = maxBoxY - 18.0;
PutPage("0 0 0 1 K\n");
double col = 1.0;
for (int bl = 0; bl < 11; bl++)
{
PutPage("0 0 0 "+FToStr(col)+" k\n");
PutPage(FToStr(startX+bl*14.0)+" "+FToStr(startY)+" 14 14 re B\n");
col -= 0.1;
}
if (!Options.isGrayscale)
{
startX = maxBoxX-bleedRight-markOffs-20.0;
PutPage("0 0 0 0.5 k\n");
PutPage(FToStr(startX)+" "+FToStr(startY)+" 14 14 re B\n");
startX -= 14.0;
PutPage("0 0 0.5 0 k\n");
PutPage(FToStr(startX)+" "+FToStr(startY)+" 14 14 re B\n");
startX -= 14.0;
PutPage("0 0.5 0 0 k\n");
PutPage(FToStr(startX)+" "+FToStr(startY)+" 14 14 re B\n");
startX -= 14.0;
PutPage("0.5 0 0 0 k\n");
PutPage(FToStr(startX)+" "+FToStr(startY)+" 14 14 re B\n");
startX -= 14.0;
PutPage("1 1 0 0 k\n");
PutPage(FToStr(startX)+" "+FToStr(startY)+" 14 14 re B\n");
startX -= 14.0;
PutPage("1 0 1 0 k\n");
PutPage(FToStr(startX)+" "+FToStr(startY)+" 14 14 re B\n");
startX -= 14.0;
PutPage("0 1 1 0 k\n");
PutPage(FToStr(startX)+" "+FToStr(startY)+" 14 14 re B\n");
startX -= 14.0;
PutPage("0 0 0 1 k\n");
PutPage(FToStr(startX)+" "+FToStr(startY)+" 14 14 re B\n");
startX -= 14.0;
PutPage("0 0 1 0 k\n");
PutPage(FToStr(startX)+" "+FToStr(startY)+" 14 14 re B\n");
startX -= 14.0;
PutPage("0 1 0 0 k\n");
PutPage(FToStr(startX)+" "+FToStr(startY)+" 14 14 re B\n");
startX -= 14.0;
PutPage("1 0 0 0 k\n");
PutPage(FToStr(startX)+" "+FToStr(startY)+" 14 14 re B\n");
}
}
if (Options.docInfoMarks)
{
// QString tmp = "";
// double startX = markOffs+bleedLeft+10.0;
FPointArray textPath;
QPainterPath painter1, painter2;
QFont infoFont("Helvetica", 7);
double startX = markOffs+bleedLeft+10.0;
QString docTitle = doc.documentInfo.getTitle();
if (docTitle.isEmpty())
{
QFileInfo fi(doc.DocName);
docTitle = fi.fileName();
}
// docTitle += " "+ tr("Page:")+" "+tmp.setNum(PgNr+1);
docTitle += " "+ tr("Page:")+" "+ QString::number(PgNr+1);
PutPage("/"+spotMapReg["Register"].ResName+" cs 1 scn\n");
PutPage("q\n");
PutPage("1 0 0 1 "+FToStr(startX)+" 6 cm\n");
// PutPage("BT\n");
// PutPage("/"+StdFonts["/Helvetica"]+" 7 Tf\n");
// PutPage(EncString(docTitle, ObjCounter)+" Tj\nET\n");
painter1.addText( QPointF(0.0,0.0), infoFont, docTitle );
textPath.fromQPainterPath(painter1);
PutPage(SetClipPathArray(&textPath, true));
PutPage("h\nf*\n");
PutPage("Q\n");
QDate d = QDate::currentDate();
QString docDate = tr("Date:")+" "+d.toString(Qt::TextDate);
PutPage("q\n");
PutPage("1 0 0 1 "+FToStr(maxBoxX / 2.0 + 20.0)+" 6 cm\n");
// PutPage("BT\n");
// PutPage("/"+StdFonts["/Helvetica"]+" 7 Tf\n");
// QDate d = QDate::currentDate();
// PutPage(EncString(tr("Date:")+" "+d.toString(Qt::TextDate), ObjCounter)+" Tj\nET\n");
painter2.addText( QPointF(0.0,0.0), infoFont, docDate );
textPath.fromQPainterPath(painter2);
PutPage(SetClipPathArray(&textPath, true));
PutPage("h\nf*\n");
PutPage("Q\n");
}
}
Seite.ObjNum = WritePDFStream(Content);
int Gobj = 0;
if (Options.Version >= 14)
{
Gobj = newObject();
StartObj(Gobj);
PutDoc("<< /S /Transparency\n");
if (Options.UseRGB)
PutDoc("/CS /DeviceRGB\n");
else
{
if (Options.isGrayscale)
PutDoc("/CS /DeviceGray\n");
else
{
if ((doc.HasCMS) && (Options.UseProfiles))
PutDoc("/CS "+ICCProfiles[Options.SolidProf].ICCArray+"\n");
else
PutDoc("/CS /DeviceCMYK\n");
}
}
PutDoc(">>\nendobj\n");
}
uint pageObject = newObject();
StartObj(pageObject);
PutDoc("<<\n/Type /Page\n/Parent 4 0 R\n");
PutDoc("/MediaBox [0 0 "+FToStr(maxBoxX)+" "+FToStr(maxBoxY)+"]\n");
PutDoc("/BleedBox ["+FToStr(markOffs)+" "+FToStr(markOffs)+" "+FToStr(maxBoxX-markOffs)+" "+FToStr(maxBoxY-markOffs)+"]\n");
PutDoc("/CropBox [0 0 "+FToStr(maxBoxX)+" "+FToStr(maxBoxY)+"]\n");
PutDoc("/TrimBox ["+FToStr(bleedLeft+markOffs)+" "+FToStr(Options.bleeds.Bottom+markOffs)+" "+FToStr(maxBoxX-bleedRight-markOffs)+" "+FToStr(maxBoxY-Options.bleeds.Top-markOffs)+"]\n");
if (Options.Version >= PDFOptions::PDFVersion_13) // PDF/X forbids having both art and trim box!
PutDoc("/ArtBox ["+FToStr(bleedLeft+markOffs)+" "+FToStr(Options.bleeds.Bottom+markOffs)+" "+FToStr(maxBoxX-bleedRight-markOffs)+" "+FToStr(maxBoxY-Options.bleeds.Top-markOffs)+"]\n");
PutDoc("/Rotate "+QString::number(Options.RotateDeg)+"\n");
PutDoc("/Contents "+QString::number(Seite.ObjNum)+" 0 R\n");
if (Options.Version >= PDFOptions::PDFVersion_14) // && (Transpar.count() != 0))
PutDoc("/Group "+QString::number(Gobj)+" 0 R\n");
if (Options.Thumbnails)
PutDoc("/Thumb "+QString::number(Seite.Thumb)+" 0 R\n");
if (Seite.AObjects.count() != 0)
{
PutDoc("/Annots [ ");
for (int b = 0; b < Seite.AObjects.count(); ++b)
PutDoc(QString::number(Seite.AObjects[b])+" 0 R ");
PutDoc("]\n");
}
if (Options.PresentMode)
{
if (Options.PresentVals[PgNr].pageViewDuration > 0)
PutDoc("/Dur "+QString::number(Options.PresentVals[PgNr].pageViewDuration)+"\n");
if (Options.PresentVals[PgNr].effectType != 0)
{
PutDoc("/Trans << /Type /Trans\n");
PutDoc("/D "+QString::number(Options.PresentVals[PgNr].pageEffectDuration)+"\n");
switch (Options.PresentVals[PgNr].effectType)
{
case 1:
PutDoc("/S /Blinds\n");
PutDoc(Options.PresentVals[PgNr].Dm == 0 ? "/Dm /H\n" : "/Dm /V\n");
break;
case 2:
PutDoc("/S /Box\n");
PutDoc(Options.PresentVals[PgNr].M == 0 ? "/M /I\n" : "/M /O\n");
break;
case 3:
PutDoc("/S /Dissolve\n");
break;
case 4:
PutDoc("/S /Glitter\n");
PutDoc("/Di ");
switch (Options.PresentVals[PgNr].Di)
{
case 0:
PutDoc("0");
break;
case 1:
PutDoc("270");
break;
case 4:
PutDoc("315");
break;
default:
PutDoc("0");
break;
}
PutDoc("\n");
break;
case 5:
PutDoc("/S /Split\n");
PutDoc(Options.PresentVals[PgNr].Dm == 0 ? "/Dm /H\n" : "/Dm /V\n");
PutDoc(Options.PresentVals[PgNr].M == 0 ? "/M /I\n" : "/M /O\n");
break;
case 6:
PutDoc("/S /Wipe\n");
PutDoc("/Di ");
switch (Options.PresentVals[PgNr].Di)
{
case 0:
PutDoc("0");
break;
case 1:
PutDoc("270");
break;
case 2:
PutDoc("90");
break;
case 3:
PutDoc("180");
break;
default:
PutDoc("0");
break;
}
PutDoc("\n");
break;
case 7:
PutDoc("/S /Push\n");
PutDoc("/Di ");
switch (Options.PresentVals[PgNr].Di)
{
case 0:
PutDoc("0");
break;
case 1:
PutDoc("270");
break;
case 2:
PutDoc("90");
break;
case 3:
PutDoc("180");
break;
default:
PutDoc("0");
break;
}
PutDoc("\n");
break;
case 8:
PutDoc("/S /Cover\n");
PutDoc("/Di ");
switch (Options.PresentVals[PgNr].Di)
{
case 0:
PutDoc("0");
break;
case 1:
PutDoc("270");
break;
case 2:
PutDoc("90");
break;
case 3:
PutDoc("180");
break;
default:
PutDoc("0");
break;
}
PutDoc("\n");
break;
case 9:
PutDoc("/S /Uncover\n");
PutDoc("/Di ");
switch (Options.PresentVals[PgNr].Di)
{
case 0:
PutDoc("0");
break;
case 1:
PutDoc("270");
break;
case 2:
PutDoc("90");
break;
case 3:
PutDoc("180");
break;
default:
PutDoc("0");
break;
}
PutDoc("\n");
break;
case 10:
PutDoc("/S /Fade\n");
break;
}
PutDoc(">>\n");
}
}
PutDoc(">>\nendobj\n");
PageTree.Kids.append(pageObject);
PageTree.KidsMap[ActPageP->pageNr()] = pageObject;
}
void PDFLibCore::writeXObject(uint objNr, QString dictionary, QByteArray stream)
{
StartObj(objNr);
PutDoc("<<");
PutDoc(dictionary);
PutDoc(">>\nstream\n");
EncodeArrayToStream(stream, objNr);
PutDoc("\nendstream\nendobj\n");
}
uint PDFLibCore::writeObject(QString type, QString dictionary)
{
uint result = newObject();
StartObj(result);
PutDoc("<<");
if (!type.isEmpty())
PutDoc("/Type " + type + "\n");
PutDoc(dictionary);
PutDoc(">>\nendobj\n");
return result;
}
bool PDFLibCore::PDF_ProcessPage(const Page* pag, uint PNr, bool clip)
{
QStack<PageItem*> groupStack;
QStack<PageItem*> groupStackS;
QStack<QString> groupDataStack;
QString tmp, output;
ActPageP = pag;
PageItem* ite;
QList<PageItem*> PItems;
int Lnr = 0;
ScLayer ll;
ll.isPrintable = false;
ll.LNr = 0;
if (Options.UseLPI)
PutPage("/"+HTName+" gs\n");
double bleedRight = 0.0;
double bleedLeft = 0.0;
double bleedBottom = 0.0;
double bleedTop = 0.0;
double markOffs = 0.0;
bleedDisplacementX = 0.0;
bleedDisplacementY = 0.0;
PutPage("q\n"); // Save
if ((Options.cropMarks) || (Options.bleedMarks) || (Options.registrationMarks) || (Options.colorMarks) || (Options.docInfoMarks))
markOffs = 20.0 + Options.markOffset;
// #8773 - incorrect page position if MPageNam.isEmpty()
/*if (!pag->MPageNam.isEmpty())
{*/
getBleeds(ActPageP, bleedLeft, bleedRight, bleedBottom, bleedTop);
PutPage("1 0 0 1 "+FToStr(bleedLeft+markOffs)+" "+FToStr(Options.bleeds.Bottom+markOffs)+" cm\n");
bleedDisplacementX = bleedLeft+markOffs;
bleedDisplacementY = Options.bleeds.Bottom+markOffs;
/*}*/
//#9385 : clip to BleedBox
if ((Options.cropMarks) || (Options.bleedMarks) || (Options.registrationMarks) || (Options.colorMarks) || (Options.docInfoMarks))
{
double bbWidth = ActPageP->width() + bleedLeft + bleedRight;
double bbHeight = ActPageP->height() + bleedBottom + bleedTop;
PutPage( QString("%1 %2 %3 %4 re W n\n").arg(FToStr(-bleedLeft)).arg(FToStr(-bleedBottom)).arg(FToStr(bbWidth)).arg(FToStr(bbHeight)) );
}
if ( (Options.MirrorH) && (!pag->MPageNam.isEmpty()) )
PutPage("-1 0 0 1 "+FToStr(ActPageP->width())+" 0 cm\n");
if ( (Options.MirrorV) && (!pag->MPageNam.isEmpty()) )
PutPage("1 0 0 -1 0 "+FToStr(ActPageP->height())+" cm\n");
if (clip)
{
double maxBoxX = ActPageP->width() - ActPageP->Margins.Right - ActPageP->Margins.Left;
double maxBoxY = ActPageP->height() - ActPageP->Margins.Top - ActPageP->Margins.Bottom;
PutPage(FToStr(ActPageP->Margins.Left)+" "+FToStr(ActPageP->Margins.Bottom)+" "+FToStr(maxBoxX)+" "+FToStr(maxBoxY)+" re W n\n");
// PutPage("0 0 "+FToStr(ActPageP->width())+" "+FToStr(ActPageP->height())+" re W n\n");
}
if (!pag->MPageNam.isEmpty() && (doc.MasterItems.count() != 0))
{
const Page* mPage = doc.MasterPages.at(doc.MasterNames[doc.DocPages.at(PNr)->MPageNam]);
int mPageIndex = doc.MasterPages.indexOf((Page* const) mPage) + 1;
if (!Options.MirrorH)
PutPage("1 0 0 1 0 0 cm\n");
for (int lam = 0; lam < doc.Layers.count() && !abortExport; ++lam)
{
doc.Layers.levelToLayer(ll, Lnr);
Lnr++;
if ((ll.isPrintable) || ((Options.Version == PDFOptions::PDFVersion_15) && (Options.useLayers)))
{
QString inh;
if ((Options.Version == PDFOptions::PDFVersion_15) && (Options.useLayers))
PutPage("/OC /"+OCGEntries[ll.Name].Name+" BDC\n");
for (int am = 0; am < pag->FromMaster.count() && !abortExport; ++am)
{
ite = pag->FromMaster.at(am);
if (usingGUI