Debian Codegraph @

podofo/tools/podofoimpose/pdftranslator.cpp

raw
1 /**
2 * SPDX-FileCopyrightText: (C) 2007 Pierre Marchand <[email protected]>
3 * SPDX-License-Identifier: GPL-2.0-or-later
4 */
5
6 #include <podofo/private/PdfDeclarationsPrivate.h>
7 #include "pdftranslator.h"
8
9 #include <fstream>
10 #include <stdexcept>
11 #include <algorithm>
12 #include <cmath>
13 #include <istream>
14 #include <ostream>
15 #include <cstdlib>
16 #include <iostream>
17
18 #include "planreader_legacy.h"
19
20 #ifdef PODOFO_HAVE_LUA
21 #include "planreader_lua.h"
22 #endif
23
24 #define MAX_SOURCE_PAGES 5000
25 #define MAX_RECORD_SIZE 2048
26
27 using namespace std;
28 using namespace PoDoFo;
29 using namespace PoDoFo::Impose;
30
31 bool PdfTranslator::checkIsPDF(string path)
32 {
33 ifstream in(path.c_str(), ifstream::in);
34 if (!in.good())
35 throw runtime_error("setSource() failed to open input file");
36
37 const int magicBufferLen = 5;
38 char magicBuffer[magicBufferLen];
39 in.read(magicBuffer, magicBufferLen);
40 string magic(magicBuffer, magicBufferLen);
41
42 in.close();
43 if (magic.find("%PDF") < 5)
44 return true;
45 // throw runtime_error("First bytes of the file tend to indicate it is not a PDF file");
46 return false;
47 }
48
49 PdfTranslator::PdfTranslator()
50 {
51 cerr << "PdfTranslator::PdfTranslator" << endl;
52 sourceDoc = nullptr;
53 targetDoc = nullptr;
54 planImposition = nullptr;
55 duplicate = 0;
56 extraSpace = 0;
57 scaleFactor = 1.0;
58 pageCount = 0;
59 sourceWidth = 0.0;
60 sourceHeight = 0.0;
61 destWidth = 0.0;
62 destHeight = 0.0;
63 }
64
65 void PdfTranslator::setSource(const string& source)
66 {
67 int dbg = 0;
68 // cerr<<"PdfTranslator::setSource "<<source<<endl;
69 cerr << ++dbg << endl;
70 if (checkIsPDF(source))
71 {
72 // cerr << "Appending "<<source<<" to source" << endl;
73 multiSource.push_back(source);
74 }
75 else
76 {
77 ifstream in(source.c_str(), ifstream::in);
78 if (!in.good())
79 throw runtime_error("setSource() failed to open input file");
80
81 char* filenameBuffer = new char[1000];
82 do
83 {
84 if (!in.getline(filenameBuffer, 1000))
85 throw runtime_error("failed reading line from input file");
86
87 string ts(filenameBuffer, (size_t)in.gcount());
88 if (ts.size() > 4) // at least ".pdf" because just test if ts is empty doesn't work.
89 {
90 multiSource.push_back(ts);
91 cerr << "Appending " << ts << " to source" << endl;
92 }
93 } while (!in.eof());
94 in.close();
95 delete[] filenameBuffer;
96 }
97 cerr << ++dbg << endl;
98
99 if (multiSource.empty())
100 throw runtime_error("No recognized source given");
101
102 for (vector<string>::const_iterator ms = multiSource.begin(); ms != multiSource.end(); ms++)
103 {
104 if (ms == multiSource.begin())
105 {
106 // cerr << "First doc is "<< (*ms).c_str() << endl;
107 try
108 {
109 sourceDoc = new PdfMemDocument();
110 sourceDoc->Load(*ms);
111 }
112 catch (PdfError& e)
113 {
114 cerr << "Unable to create Document: " << PdfError::ErrorMessage(e.GetCode()) << endl;
115 return;
116 }
117 }
118 else
119 {
120 PdfMemDocument mdoc;
121 mdoc.Load(*ms);
122 // cerr << "Appending "<< mdoc.GetPageCount() << " page(s) of " << *ms << endl;
123 sourceDoc->GetPages().AppendDocumentPages(mdoc, 0, mdoc.GetPages().GetCount());
124 }
125 }
126
127 pageCount = sourceDoc->GetPages().GetCount();
128 // cerr << "Document has "<< pcount << " page(s) " << endl;
129 if (pageCount > 0) // only here to avoid possible segfault, but PDF without page is not conform IIRC
130 {
131 auto& firstPage = sourceDoc->GetPages().GetPageAt(0);
132
133 Rect rect(firstPage.GetMediaBox());
134 // keep in mind it’s just a hint since PDF can have different page sizes in a same doc
135 sourceWidth = rect.Width - rect.X;
136 sourceHeight = rect.Height - rect.Y;
137 }
138 }
139
140 void PdfTranslator::addToSource(const string& source)
141 {
142 // cerr<<"PdfTranslator::addToSource "<< source<<endl;
143 if (!sourceDoc)
144 return;
145
146 PdfMemDocument extraDoc;
147 extraDoc.Load(source);
148 sourceDoc->GetPages().AppendDocumentPages(extraDoc, 0, extraDoc.GetPages().GetCount());
149 multiSource.push_back(source);
150
151 }
152
153 PdfObject* PdfTranslator::migrateResource(PdfObject* obj)
154 {
155 // cerr<<"PdfTranslator::migrateResource"<<endl;
156 PdfObject* ret = nullptr;
157
158 if (!obj)
159 PODOFO_RAISE_ERROR_INFO(PdfErrorCode::InvalidHandle, "migrateResource called"
160 " with nullptr object");
161
162 if (obj->IsDictionary())
163 {
164 if (obj->GetIndirectReference().IsIndirect())
165 ret = &targetDoc->GetObjects().CreateObject(*obj);
166 else
167 ret = new PdfObject(*obj);
168
169 for (auto& pair : obj->GetDictionary())
170 {
171 PdfObject* o = &pair.second;
172 auto res = setMigrationPending.insert(o);
173 if (!res.second)
174 {
175 ostringstream oss;
176 oss << "Cycle detected: Object with ref " << o->GetIndirectReference().ToString()
177 << " is already pending migration to the target.\n";
178 PoDoFo::LogMessage(PdfLogSeverity::Warning, oss.str());
179 continue;
180 }
181 PdfObject* migrated = migrateResource(o);
182 if (migrated != nullptr)
183 {
184 ret->GetDictionary().AddKey(pair.first, *migrated);
185 if (!(migrated->GetIndirectReference().IsIndirect()))
186 delete migrated;
187 }
188 }
189
190 if (obj->HasStream())
191 {
192 *(ret->GetStream()) = *(obj->GetStream());
193 }
194 }
195 else if (obj->IsArray())
196 {
197 PdfArray carray(obj->GetArray());
198 PdfArray narray;
199 for (unsigned ci = 0; ci < carray.GetSize(); ci++)
200 {
201 PdfObject* co(migrateResource(&carray[ci]));
202 if (co == nullptr)
203 continue;
204
205 narray.Add(*co);
206 if (!(co->GetIndirectReference().IsIndirect()))
207 {
208 delete co;
209 }
210 }
211 if (obj->GetIndirectReference().IsIndirect())
212 {
213 ret = &targetDoc->GetObjects().CreateObject(narray);
214 }
215 else
216 {
217 ret = new PdfObject(narray);
218 }
219 }
220 else if (obj->IsReference())
221 {
222 if (migrateMap.find(obj->GetReference().ToString()) != migrateMap.end())
223 {
224 ostringstream oss;
225 oss << "Referenced object " << obj->GetReference().ToString()
226 << " already migrated." << endl;
227 PoDoFo::LogMessage(PdfLogSeverity::Debug, oss.str());
228
229 const PdfObject* const found = migrateMap[obj->GetReference().ToString()];
230 return new PdfObject(found->GetIndirectReference());
231 }
232
233 PdfObject* to_migrate = sourceDoc->GetObjects().GetObject(obj->GetReference());
234
235 pair<set<PdfObject*>::iterator, bool> res
236 = setMigrationPending.insert(to_migrate);
237 if (!res.second)
238 {
239 ostringstream oss;
240 oss << "Cycle detected: Object with ref " << obj->GetReference().ToString()
241 << " is already pending migration to the target.\n";
242 PoDoFo::LogMessage(PdfLogSeverity::Warning, oss.str());
243 return nullptr; // skip this migration
244 }
245 PdfObject* o(migrateResource(to_migrate));
246 if (nullptr != o)
247 ret = new PdfObject(o->GetIndirectReference());
248 else
249 return nullptr; // avoid going through rest of method
250 }
251 else if (obj->IsName())
252 {
253 ret = &targetDoc->GetObjects().CreateObject(obj->GetName());
254 }
255 else if (obj->IsNumber())
256 {
257 ret = &targetDoc->GetObjects().CreateObject(obj->GetNumber());
258 }
259 else if (obj->IsNull())
260 {
261 ret = &targetDoc->GetObjects().CreateDictionaryObject();
262 }
263 else
264 {
265 ret = new PdfObject(*obj);//targetDoc->GetObjects().CreateObject(*obj);
266 }
267
268 if (obj->GetIndirectReference().IsIndirect())
269 {
270 migrateMap.insert(pair<string, PdfObject*>(obj->GetIndirectReference().ToString(), ret));
271 }
272
273 return ret;
274 }
275
276 PdfObject* PdfTranslator::getInheritedResources(PdfPage& page)
277 {
278 // cerr<<"PdfTranslator::getInheritedResources"<<endl;
279 PdfObject* res(0);
280 // mabri: resources are inherited as whole dict, not at all if the page has the dict
281 // mabri: specified in PDF32000_2008.pdf section 7.7.3.4 Inheritance of Page Attributes
282 // mabri: and in section 7.8.3 Resource Dictionaries
283 PdfObject* sourceRes = page.GetDictionary().FindKeyParent("Resources");
284 if (sourceRes)
285 {
286 res = migrateResource(sourceRes);
287 }
288 return res;
289 }
290
291 void PdfTranslator::setTarget(const string& target)
292 {
293 // cerr<<"PdfTranslator::setTarget "<<target<<endl;
294 if (!sourceDoc)
295 throw logic_error("setTarget() called before setSource()");
296
297 targetDoc = new PdfMemDocument;
298 outFilePath = target;
299
300 for (unsigned i = 0; i < pageCount; i++)
301 {
302 auto& page = sourceDoc->GetPages().GetPageAt(i);
303 charbuff buff;
304 BufferStreamDevice outMemStream(buff);
305
306
307 auto xobj = sourceDoc->CreateXObjectForm(page.GetMediaBox());
308 if (page.GetContents() != nullptr)
309 page.GetContents()->CopyTo(outMemStream);
310
311 /// Its time to manage other keys of the page dictionary.
312 vector<string> pageKeys;
313 vector<string>::const_iterator itKey;
314 pageKeys.push_back("Group");
315 for (itKey = pageKeys.begin(); itKey != pageKeys.end(); itKey++)
316 {
317 PdfName keyname(*itKey);
318 if (page.GetDictionary().HasKey(keyname))
319 {
320 PdfObject* migObj = migrateResource(page.GetDictionary().GetKey(keyname));
321 if (nullptr == migObj)
322 continue;
323 xobj->GetDictionary().AddKey(keyname, *migObj);
324 }
325 }
326
327 outMemStream.Close();
328
329 xobj->GetObject().GetOrCreateStream().SetData(buff);
330
331 resources[i + 1] = getInheritedResources(page);
332 xobjects[i + 1] = xobj.get();
333 cropRect[i + 1] = page.GetCropBox();
334 bleedRect[i + 1] = page.GetBleedBox();
335 trimRect[i + 1] = page.GetTrimBox();
336 artRect[i + 1] = page.GetArtBox();
337 }
338
339 targetDoc->GetMetadata().SetPdfVersion(sourceDoc->GetMetadata().GetPdfVersion());
340
341 auto& sourceMetadata = sourceDoc->GetMetadata();
342 auto& targetMetadata = targetDoc->GetMetadata();
343
344 if (sourceMetadata.GetAuthor().has_value())
345 targetMetadata.SetAuthor(*sourceMetadata.GetAuthor());
346 if (sourceMetadata.GetCreator().has_value())
347 targetMetadata.SetCreator(*sourceMetadata.GetCreator());
348 if (sourceMetadata.GetSubject().has_value())
349 targetMetadata.SetSubject(*sourceMetadata.GetSubject());
350 if (sourceMetadata.GetTitle().has_value())
351 targetMetadata.SetTitle(*sourceMetadata.GetTitle());
352 if (sourceMetadata.GetKeywords().size() != 0)
353 targetMetadata.SetKeywords(sourceMetadata.GetKeywords());
354 if (sourceMetadata.GetTrapped().has_value())
355 targetMetadata.SetTrapped(*sourceMetadata.GetTrapped());
356
357 // PdfObject *scat( sourceDoc->GetCatalog() );
358 // PdfObject *tcat( targetDoc->GetCatalog() );
359 // TKeyMap catmap = scat->GetDictionary().GetKeys();
360 // for ( TCIKeyMap itc = catmap.begin(); itc != catmap.end(); ++itc )
361 // {
362 // if(tcat->GetDictionary().GetKey(itc->first) == 0)
363 // {
364 // PdfObject *o = itc->second;
365 // tcat->GetDictionary().AddKey (itc->first , migrateResource( o ) );
366 // }
367 // }
368
369 // delete sourceDoc;
370 }
371
372 void PdfTranslator::transform(double a, double b, double c, double d, double e, double f)
373 {
374 if (transformMatrix.empty()) {
375 transformMatrix.push_back(a);
376 transformMatrix.push_back(b);
377 transformMatrix.push_back(c);
378 transformMatrix.push_back(d);
379 transformMatrix.push_back(e);
380 transformMatrix.push_back(f);
381
382 }
383 else {
384 vector<double> m0 = transformMatrix;
385 vector<double> m;
386
387 m.push_back(m0.at(0) * a + m0.at(1) * c);
388 m.push_back(m0.at(0) * b + m0.at(1) * d);
389 m.push_back(m0.at(2) * a + m0.at(3) * c);
390 m.push_back(m0.at(2) * b + m0.at(3) * d);
391
392 m.push_back(m0.at(4) * a + m0.at(5) * c + e);
393 m.push_back(m0.at(4) * b + m0.at(5) * d + f);
394
395 transformMatrix = m;
396 }
397 }
398
399 void PdfTranslator::rotate_and_translate(double theta, double dx, double dy)
400 {
401 double cosR = cos(theta * 3.14159 / 180.0);
402 double sinR = sin(theta * 3.14159 / 180.0);
403 transform(cosR, sinR, -sinR, cosR, dx, dy);
404 }
405
406 void PdfTranslator::translate(double dx, double dy)
407 {
408 transform(1, 0, 0, 1, dx, dy);
409 }
410
411 void PdfTranslator::scale(double sx, double sy)
412 {
413 transform(sx, 0, 0, sy, 0, 0);
414 }
415
416 void PdfTranslator::rotate(double theta)
417 {
418 double cosR = cos(theta * 3.14159 / 180.0);
419 double sinR = sin(theta * 3.14159 / 180.0);
420 // Counter-clockwise rotation (default):
421 transform(cosR, sinR, -sinR, cosR, 0, 0);
422 // Clockwise rotation:
423 // transform(cosR, -sinR, sinR, cosR, 0, 0);
424 }
425
426 void PdfTranslator::loadPlan(const string& planFile, PlanReader loader)
427 {
428 // cerr<< "loadPlan" << planFile<<endl;
429 SourceVars sv;
430 sv.PageCount = pageCount;
431 sv.PageHeight = sourceHeight;
432 sv.PageWidth = sourceWidth;
433 planImposition = new ImpositionPlan(sv);
434 if (loader == PlanReader::Legacy)
435 {
436 PlanReader_Legacy(planFile, planImposition);
437 }
438 #if defined(PODOFO_HAVE_LUA)
439 else if (loader == PlanReader::Lua)
440 {
441 PlanReader_Lua(planFile, planImposition);
442 }
443 #endif
444
445 if (!planImposition->valid())
446 throw runtime_error("Unable to build a valid imposition plan");
447
448 destWidth = planImposition->destWidth();
449 destHeight = planImposition->destHeight();
450 scaleFactor = planImposition->scale();
451 boundingBox = planImposition->boundingBox();
452 // cerr <<"Plan completed "<< planImposition.size() <<endl;
453
454 }
455
456 void PdfTranslator::impose()
457 {
458 // cerr<<"PdfTranslator::impose"<<endl;
459 if (!targetDoc)
460 throw invalid_argument("impose() called with empty target");
461
462 // PdfObject trimbox;
463 // Rect trim ( 0, 0, destWidth, destHeight );
464 // trim.ToVariant ( trimbox );
465 map<int, Rect>* bbIndex = nullptr;
466 if (boundingBox.size() > 0)
467 {
468 if (boundingBox.find("crop") != string::npos)
469 {
470 bbIndex = &cropRect;
471 }
472 else if (boundingBox.find("bleed") != string::npos)
473 {
474 bbIndex = &bleedRect;
475 }
476 else if (boundingBox.find("trim") != string::npos)
477 {
478 bbIndex = &trimRect;
479 }
480 else if (boundingBox.find("art") != string::npos)
481 {
482 bbIndex = &artRect;
483 }
484 }
485
486 typedef map<int, vector<PageRecord> > groups_t;
487 groups_t groups;
488 for (unsigned i = 0; i < planImposition->size(); i++)
489 {
490 groups[(*planImposition)[i].destPage].push_back((*planImposition)[i]);
491 }
492
493 unsigned int lastPlate(0);
494 groups_t::const_iterator git = groups.begin();
495 const groups_t::const_iterator gitEnd = groups.end();
496 while (git != gitEnd)
497 {
498 PdfPage* newpage = nullptr;
499 // Allow "holes" in dest. pages sequence.
500 unsigned int curPlate(git->first);
501 while (lastPlate != curPlate)
502 {
503 newpage = &targetDoc->GetPages().CreatePage(Rect(0.0, 0.0, destWidth, destHeight));
504 lastPlate++;
505 }
506 // newpage->GetObject()->GetDictionary().AddKey ( PdfName ( "TrimBox" ), trimbox );
507 PdfDictionary xdict;
508
509 ostringstream buffer;
510 // Scale
511 buffer << fixed << scaleFactor << " 0 0 " << scaleFactor << " 0 0 cm\n";
512
513 for (unsigned int i = 0; i < git->second.size(); i++)
514 {
515 PageRecord curRecord(git->second[i]);
516 // cerr<<curRecord.sourcePage<< " " << curRecord.destPage<<endl;
517 if (curRecord.sourcePage <= pageCount)
518 {
519 double rot = curRecord.rotate;
520 double tx = curRecord.transX;
521 double ty = curRecord.transY;
522 double sx = curRecord.scaleX;
523 double sy = curRecord.scaleY;
524
525 int resourceIndex( /*(curRecord.duplicateOf > 0) ? curRecord.duplicateOf : */curRecord.sourcePage);
526 PdfXObjectForm* xo = xobjects[resourceIndex];
527 if (nullptr != bbIndex)
528 {
529 PdfArray bb;
530 // DominikS: Fix compilation using Visual Studio on Windows
531 // mabri: ML post archive URL is https://sourceforge.net/p/podofo/mailman/message/24609746/
532 // bbIndex->at(resourceIndex).ToVariant( bb );
533 ((*bbIndex)[resourceIndex]).ToArray(bb);
534 xo->GetDictionary().AddKey("BBox", bb);
535 }
536 ostringstream op;
537 op << "OriginalPage" << resourceIndex;
538 xdict.AddKey(PdfName(op.str()), xo->GetObject().GetIndirectReference());
539
540 if (resources[resourceIndex])
541 {
542 if (resources[resourceIndex]->IsDictionary())
543 {
544 for (auto& pair : resources[resourceIndex]->GetDictionary())
545 {
546 xo->GetOrCreateResources().GetDictionary().AddKey(pair.first, pair.second);
547 }
548 }
549 else if (resources[resourceIndex]->IsReference())
550 {
551 xo->GetDictionary().AddKey("Resources", *resources[resourceIndex]);
552 }
553 else
554 {
555 cerr << "ERROR Unknown type resource " << resources[resourceIndex]->GetDataTypeString() << endl;
556 }
557
558 }
559 // Make sure we start with an empty transformMatrix.
560 transformMatrix.clear();
561 translate(0, 0);
562 // 1. Rotate, 2. Translate, 3. Scale
563 if (rot != 0 || tx != 0 || ty != 0) {
564 rotate_and_translate(rot, tx, ty);
565 }
566 scale(sx, sy);
567
568 // Very primitive but it makes it easy to track down imposition plan into content stream.
569 buffer << "q\n";
570 buffer << fixed << transformMatrix[0] << " " << transformMatrix[1] << " " << transformMatrix[2] << " " << transformMatrix[3] << " " << transformMatrix[4] << " " << transformMatrix[5] << " cm\n";
571 buffer << "/OriginalPage" << resourceIndex << " Do\n";
572 buffer << "Q\n";
573 }
574 }
575
576 if (!newpage)
577 PODOFO_RAISE_ERROR(PdfErrorCode::ValueOutOfRange);
578
579 string bufStr = buffer.str();
580 newpage->GetOrCreateContents().CreateStreamForAppending().SetData(bufStr);
581 newpage->GetResources().GetDictionary().AddKey(PdfName("XObject"), xdict);
582 git++;
583 }
584
585 targetDoc->Save(outFilePath);
586
587 // The following is necessary to avoid line 195 being detected as allocation having a memory leak
588 // without changing other files than this one (thorough leak prevention shall be applied later).
589 for (map<int, PdfObject*>::iterator it = resources.begin(); it != resources.end(); it++)
590 delete (*it).second;
591
592 resources.clear();
593 }