Line data Source code
1 : /******************************************************************************
2 : *
3 : * Project: PDF driver
4 : * Purpose: GDALDataset driver for PDF dataset.
5 : * Author: Even Rouault, <even dot rouault at spatialys.com>
6 : *
7 : ******************************************************************************
8 : *
9 : * Support for open-source PDFium library
10 : *
11 : * Copyright (C) 2015 Klokan Technologies GmbH (http://www.klokantech.com/)
12 : * Author: Martin Mikita <martin.mikita@klokantech.com>, xmikit00 @ FIT VUT Brno
13 : *
14 : ******************************************************************************
15 : * Copyright (c) 2010-2014, Even Rouault <even dot rouault at spatialys.com>
16 : *
17 : * SPDX-License-Identifier: MIT
18 : ****************************************************************************/
19 :
20 : #include "gdal_pdf.h"
21 :
22 : #include "cpl_json_streaming_writer.h"
23 : #include "cpl_vsi_virtual.h"
24 : #include "cpl_spawn.h"
25 : #include "cpl_string.h"
26 : #include "gdal_frmts.h"
27 : #include "gdalalgorithm.h"
28 : #include "ogr_spatialref.h"
29 : #include "ogr_geometry.h"
30 :
31 : #ifdef HAVE_POPPLER
32 : #include "cpl_multiproc.h"
33 : #include "pdfio.h"
34 : #endif // HAVE_POPPLER
35 :
36 : #include "pdfcreatecopy.h"
37 :
38 : #include "pdfdrivercore.h"
39 :
40 : #include <algorithm>
41 : #include <cassert>
42 : #include <limits>
43 : #include <set>
44 :
45 : #ifdef HAVE_PDFIUM
46 : // To be able to use
47 : // https://github.com/rouault/pdfium_build_gdal_3_5/releases/download/v1_pdfium_5106/install-win10-vs2019-x64-rev5106.zip
48 : // with newer Visual Studio versions.
49 : // Trick from https://github.com/conan-io/conan-center-index/issues/4826
50 : #if _MSC_VER >= 1932 // Visual Studio 2022 version 17.2+
51 : #pragma comment( \
52 : linker, \
53 : "/alternatename:__imp___std_init_once_complete=__imp_InitOnceComplete")
54 : #pragma comment( \
55 : linker, \
56 : "/alternatename:__imp___std_init_once_begin_initialize=__imp_InitOnceBeginInitialize")
57 : #endif
58 : #endif
59 :
60 : /* g++ -fPIC -g -Wall frmts/pdf/pdfdataset.cpp -shared -o gdal_PDF.so -Iport
61 : * -Igcore -Iogr -L. -lgdal -lpoppler -I/usr/include/poppler */
62 :
63 : #ifdef HAVE_PDF_READ_SUPPORT
64 :
65 : static double Get(GDALPDFObject *poObj, int nIndice = -1);
66 :
67 : #ifdef HAVE_POPPLER
68 :
69 : static CPLMutex *hGlobalParamsMutex = nullptr;
70 :
71 : /************************************************************************/
72 : /* GDALPDFOutputDev */
73 : /************************************************************************/
74 :
75 : class GDALPDFOutputDev : public SplashOutputDev
76 : {
77 : private:
78 : int bEnableVector;
79 : int bEnableText;
80 : int bEnableBitmap;
81 :
82 0 : void skipBytes(Stream *str, int width, int height, int nComps, int nBits)
83 : {
84 0 : int nVals = width * nComps;
85 0 : int nLineSize = (nVals * nBits + 7) >> 3;
86 0 : int nBytes = nLineSize * height;
87 0 : for (int i = 0; i < nBytes; i++)
88 : {
89 0 : if (str->getChar() == EOF)
90 0 : break;
91 : }
92 0 : }
93 :
94 : public:
95 47 : GDALPDFOutputDev(SplashColorMode colorModeA, int bitmapRowPadA,
96 : bool reverseVideoA, SplashColorPtr paperColorA)
97 47 : : SplashOutputDev(colorModeA, bitmapRowPadA, reverseVideoA,
98 : paperColorA),
99 47 : bEnableVector(TRUE), bEnableText(TRUE), bEnableBitmap(TRUE)
100 : {
101 47 : }
102 :
103 11 : void SetEnableVector(int bFlag)
104 : {
105 11 : bEnableVector = bFlag;
106 11 : }
107 :
108 11 : void SetEnableText(int bFlag)
109 : {
110 11 : bEnableText = bFlag;
111 11 : }
112 :
113 11 : void SetEnableBitmap(int bFlag)
114 : {
115 11 : bEnableBitmap = bFlag;
116 11 : }
117 :
118 : virtual void startPage(int pageNum, GfxState *state, XRef *xrefIn) override;
119 :
120 1673 : virtual void stroke(GfxState *state) override
121 : {
122 1673 : if (bEnableVector)
123 1664 : SplashOutputDev::stroke(state);
124 1673 : }
125 :
126 8 : virtual void fill(GfxState *state) override
127 : {
128 8 : if (bEnableVector)
129 8 : SplashOutputDev::fill(state);
130 8 : }
131 :
132 38 : virtual void eoFill(GfxState *state) override
133 : {
134 38 : if (bEnableVector)
135 32 : SplashOutputDev::eoFill(state);
136 38 : }
137 :
138 4295 : virtual void drawChar(GfxState *state, double x, double y, double dx,
139 : double dy, double originX, double originY,
140 : CharCode code, int nBytes, const Unicode *u,
141 : int uLen) override
142 : {
143 4295 : if (bEnableText)
144 4259 : SplashOutputDev::drawChar(state, x, y, dx, dy, originX, originY,
145 : code, nBytes, u, uLen);
146 4295 : }
147 :
148 681 : virtual void beginTextObject(GfxState *state) override
149 : {
150 681 : if (bEnableText)
151 678 : SplashOutputDev::beginTextObject(state);
152 681 : }
153 :
154 681 : virtual void endTextObject(GfxState *state) override
155 : {
156 681 : if (bEnableText)
157 678 : SplashOutputDev::endTextObject(state);
158 681 : }
159 :
160 0 : virtual void drawImageMask(GfxState *state, Object *ref, Stream *str,
161 : int width, int height, bool invert,
162 : bool interpolate, bool inlineImg) override
163 : {
164 0 : if (bEnableBitmap)
165 0 : SplashOutputDev::drawImageMask(state, ref, str, width, height,
166 : invert, interpolate, inlineImg);
167 : else
168 : {
169 0 : VSIPDFFileStream::resetNoCheckReturnValue(str);
170 0 : if (inlineImg)
171 : {
172 0 : skipBytes(str, width, height, 1, 1);
173 : }
174 0 : str->close();
175 : }
176 0 : }
177 :
178 0 : virtual void setSoftMaskFromImageMask(GfxState *state, Object *ref,
179 : Stream *str, int width, int height,
180 : bool invert, bool inlineImg,
181 : double *baseMatrix) override
182 : {
183 0 : if (bEnableBitmap)
184 0 : SplashOutputDev::setSoftMaskFromImageMask(
185 : state, ref, str, width, height, invert, inlineImg, baseMatrix);
186 : else
187 0 : str->close();
188 0 : }
189 :
190 0 : virtual void unsetSoftMaskFromImageMask(GfxState *state,
191 : double *baseMatrix) override
192 : {
193 0 : if (bEnableBitmap)
194 0 : SplashOutputDev::unsetSoftMaskFromImageMask(state, baseMatrix);
195 0 : }
196 :
197 34 : virtual void drawImage(GfxState *state, Object *ref, Stream *str, int width,
198 : int height, GfxImageColorMap *colorMap,
199 : bool interpolate, const int *maskColors,
200 : bool inlineImg) override
201 : {
202 34 : if (bEnableBitmap)
203 31 : SplashOutputDev::drawImage(state, ref, str, width, height, colorMap,
204 : interpolate, maskColors, inlineImg);
205 : else
206 : {
207 3 : VSIPDFFileStream::resetNoCheckReturnValue(str);
208 3 : if (inlineImg)
209 : {
210 0 : skipBytes(str, width, height, colorMap->getNumPixelComps(),
211 : colorMap->getBits());
212 : }
213 3 : str->close();
214 : }
215 34 : }
216 :
217 0 : virtual void drawMaskedImage(GfxState *state, Object *ref, Stream *str,
218 : int width, int height,
219 : GfxImageColorMap *colorMap, bool interpolate,
220 : Stream *maskStr, int maskWidth, int maskHeight,
221 : bool maskInvert, bool maskInterpolate) override
222 : {
223 0 : if (bEnableBitmap)
224 0 : SplashOutputDev::drawMaskedImage(
225 : state, ref, str, width, height, colorMap, interpolate, maskStr,
226 : maskWidth, maskHeight, maskInvert, maskInterpolate);
227 : else
228 0 : str->close();
229 0 : }
230 :
231 2 : virtual void drawSoftMaskedImage(GfxState *state, Object *ref, Stream *str,
232 : int width, int height,
233 : GfxImageColorMap *colorMap,
234 : bool interpolate, Stream *maskStr,
235 : int maskWidth, int maskHeight,
236 : GfxImageColorMap *maskColorMap,
237 : bool maskInterpolate) override
238 : {
239 2 : if (bEnableBitmap)
240 : {
241 2 : if (maskColorMap->getBits() <=
242 : 0) /* workaround poppler bug (robustness) */
243 : {
244 0 : str->close();
245 0 : return;
246 : }
247 2 : SplashOutputDev::drawSoftMaskedImage(
248 : state, ref, str, width, height, colorMap, interpolate, maskStr,
249 : maskWidth, maskHeight, maskColorMap, maskInterpolate);
250 : }
251 : else
252 0 : str->close();
253 : }
254 : };
255 :
256 47 : void GDALPDFOutputDev::startPage(int pageNum, GfxState *state, XRef *xrefIn)
257 : {
258 47 : SplashOutputDev::startPage(pageNum, state, xrefIn);
259 47 : SplashBitmap *poBitmap = getBitmap();
260 94 : memset(poBitmap->getDataPtr(), 255,
261 47 : static_cast<size_t>(poBitmap->getRowSize()) * poBitmap->getHeight());
262 47 : }
263 :
264 : #endif // ~ HAVE_POPPLER
265 :
266 : /************************************************************************/
267 : /* Dump routines */
268 : /************************************************************************/
269 :
270 : class GDALPDFDumper
271 : {
272 : private:
273 : FILE *f = nullptr;
274 : const int nDepthLimit;
275 : std::set<int> aoSetObjectExplored{};
276 : const bool bDumpParent;
277 :
278 : void DumpSimplified(GDALPDFObject *poObj);
279 :
280 : CPL_DISALLOW_COPY_ASSIGN(GDALPDFDumper)
281 :
282 : public:
283 2 : GDALPDFDumper(const char *pszFilename, const char *pszDumpFile,
284 : int nDepthLimitIn = -1)
285 2 : : nDepthLimit(nDepthLimitIn),
286 2 : bDumpParent(CPLGetConfigOption("PDF_DUMP_PARENT", "FALSE"))
287 : {
288 2 : if (strcmp(pszDumpFile, "stderr") == 0)
289 0 : f = stderr;
290 2 : else if (EQUAL(pszDumpFile, "YES"))
291 0 : f = fopen(CPLSPrintf("dump_%s.txt", CPLGetFilename(pszFilename)),
292 : "wt");
293 : else
294 2 : f = fopen(pszDumpFile, "wt");
295 2 : if (f == nullptr)
296 0 : f = stderr;
297 2 : }
298 :
299 2 : ~GDALPDFDumper()
300 2 : {
301 2 : if (f != stderr)
302 2 : fclose(f);
303 2 : }
304 :
305 : void Dump(GDALPDFObject *poObj, int nDepth = 0);
306 : void Dump(GDALPDFDictionary *poDict, int nDepth = 0);
307 : void Dump(GDALPDFArray *poArray, int nDepth = 0);
308 : };
309 :
310 6 : void GDALPDFDumper::Dump(GDALPDFArray *poArray, int nDepth)
311 : {
312 6 : if (nDepthLimit >= 0 && nDepth > nDepthLimit)
313 0 : return;
314 :
315 6 : int nLength = poArray->GetLength();
316 : int i;
317 12 : CPLString osIndent;
318 28 : for (i = 0; i < nDepth; i++)
319 22 : osIndent += " ";
320 16 : for (i = 0; i < nLength; i++)
321 : {
322 10 : fprintf(f, "%sItem[%d]:", osIndent.c_str(), i);
323 10 : GDALPDFObject *poObj = nullptr;
324 10 : if ((poObj = poArray->Get(i)) != nullptr)
325 : {
326 10 : if (poObj->GetType() == PDFObjectType_String ||
327 10 : poObj->GetType() == PDFObjectType_Null ||
328 10 : poObj->GetType() == PDFObjectType_Bool ||
329 10 : poObj->GetType() == PDFObjectType_Int ||
330 22 : poObj->GetType() == PDFObjectType_Real ||
331 2 : poObj->GetType() == PDFObjectType_Name)
332 : {
333 8 : fprintf(f, " ");
334 8 : DumpSimplified(poObj);
335 8 : fprintf(f, "\n");
336 : }
337 : else
338 : {
339 2 : fprintf(f, "\n");
340 2 : Dump(poObj, nDepth + 1);
341 : }
342 : }
343 : }
344 : }
345 :
346 986 : void GDALPDFDumper::DumpSimplified(GDALPDFObject *poObj)
347 : {
348 986 : switch (poObj->GetType())
349 : {
350 0 : case PDFObjectType_String:
351 0 : fprintf(f, "%s (string)", poObj->GetString().c_str());
352 0 : break;
353 :
354 0 : case PDFObjectType_Null:
355 0 : fprintf(f, "null");
356 0 : break;
357 :
358 0 : case PDFObjectType_Bool:
359 0 : fprintf(f, "%s (bool)", poObj->GetBool() ? "true" : "false");
360 0 : break;
361 :
362 494 : case PDFObjectType_Int:
363 494 : fprintf(f, "%d (int)", poObj->GetInt());
364 494 : break;
365 :
366 0 : case PDFObjectType_Real:
367 0 : fprintf(f, "%f (real)", poObj->GetReal());
368 0 : break;
369 :
370 492 : case PDFObjectType_Name:
371 492 : fprintf(f, "%s (name)", poObj->GetName().c_str());
372 492 : break;
373 :
374 0 : default:
375 0 : fprintf(f, "unknown !");
376 0 : break;
377 : }
378 986 : }
379 :
380 140 : void GDALPDFDumper::Dump(GDALPDFObject *poObj, int nDepth)
381 : {
382 140 : if (nDepthLimit >= 0 && nDepth > nDepthLimit)
383 2 : return;
384 :
385 : int i;
386 140 : CPLString osIndent;
387 1032 : for (i = 0; i < nDepth; i++)
388 892 : osIndent += " ";
389 140 : fprintf(f, "%sType = %s", osIndent.c_str(), poObj->GetTypeName());
390 140 : int nRefNum = poObj->GetRefNum().toInt();
391 140 : if (nRefNum != 0)
392 132 : fprintf(f, ", Num = %d, Gen = %d", nRefNum, poObj->GetRefGen());
393 140 : fprintf(f, "\n");
394 :
395 140 : if (nRefNum != 0)
396 : {
397 132 : if (aoSetObjectExplored.find(nRefNum) != aoSetObjectExplored.end())
398 2 : return;
399 130 : aoSetObjectExplored.insert(nRefNum);
400 : }
401 :
402 138 : switch (poObj->GetType())
403 : {
404 6 : case PDFObjectType_Array:
405 6 : Dump(poObj->GetArray(), nDepth + 1);
406 6 : break;
407 :
408 132 : case PDFObjectType_Dictionary:
409 132 : Dump(poObj->GetDictionary(), nDepth + 1);
410 132 : break;
411 :
412 0 : case PDFObjectType_String:
413 : case PDFObjectType_Null:
414 : case PDFObjectType_Bool:
415 : case PDFObjectType_Int:
416 : case PDFObjectType_Real:
417 : case PDFObjectType_Name:
418 0 : fprintf(f, "%s", osIndent.c_str());
419 0 : DumpSimplified(poObj);
420 0 : fprintf(f, "\n");
421 0 : break;
422 :
423 0 : default:
424 0 : fprintf(f, "%s", osIndent.c_str());
425 0 : fprintf(f, "unknown !\n");
426 0 : break;
427 : }
428 :
429 138 : GDALPDFStream *poStream = poObj->GetStream();
430 138 : if (poStream != nullptr)
431 : {
432 122 : fprintf(f,
433 : "%sHas stream (" CPL_FRMT_GIB
434 : " uncompressed bytes, " CPL_FRMT_GIB " raw bytes)\n",
435 122 : osIndent.c_str(), static_cast<GIntBig>(poStream->GetLength()),
436 122 : static_cast<GIntBig>(poStream->GetRawLength()));
437 : }
438 : }
439 :
440 132 : void GDALPDFDumper::Dump(GDALPDFDictionary *poDict, int nDepth)
441 : {
442 132 : if (nDepthLimit >= 0 && nDepth > nDepthLimit)
443 0 : return;
444 :
445 264 : CPLString osIndent;
446 1128 : for (int i = 0; i < nDepth; i++)
447 996 : osIndent += " ";
448 132 : int i = 0;
449 132 : const auto &oMap = poDict->GetValues();
450 1246 : for (const auto &[osKey, poObj] : oMap)
451 : {
452 1114 : fprintf(f, "%sItem[%d] : %s", osIndent.c_str(), i, osKey.c_str());
453 1114 : ++i;
454 1114 : if (osKey == "Parent" && !bDumpParent)
455 : {
456 0 : if (poObj->GetRefNum().toBool())
457 0 : fprintf(f, ", Num = %d, Gen = %d", poObj->GetRefNum().toInt(),
458 0 : poObj->GetRefGen());
459 0 : fprintf(f, "\n");
460 0 : continue;
461 : }
462 1114 : if (poObj != nullptr)
463 : {
464 1114 : if (poObj->GetType() == PDFObjectType_String ||
465 1114 : poObj->GetType() == PDFObjectType_Null ||
466 1114 : poObj->GetType() == PDFObjectType_Bool ||
467 1114 : poObj->GetType() == PDFObjectType_Int ||
468 2856 : poObj->GetType() == PDFObjectType_Real ||
469 628 : poObj->GetType() == PDFObjectType_Name)
470 : {
471 978 : fprintf(f, " = ");
472 978 : DumpSimplified(poObj);
473 978 : fprintf(f, "\n");
474 : }
475 : else
476 : {
477 136 : fprintf(f, "\n");
478 136 : Dump(poObj, nDepth + 1);
479 : }
480 : }
481 : }
482 : }
483 :
484 : /************************************************************************/
485 : /* PDFRasterBand() */
486 : /************************************************************************/
487 :
488 1367 : PDFRasterBand::PDFRasterBand(PDFDataset *poDSIn, int nBandIn,
489 1367 : int nResolutionLevelIn)
490 1367 : : nResolutionLevel(nResolutionLevelIn)
491 : {
492 1367 : poDS = poDSIn;
493 1367 : nBand = nBandIn;
494 :
495 1367 : eDataType = GDT_Byte;
496 :
497 1367 : if (nResolutionLevel > 0)
498 : {
499 8 : nBlockXSize = 256;
500 8 : nBlockYSize = 256;
501 8 : poDSIn->SetMetadataItem("INTERLEAVE", "PIXEL", "IMAGE_STRUCTURE");
502 : }
503 1359 : else if (poDSIn->m_nBlockXSize)
504 : {
505 72 : nBlockXSize = poDSIn->m_nBlockXSize;
506 72 : nBlockYSize = poDSIn->m_nBlockYSize;
507 72 : poDSIn->SetMetadataItem("INTERLEAVE", "PIXEL", "IMAGE_STRUCTURE");
508 : }
509 1287 : else if (poDSIn->GetRasterXSize() <
510 1287 : 64 * 1024 * 1024 / poDSIn->GetRasterYSize())
511 : {
512 1283 : nBlockXSize = poDSIn->GetRasterXSize();
513 1283 : nBlockYSize = 1;
514 : }
515 : else
516 : {
517 4 : nBlockXSize = std::min(1024, poDSIn->GetRasterXSize());
518 4 : nBlockYSize = std::min(1024, poDSIn->GetRasterYSize());
519 4 : poDSIn->SetMetadataItem("INTERLEAVE", "PIXEL", "IMAGE_STRUCTURE");
520 : }
521 1367 : }
522 :
523 : /************************************************************************/
524 : /* InitOverviews() */
525 : /************************************************************************/
526 :
527 10 : void PDFDataset::InitOverviews()
528 : {
529 : #ifdef HAVE_PDFIUM
530 : // Only if used pdfium, make "arbitrary overviews"
531 : // Blocks are 256x256
532 14 : if (m_bUseLib.test(PDFLIB_PDFIUM) && m_apoOvrDS.empty() &&
533 4 : m_apoOvrDSBackup.empty())
534 : {
535 3 : int nXSize = nRasterXSize;
536 3 : int nYSize = nRasterYSize;
537 3 : constexpr int minSize = 256;
538 3 : int nDiscard = 1;
539 5 : while (nXSize > minSize || nYSize > minSize)
540 : {
541 2 : nXSize = (nXSize + 1) / 2;
542 2 : nYSize = (nYSize + 1) / 2;
543 :
544 2 : auto poOvrDS = std::make_unique<PDFDataset>(this, nXSize, nYSize);
545 :
546 10 : for (int i = 0; i < nBands; i++)
547 16 : poOvrDS->SetBand(
548 8 : i + 1, new PDFRasterBand(poOvrDS.get(), i + 1, nDiscard));
549 :
550 2 : m_apoOvrDS.emplace_back(std::move(poOvrDS));
551 2 : ++nDiscard;
552 : }
553 : }
554 : #endif
555 : #if defined(HAVE_POPPLER) || defined(HAVE_PODOFO)
556 16 : if (!m_bUseLib.test(PDFLIB_PDFIUM) && m_apoOvrDS.empty() &&
557 16 : m_apoOvrDSBackup.empty() && m_osUserPwd != "ASK_INTERACTIVE")
558 : {
559 1 : int nXSize = nRasterXSize;
560 1 : int nYSize = nRasterYSize;
561 1 : constexpr int minSize = 256;
562 1 : double dfDPI = m_dfDPI;
563 3 : while (nXSize > minSize || nYSize > minSize)
564 : {
565 2 : nXSize = (nXSize + 1) / 2;
566 2 : nYSize = (nYSize + 1) / 2;
567 2 : dfDPI /= 2;
568 :
569 2 : GDALOpenInfo oOpenInfo(GetDescription(), GA_ReadOnly);
570 2 : CPLStringList aosOpenOptions(CSLDuplicate(papszOpenOptions));
571 2 : aosOpenOptions.SetNameValue("DPI", CPLSPrintf("%g", dfDPI));
572 2 : aosOpenOptions.SetNameValue("BANDS", CPLSPrintf("%d", nBands));
573 2 : aosOpenOptions.SetNameValue("@OPEN_FOR_OVERVIEW", "YES");
574 2 : if (!m_osUserPwd.empty())
575 0 : aosOpenOptions.SetNameValue("USER_PWD", m_osUserPwd.c_str());
576 2 : oOpenInfo.papszOpenOptions = aosOpenOptions.List();
577 2 : auto poOvrDS = std::unique_ptr<PDFDataset>(Open(&oOpenInfo));
578 2 : if (!poOvrDS || poOvrDS->nBands != nBands)
579 0 : break;
580 2 : poOvrDS->m_bIsOvrDS = true;
581 2 : m_apoOvrDS.emplace_back(std::move(poOvrDS));
582 : }
583 : }
584 : #endif
585 10 : }
586 :
587 : /************************************************************************/
588 : /* GetColorInterpretation() */
589 : /************************************************************************/
590 :
591 60 : GDALColorInterp PDFRasterBand::GetColorInterpretation()
592 : {
593 60 : PDFDataset *poGDS = cpl::down_cast<PDFDataset *>(poDS);
594 60 : if (poGDS->nBands == 1)
595 0 : return GCI_GrayIndex;
596 : else
597 60 : return static_cast<GDALColorInterp>(GCI_RedBand + (nBand - 1));
598 : }
599 :
600 : /************************************************************************/
601 : /* GetOverviewCount() */
602 : /************************************************************************/
603 :
604 19 : int PDFRasterBand::GetOverviewCount()
605 : {
606 19 : PDFDataset *poGDS = cpl::down_cast<PDFDataset *>(poDS);
607 19 : if (poGDS->m_bIsOvrDS)
608 0 : return 0;
609 19 : if (GDALPamRasterBand::GetOverviewCount() > 0)
610 9 : return GDALPamRasterBand::GetOverviewCount();
611 : else
612 : {
613 10 : poGDS->InitOverviews();
614 10 : return static_cast<int>(poGDS->m_apoOvrDS.size());
615 : }
616 : }
617 :
618 : /************************************************************************/
619 : /* GetOverview() */
620 : /************************************************************************/
621 :
622 8 : GDALRasterBand *PDFRasterBand::GetOverview(int iOverviewIndex)
623 : {
624 8 : if (GDALPamRasterBand::GetOverviewCount() > 0)
625 2 : return GDALPamRasterBand::GetOverview(iOverviewIndex);
626 :
627 6 : else if (iOverviewIndex < 0 || iOverviewIndex >= GetOverviewCount())
628 4 : return nullptr;
629 : else
630 : {
631 2 : PDFDataset *poGDS = cpl::down_cast<PDFDataset *>(poDS);
632 2 : return poGDS->m_apoOvrDS[iOverviewIndex]->GetRasterBand(nBand);
633 : }
634 : }
635 :
636 : /************************************************************************/
637 : /* ~PDFRasterBand() */
638 : /************************************************************************/
639 :
640 2734 : PDFRasterBand::~PDFRasterBand()
641 : {
642 2734 : }
643 :
644 : /************************************************************************/
645 : /* IReadBlockFromTile() */
646 : /************************************************************************/
647 :
648 320 : CPLErr PDFRasterBand::IReadBlockFromTile(int nBlockXOff, int nBlockYOff,
649 : void *pImage)
650 :
651 : {
652 320 : PDFDataset *poGDS = cpl::down_cast<PDFDataset *>(poDS);
653 :
654 320 : int nReqXSize = nBlockXSize;
655 320 : int nReqYSize = nBlockYSize;
656 320 : if ((nBlockXOff + 1) * nBlockXSize > nRasterXSize)
657 40 : nReqXSize = nRasterXSize - nBlockXOff * nBlockXSize;
658 320 : if ((nBlockYOff + 1) * nBlockYSize > nRasterYSize)
659 48 : nReqYSize = nRasterYSize - nBlockYOff * nBlockYSize;
660 :
661 320 : int nXBlocks = DIV_ROUND_UP(nRasterXSize, nBlockXSize);
662 320 : int iTile = poGDS->m_aiTiles[nBlockYOff * nXBlocks + nBlockXOff];
663 320 : if (iTile < 0)
664 : {
665 0 : memset(pImage, 0, static_cast<size_t>(nBlockXSize) * nBlockYSize);
666 0 : return CE_None;
667 : }
668 :
669 320 : GDALPDFTileDesc &sTile = poGDS->m_asTiles[iTile];
670 320 : GDALPDFObject *poImage = sTile.poImage;
671 :
672 320 : if (nBand == 4)
673 : {
674 60 : GDALPDFDictionary *poImageDict = poImage->GetDictionary();
675 60 : GDALPDFObject *poSMask = poImageDict->Get("SMask");
676 120 : if (poSMask != nullptr &&
677 60 : poSMask->GetType() == PDFObjectType_Dictionary)
678 : {
679 60 : GDALPDFDictionary *poSMaskDict = poSMask->GetDictionary();
680 60 : GDALPDFObject *poWidth = poSMaskDict->Get("Width");
681 60 : GDALPDFObject *poHeight = poSMaskDict->Get("Height");
682 60 : GDALPDFObject *poColorSpace = poSMaskDict->Get("ColorSpace");
683 : GDALPDFObject *poBitsPerComponent =
684 60 : poSMaskDict->Get("BitsPerComponent");
685 60 : double dfBits = 0;
686 60 : if (poBitsPerComponent)
687 60 : dfBits = Get(poBitsPerComponent);
688 60 : if (poWidth && Get(poWidth) == nReqXSize && poHeight &&
689 60 : Get(poHeight) == nReqYSize && poColorSpace &&
690 120 : poColorSpace->GetType() == PDFObjectType_Name &&
691 224 : poColorSpace->GetName() == "DeviceGray" &&
692 44 : (dfBits == 1 || dfBits == 8))
693 : {
694 60 : GDALPDFStream *poStream = poSMask->GetStream();
695 60 : GByte *pabyStream = nullptr;
696 :
697 60 : if (poStream == nullptr)
698 0 : return CE_Failure;
699 :
700 60 : pabyStream = reinterpret_cast<GByte *>(poStream->GetBytes());
701 60 : if (pabyStream == nullptr)
702 0 : return CE_Failure;
703 :
704 60 : const int nReqXSize1 = (nReqXSize + 7) / 8;
705 104 : if ((dfBits == 8 &&
706 44 : static_cast<size_t>(poStream->GetLength()) !=
707 120 : static_cast<size_t>(nReqXSize) * nReqYSize) ||
708 16 : (dfBits == 1 &&
709 16 : static_cast<size_t>(poStream->GetLength()) !=
710 16 : static_cast<size_t>(nReqXSize1) * nReqYSize))
711 : {
712 0 : VSIFree(pabyStream);
713 0 : return CE_Failure;
714 : }
715 :
716 60 : GByte *pabyData = static_cast<GByte *>(pImage);
717 60 : if (nReqXSize != nBlockXSize || nReqYSize != nBlockYSize)
718 : {
719 20 : memset(pabyData, 0,
720 20 : static_cast<size_t>(nBlockXSize) * nBlockYSize);
721 : }
722 :
723 60 : if (dfBits == 8)
724 : {
725 1372 : for (int j = 0; j < nReqYSize; j++)
726 : {
727 43824 : for (int i = 0; i < nReqXSize; i++)
728 : {
729 42496 : pabyData[j * nBlockXSize + i] =
730 42496 : pabyStream[j * nReqXSize + i];
731 : }
732 : }
733 : }
734 : else
735 : {
736 488 : for (int j = 0; j < nReqYSize; j++)
737 : {
738 6576 : for (int i = 0; i < nReqXSize; i++)
739 : {
740 6104 : if (pabyStream[j * nReqXSize1 + i / 8] &
741 6104 : (1 << (7 - (i % 8))))
742 1792 : pabyData[j * nBlockXSize + i] = 255;
743 : else
744 4312 : pabyData[j * nBlockXSize + i] = 0;
745 : }
746 : }
747 : }
748 :
749 60 : VSIFree(pabyStream);
750 60 : return CE_None;
751 : }
752 : }
753 :
754 0 : memset(pImage, 255, static_cast<size_t>(nBlockXSize) * nBlockYSize);
755 0 : return CE_None;
756 : }
757 :
758 260 : if (poGDS->m_nLastBlockXOff == nBlockXOff &&
759 0 : poGDS->m_nLastBlockYOff == nBlockYOff &&
760 0 : poGDS->m_pabyCachedData != nullptr)
761 : {
762 : #ifdef DEBUG
763 0 : CPLDebug("PDF", "Using cached block (%d, %d)", nBlockXOff, nBlockYOff);
764 : #endif
765 : // do nothing
766 : }
767 : else
768 : {
769 260 : if (!poGDS->m_bTried)
770 : {
771 10 : poGDS->m_bTried = true;
772 10 : poGDS->m_pabyCachedData =
773 10 : static_cast<GByte *>(VSIMalloc3(3, nBlockXSize, nBlockYSize));
774 : }
775 260 : if (poGDS->m_pabyCachedData == nullptr)
776 0 : return CE_Failure;
777 :
778 260 : GDALPDFStream *poStream = poImage->GetStream();
779 260 : GByte *pabyStream = nullptr;
780 :
781 260 : if (poStream == nullptr)
782 0 : return CE_Failure;
783 :
784 260 : pabyStream = reinterpret_cast<GByte *>(poStream->GetBytes());
785 260 : if (pabyStream == nullptr)
786 0 : return CE_Failure;
787 :
788 260 : if (static_cast<size_t>(poStream->GetLength()) !=
789 260 : static_cast<size_t>(sTile.nBands) * nReqXSize * nReqYSize)
790 : {
791 0 : VSIFree(pabyStream);
792 0 : return CE_Failure;
793 : }
794 :
795 260 : memcpy(poGDS->m_pabyCachedData, pabyStream,
796 260 : static_cast<size_t>(poStream->GetLength()));
797 260 : VSIFree(pabyStream);
798 260 : poGDS->m_nLastBlockXOff = nBlockXOff;
799 260 : poGDS->m_nLastBlockYOff = nBlockYOff;
800 : }
801 :
802 260 : GByte *pabyData = static_cast<GByte *>(pImage);
803 260 : if (nBand != 4 && (nReqXSize != nBlockXSize || nReqYSize != nBlockYSize))
804 : {
805 60 : memset(pabyData, 0, static_cast<size_t>(nBlockXSize) * nBlockYSize);
806 : }
807 :
808 260 : if (poGDS->nBands >= 3 && sTile.nBands == 3)
809 : {
810 5580 : for (int j = 0; j < nReqYSize; j++)
811 : {
812 151200 : for (int i = 0; i < nReqXSize; i++)
813 : {
814 145800 : pabyData[j * nBlockXSize + i] =
815 : poGDS
816 145800 : ->m_pabyCachedData[3 * (j * nReqXSize + i) + nBand - 1];
817 : }
818 180 : }
819 : }
820 80 : else if (sTile.nBands == 1)
821 : {
822 12368 : for (int j = 0; j < nReqYSize; j++)
823 : {
824 2109440 : for (int i = 0; i < nReqXSize; i++)
825 : {
826 2097150 : pabyData[j * nBlockXSize + i] =
827 2097150 : poGDS->m_pabyCachedData[j * nReqXSize + i];
828 : }
829 : }
830 : }
831 :
832 260 : return CE_None;
833 : }
834 :
835 : /************************************************************************/
836 : /* GetSuggestedBlockAccessPattern() */
837 : /************************************************************************/
838 :
839 : GDALSuggestedBlockAccessPattern
840 2 : PDFRasterBand::GetSuggestedBlockAccessPattern() const
841 : {
842 2 : PDFDataset *poGDS = cpl::down_cast<PDFDataset *>(poDS);
843 2 : if (!poGDS->m_aiTiles.empty())
844 0 : return GSBAP_RANDOM;
845 2 : return GSBAP_LARGEST_CHUNK_POSSIBLE;
846 : }
847 :
848 : /************************************************************************/
849 : /* IReadBlock() */
850 : /************************************************************************/
851 :
852 50185 : CPLErr PDFRasterBand::IReadBlock(int nBlockXOff, int nBlockYOff, void *pImage)
853 :
854 : {
855 50185 : PDFDataset *poGDS = cpl::down_cast<PDFDataset *>(poDS);
856 :
857 50185 : if (!poGDS->m_aiTiles.empty())
858 : {
859 320 : if (IReadBlockFromTile(nBlockXOff, nBlockYOff, pImage) == CE_None)
860 : {
861 320 : return CE_None;
862 : }
863 : else
864 : {
865 0 : poGDS->m_aiTiles.resize(0);
866 0 : poGDS->m_bTried = false;
867 0 : CPLFree(poGDS->m_pabyCachedData);
868 0 : poGDS->m_pabyCachedData = nullptr;
869 0 : poGDS->m_nLastBlockXOff = -1;
870 0 : poGDS->m_nLastBlockYOff = -1;
871 : }
872 : }
873 :
874 49865 : int nReqXSize = nBlockXSize;
875 49865 : int nReqYSize = nBlockYSize;
876 49865 : if ((nBlockXOff + 1) * nBlockXSize > nRasterXSize)
877 0 : nReqXSize = nRasterXSize - nBlockXOff * nBlockXSize;
878 49865 : if (nBlockYSize == 1)
879 49860 : nReqYSize = nRasterYSize;
880 5 : else if ((nBlockYOff + 1) * nBlockYSize > nRasterYSize)
881 0 : nReqYSize = nRasterYSize - nBlockYOff * nBlockYSize;
882 :
883 49865 : if (!poGDS->m_bTried)
884 : {
885 102 : poGDS->m_bTried = true;
886 102 : if (nBlockYSize == 1)
887 300 : poGDS->m_pabyCachedData = static_cast<GByte *>(VSIMalloc3(
888 100 : std::max(3, poGDS->nBands), nRasterXSize, nRasterYSize));
889 : else
890 6 : poGDS->m_pabyCachedData = static_cast<GByte *>(VSIMalloc3(
891 2 : std::max(3, poGDS->nBands), nBlockXSize, nBlockYSize));
892 : }
893 49865 : if (poGDS->m_pabyCachedData == nullptr)
894 0 : return CE_Failure;
895 :
896 49865 : if (poGDS->m_nLastBlockXOff == nBlockXOff &&
897 49760 : (nBlockYSize == 1 || poGDS->m_nLastBlockYOff == nBlockYOff) &&
898 49760 : poGDS->m_pabyCachedData != nullptr)
899 : {
900 : /*CPLDebug("PDF", "Using cached block (%d, %d)",
901 : nBlockXOff, nBlockYOff);*/
902 : // do nothing
903 : }
904 : else
905 : {
906 : #ifdef HAVE_PODOFO
907 : if (poGDS->m_bUseLib.test(PDFLIB_PODOFO) && nBand == 4)
908 : {
909 : memset(pImage, 255, nBlockXSize * nBlockYSize);
910 : return CE_None;
911 : }
912 : #endif
913 :
914 105 : const int nReqXOff = nBlockXOff * nBlockXSize;
915 105 : const int nReqYOff = (nBlockYSize == 1) ? 0 : nBlockYOff * nBlockYSize;
916 105 : const GSpacing nPixelSpace = 1;
917 105 : const GSpacing nLineSpace = nBlockXSize;
918 105 : const GSpacing nBandSpace =
919 105 : static_cast<GSpacing>(nBlockXSize) *
920 105 : ((nBlockYSize == 1) ? nRasterYSize : nBlockYSize);
921 :
922 105 : CPLErr eErr = poGDS->ReadPixels(nReqXOff, nReqYOff, nReqXSize,
923 : nReqYSize, nPixelSpace, nLineSpace,
924 : nBandSpace, poGDS->m_pabyCachedData);
925 :
926 105 : if (eErr == CE_None)
927 : {
928 105 : poGDS->m_nLastBlockXOff = nBlockXOff;
929 105 : poGDS->m_nLastBlockYOff = nBlockYOff;
930 : }
931 : else
932 : {
933 0 : CPLFree(poGDS->m_pabyCachedData);
934 0 : poGDS->m_pabyCachedData = nullptr;
935 : }
936 : }
937 49865 : if (poGDS->m_pabyCachedData == nullptr)
938 0 : return CE_Failure;
939 :
940 49865 : if (nBlockYSize == 1)
941 49860 : memcpy(pImage,
942 49860 : poGDS->m_pabyCachedData +
943 49860 : (nBand - 1) * nBlockXSize * nRasterYSize +
944 49860 : nBlockYOff * nBlockXSize,
945 49860 : nBlockXSize);
946 : else
947 : {
948 5 : memcpy(pImage,
949 5 : poGDS->m_pabyCachedData +
950 5 : static_cast<size_t>(nBand - 1) * nBlockXSize * nBlockYSize,
951 5 : static_cast<size_t>(nBlockXSize) * nBlockYSize);
952 :
953 5 : if (poGDS->m_bCacheBlocksForOtherBands && nBand == 1)
954 : {
955 19 : for (int iBand = 2; iBand <= poGDS->nBands; ++iBand)
956 : {
957 28 : auto poOtherBand = cpl::down_cast<PDFRasterBand *>(
958 14 : poGDS->papoBands[iBand - 1]);
959 : GDALRasterBlock *poBlock =
960 14 : poOtherBand->TryGetLockedBlockRef(nBlockXOff, nBlockYOff);
961 14 : if (poBlock)
962 : {
963 0 : poBlock->DropLock();
964 : }
965 : else
966 : {
967 28 : poBlock = poOtherBand->GetLockedBlockRef(nBlockXOff,
968 14 : nBlockYOff, TRUE);
969 14 : if (poBlock)
970 : {
971 28 : memcpy(poBlock->GetDataRef(),
972 14 : poGDS->m_pabyCachedData +
973 14 : static_cast<size_t>(iBand - 1) *
974 14 : nBlockXSize * nBlockYSize,
975 14 : static_cast<size_t>(nBlockXSize) * nBlockYSize);
976 14 : poBlock->DropLock();
977 : }
978 : }
979 : }
980 : }
981 : }
982 :
983 49865 : return CE_None;
984 : }
985 :
986 : /************************************************************************/
987 : /* PDFEnterPasswordFromConsoleIfNeeded() */
988 : /************************************************************************/
989 :
990 6 : static const char *PDFEnterPasswordFromConsoleIfNeeded(const char *pszUserPwd)
991 : {
992 6 : if (EQUAL(pszUserPwd, "ASK_INTERACTIVE"))
993 : {
994 : static char szPassword[81];
995 4 : printf("Enter password (will be echo'ed in the console): "); /*ok*/
996 4 : if (nullptr == fgets(szPassword, sizeof(szPassword), stdin))
997 : {
998 0 : fprintf(stderr, "WARNING: Error getting password.\n"); /*ok*/
999 : }
1000 4 : szPassword[sizeof(szPassword) - 1] = 0;
1001 4 : char *sz10 = strchr(szPassword, '\n');
1002 4 : if (sz10)
1003 0 : *sz10 = 0;
1004 4 : return szPassword;
1005 : }
1006 2 : return pszUserPwd;
1007 : }
1008 :
1009 : #ifdef HAVE_PDFIUM
1010 :
1011 : /************************************************************************/
1012 : /* Pdfium Load/Unload */
1013 : /* Copyright (C) 2015 Klokan Technologies GmbH (http://www.klokantech.com/) */
1014 : /* Author: Martin Mikita <martin.mikita@klokantech.com> */
1015 : /************************************************************************/
1016 :
1017 : // Flag for calling PDFium Init and Destroy methods
1018 : bool PDFDataset::g_bPdfiumInit = false;
1019 :
1020 : // Pdfium global read mutex - Pdfium is not multi-thread
1021 : static CPLMutex *g_oPdfiumReadMutex = nullptr;
1022 : static CPLMutex *g_oPdfiumLoadDocMutex = nullptr;
1023 :
1024 : // Comparison of char* for std::map
1025 : struct cmp_str
1026 : {
1027 445 : bool operator()(char const *a, char const *b) const
1028 : {
1029 445 : return strcmp(a, b) < 0;
1030 : }
1031 : };
1032 :
1033 5576 : static int GDALPdfiumGetBlock(void *param, unsigned long position,
1034 : unsigned char *pBuf, unsigned long size)
1035 : {
1036 5576 : VSILFILE *fp = static_cast<VSILFILE *>(param);
1037 5576 : VSIFSeekL(fp, position, SEEK_SET);
1038 5576 : return VSIFReadL(pBuf, size, 1, fp) == 1;
1039 : }
1040 :
1041 : // List of all PDF datasets
1042 : typedef std::map<const char *, TPdfiumDocumentStruct *, cmp_str>
1043 : TMapPdfiumDatasets;
1044 : static TMapPdfiumDatasets g_mPdfiumDatasets;
1045 :
1046 : /**
1047 : * Loading PDFIUM page
1048 : * - multithreading requires "mutex"
1049 : * - one page can require too much RAM
1050 : * - we will have one document per filename and one object per page
1051 : */
1052 :
1053 227 : static int LoadPdfiumDocumentPage(const char *pszFilename,
1054 : const char *pszUserPwd, int pageNum,
1055 : TPdfiumDocumentStruct **doc,
1056 : TPdfiumPageStruct **page, int *pnPageCount)
1057 : {
1058 : // Prepare nullptr for error returning
1059 227 : if (doc)
1060 227 : *doc = nullptr;
1061 227 : if (page)
1062 227 : *page = nullptr;
1063 227 : if (pnPageCount)
1064 227 : *pnPageCount = 0;
1065 :
1066 : // Loading document and page must be only in one thread!
1067 227 : CPLCreateOrAcquireMutex(&g_oPdfiumLoadDocMutex, PDFIUM_MUTEX_TIMEOUT);
1068 :
1069 : // Library can be destroyed if every PDF dataset was closed!
1070 227 : if (!PDFDataset::g_bPdfiumInit)
1071 : {
1072 203 : FPDF_InitLibrary();
1073 203 : PDFDataset::g_bPdfiumInit = TRUE;
1074 : }
1075 :
1076 227 : TMapPdfiumDatasets::iterator it;
1077 227 : it = g_mPdfiumDatasets.find(pszFilename);
1078 227 : TPdfiumDocumentStruct *poDoc = nullptr;
1079 : // Load new document if missing
1080 227 : if (it == g_mPdfiumDatasets.end())
1081 : {
1082 : // Try without password (if PDF not requires password it can fail)
1083 :
1084 217 : VSILFILE *fp = VSIFOpenL(pszFilename, "rb");
1085 217 : if (fp == nullptr)
1086 : {
1087 1 : CPLReleaseMutex(g_oPdfiumLoadDocMutex);
1088 1 : return FALSE;
1089 : }
1090 216 : VSIFSeekL(fp, 0, SEEK_END);
1091 216 : const auto nFileLen64 = VSIFTellL(fp);
1092 : if constexpr (LONG_MAX < std::numeric_limits<vsi_l_offset>::max())
1093 : {
1094 216 : if (nFileLen64 > LONG_MAX)
1095 : {
1096 0 : VSIFCloseL(fp);
1097 0 : CPLReleaseMutex(g_oPdfiumLoadDocMutex);
1098 0 : return FALSE;
1099 : }
1100 : }
1101 :
1102 216 : FPDF_FILEACCESS *psFileAccess = new FPDF_FILEACCESS;
1103 216 : psFileAccess->m_Param = fp;
1104 216 : psFileAccess->m_FileLen = static_cast<unsigned long>(nFileLen64);
1105 216 : psFileAccess->m_GetBlock = GDALPdfiumGetBlock;
1106 216 : CPDF_Document *docPdfium = CPDFDocumentFromFPDFDocument(
1107 : FPDF_LoadCustomDocument(psFileAccess, nullptr));
1108 216 : if (docPdfium == nullptr)
1109 : {
1110 15 : unsigned long err = FPDF_GetLastError();
1111 15 : if (err == FPDF_ERR_PASSWORD)
1112 : {
1113 7 : if (pszUserPwd)
1114 : {
1115 : pszUserPwd =
1116 6 : PDFEnterPasswordFromConsoleIfNeeded(pszUserPwd);
1117 6 : docPdfium = CPDFDocumentFromFPDFDocument(
1118 : FPDF_LoadCustomDocument(psFileAccess, pszUserPwd));
1119 6 : if (docPdfium == nullptr)
1120 3 : err = FPDF_GetLastError();
1121 : else
1122 3 : err = FPDF_ERR_SUCCESS;
1123 : }
1124 : else
1125 : {
1126 1 : CPLError(CE_Failure, CPLE_AppDefined,
1127 : "A password is needed. You can specify it through "
1128 : "the PDF_USER_PWD "
1129 : "configuration option / USER_PWD open option "
1130 : "(that can be set to ASK_INTERACTIVE)");
1131 :
1132 1 : VSIFCloseL(fp);
1133 1 : delete psFileAccess;
1134 1 : CPLReleaseMutex(g_oPdfiumLoadDocMutex);
1135 1 : return FALSE;
1136 : }
1137 : } // First Error Password [null password given]
1138 14 : if (err != FPDF_ERR_SUCCESS)
1139 : {
1140 11 : if (err == FPDF_ERR_PASSWORD)
1141 3 : CPLError(CE_Failure, CPLE_AppDefined,
1142 : "PDFium Invalid password.");
1143 8 : else if (err == FPDF_ERR_SECURITY)
1144 0 : CPLError(CE_Failure, CPLE_AppDefined,
1145 : "PDFium Unsupported security scheme.");
1146 8 : else if (err == FPDF_ERR_FORMAT)
1147 8 : CPLError(CE_Failure, CPLE_AppDefined,
1148 : "PDFium File not in PDF format or corrupted.");
1149 0 : else if (err == FPDF_ERR_FILE)
1150 0 : CPLError(CE_Failure, CPLE_AppDefined,
1151 : "PDFium File not found or could not be opened.");
1152 : else
1153 0 : CPLError(CE_Failure, CPLE_AppDefined,
1154 : "PDFium Unknown PDF error or invalid PDF.");
1155 :
1156 11 : VSIFCloseL(fp);
1157 11 : delete psFileAccess;
1158 11 : CPLReleaseMutex(g_oPdfiumLoadDocMutex);
1159 11 : return FALSE;
1160 : }
1161 : } // ~ wrong PDF or password required
1162 :
1163 : // Create new poDoc
1164 204 : poDoc = new TPdfiumDocumentStruct;
1165 204 : if (!poDoc)
1166 : {
1167 0 : CPLError(CE_Failure, CPLE_AppDefined,
1168 : "Not enough memory for Pdfium Document object");
1169 :
1170 0 : VSIFCloseL(fp);
1171 0 : delete psFileAccess;
1172 0 : CPLReleaseMutex(g_oPdfiumLoadDocMutex);
1173 0 : return FALSE;
1174 : }
1175 204 : poDoc->filename = CPLStrdup(pszFilename);
1176 204 : poDoc->doc = docPdfium;
1177 204 : poDoc->psFileAccess = psFileAccess;
1178 :
1179 204 : g_mPdfiumDatasets[poDoc->filename] = poDoc;
1180 : }
1181 : // Document already loaded
1182 : else
1183 : {
1184 10 : poDoc = it->second;
1185 : }
1186 :
1187 : // Check page num in document
1188 214 : int nPages = poDoc->doc->GetPageCount();
1189 214 : if (pageNum < 1 || pageNum > nPages)
1190 : {
1191 1 : CPLError(CE_Failure, CPLE_AppDefined,
1192 : "PDFium Invalid page number (%d/%d) for document %s", pageNum,
1193 : nPages, pszFilename);
1194 :
1195 1 : CPLReleaseMutex(g_oPdfiumLoadDocMutex);
1196 1 : return FALSE;
1197 : }
1198 :
1199 : /* Sanity check to validate page count */
1200 213 : if (pageNum != nPages)
1201 : {
1202 11 : if (poDoc->doc->GetPageDictionary(nPages - 1) == nullptr)
1203 : {
1204 0 : CPLError(CE_Failure, CPLE_AppDefined,
1205 : "Invalid PDF : invalid page count");
1206 0 : CPLReleaseMutex(g_oPdfiumLoadDocMutex);
1207 0 : return FALSE;
1208 : }
1209 : }
1210 :
1211 213 : TMapPdfiumPages::iterator itPage;
1212 213 : itPage = poDoc->pages.find(pageNum);
1213 213 : TPdfiumPageStruct *poPage = nullptr;
1214 : // Page not loaded
1215 213 : if (itPage == poDoc->pages.end())
1216 : {
1217 208 : auto pDict = poDoc->doc->GetPageDictionary(pageNum - 1);
1218 208 : if (pDict == nullptr)
1219 : {
1220 0 : CPLError(CE_Failure, CPLE_AppDefined,
1221 : "Invalid PDFium : invalid page");
1222 :
1223 0 : CPLReleaseMutex(g_oPdfiumLoadDocMutex);
1224 0 : return FALSE;
1225 : }
1226 : auto pPage = pdfium::MakeRetain<CPDF_Page>(
1227 208 : poDoc->doc,
1228 : // coverity is confused by WrapRetain(), believing that multiple
1229 : // smart pointers manage the same raw pointer. Which is actually
1230 : // true, but a RetainPtr holds a reference counted object. It is
1231 : // thus safe to have several RetainPtr holding it.
1232 : // coverity[multiple_init_smart_ptr]
1233 208 : pdfium::WrapRetain(const_cast<CPDF_Dictionary *>(pDict.Get())));
1234 :
1235 208 : poPage = new TPdfiumPageStruct;
1236 208 : if (!poPage)
1237 : {
1238 0 : CPLError(CE_Failure, CPLE_AppDefined,
1239 : "Not enough memory for Pdfium Page object");
1240 :
1241 0 : CPLReleaseMutex(g_oPdfiumLoadDocMutex);
1242 0 : return FALSE;
1243 : }
1244 208 : poPage->pageNum = pageNum;
1245 208 : poPage->page = pPage.Leak();
1246 208 : poPage->readMutex = nullptr;
1247 208 : poPage->sharedNum = 0;
1248 :
1249 208 : poDoc->pages[pageNum] = poPage;
1250 : }
1251 : // Page already loaded
1252 : else
1253 : {
1254 5 : poPage = itPage->second;
1255 : }
1256 :
1257 : // Increase number of used
1258 213 : ++poPage->sharedNum;
1259 :
1260 213 : if (doc)
1261 213 : *doc = poDoc;
1262 213 : if (page)
1263 213 : *page = poPage;
1264 213 : if (pnPageCount)
1265 213 : *pnPageCount = nPages;
1266 :
1267 213 : CPLReleaseMutex(g_oPdfiumLoadDocMutex);
1268 :
1269 213 : return TRUE;
1270 : }
1271 :
1272 : // ~ static int LoadPdfiumDocumentPage()
1273 :
1274 213 : static int UnloadPdfiumDocumentPage(TPdfiumDocumentStruct **doc,
1275 : TPdfiumPageStruct **page)
1276 : {
1277 213 : if (!doc || !page)
1278 0 : return FALSE;
1279 :
1280 213 : TPdfiumPageStruct *pPage = *page;
1281 213 : TPdfiumDocumentStruct *pDoc = *doc;
1282 :
1283 : // Get mutex for loading pdfium
1284 213 : CPLCreateOrAcquireMutex(&g_oPdfiumLoadDocMutex, PDFIUM_MUTEX_TIMEOUT);
1285 :
1286 : // Decrease page use
1287 213 : --pPage->sharedNum;
1288 :
1289 : #ifdef DEBUG
1290 213 : CPLDebug("PDF", "PDFDataset::UnloadPdfiumDocumentPage: page shared num %d",
1291 : pPage->sharedNum);
1292 : #endif
1293 : // Page is used (also document)
1294 213 : if (pPage->sharedNum != 0)
1295 : {
1296 5 : CPLReleaseMutex(g_oPdfiumLoadDocMutex);
1297 5 : return TRUE;
1298 : }
1299 :
1300 : // Get mutex, release and destroy it
1301 208 : CPLCreateOrAcquireMutex(&(pPage->readMutex), PDFIUM_MUTEX_TIMEOUT);
1302 208 : CPLReleaseMutex(pPage->readMutex);
1303 208 : CPLDestroyMutex(pPage->readMutex);
1304 : // Close page and remove from map
1305 208 : FPDF_ClosePage(FPDFPageFromIPDFPage(pPage->page));
1306 :
1307 208 : pDoc->pages.erase(pPage->pageNum);
1308 208 : delete pPage;
1309 208 : pPage = nullptr;
1310 :
1311 : #ifdef DEBUG
1312 208 : CPLDebug("PDF", "PDFDataset::UnloadPdfiumDocumentPage: pages %lu",
1313 : pDoc->pages.size());
1314 : #endif
1315 : // Another page is used
1316 208 : if (!pDoc->pages.empty())
1317 : {
1318 4 : CPLReleaseMutex(g_oPdfiumLoadDocMutex);
1319 4 : return TRUE;
1320 : }
1321 :
1322 : // Close document and remove from map
1323 204 : FPDF_CloseDocument(FPDFDocumentFromCPDFDocument(pDoc->doc));
1324 204 : g_mPdfiumDatasets.erase(pDoc->filename);
1325 204 : CPLFree(pDoc->filename);
1326 204 : VSIFCloseL(static_cast<VSILFILE *>(pDoc->psFileAccess->m_Param));
1327 204 : delete pDoc->psFileAccess;
1328 204 : delete pDoc;
1329 204 : pDoc = nullptr;
1330 :
1331 : #ifdef DEBUG
1332 204 : CPLDebug("PDF", "PDFDataset::UnloadPdfiumDocumentPage: documents %lu",
1333 : g_mPdfiumDatasets.size());
1334 : #endif
1335 : // Another document is used
1336 204 : if (!g_mPdfiumDatasets.empty())
1337 : {
1338 3 : CPLReleaseMutex(g_oPdfiumLoadDocMutex);
1339 3 : return TRUE;
1340 : }
1341 :
1342 : #ifdef DEBUG
1343 201 : CPLDebug("PDF", "PDFDataset::UnloadPdfiumDocumentPage: Nothing loaded, "
1344 : "destroy Library");
1345 : #endif
1346 : // No document loaded, destroy pdfium
1347 201 : FPDF_DestroyLibrary();
1348 201 : PDFDataset::g_bPdfiumInit = FALSE;
1349 :
1350 201 : CPLReleaseMutex(g_oPdfiumLoadDocMutex);
1351 :
1352 201 : return TRUE;
1353 : }
1354 :
1355 : // ~ static int UnloadPdfiumDocumentPage()
1356 :
1357 : #endif // ~ HAVE_PDFIUM
1358 :
1359 : /************************************************************************/
1360 : /* GetOption() */
1361 : /************************************************************************/
1362 :
1363 2445 : const char *PDFDataset::GetOption(char **papszOpenOptionsIn,
1364 : const char *pszOptionName,
1365 : const char *pszDefaultVal)
1366 : {
1367 2445 : CPLErr eLastErrType = CPLGetLastErrorType();
1368 2445 : CPLErrorNum nLastErrno = CPLGetLastErrorNo();
1369 4890 : CPLString osLastErrorMsg(CPLGetLastErrorMsg());
1370 2445 : CPLXMLNode *psNode = CPLParseXMLString(PDFGetOpenOptionList());
1371 2445 : CPLErrorSetState(eLastErrType, nLastErrno, osLastErrorMsg);
1372 2445 : if (psNode == nullptr)
1373 0 : return pszDefaultVal;
1374 2445 : CPLXMLNode *psIter = psNode->psChild;
1375 11163 : while (psIter != nullptr)
1376 : {
1377 11163 : if (EQUAL(CPLGetXMLValue(psIter, "name", ""), pszOptionName))
1378 : {
1379 : const char *pszVal =
1380 2445 : CSLFetchNameValue(papszOpenOptionsIn, pszOptionName);
1381 2445 : if (pszVal != nullptr)
1382 : {
1383 36 : CPLDestroyXMLNode(psNode);
1384 36 : return pszVal;
1385 : }
1386 : const char *pszAltConfigOption =
1387 2409 : CPLGetXMLValue(psIter, "alt_config_option", nullptr);
1388 2409 : if (pszAltConfigOption != nullptr)
1389 : {
1390 2409 : pszVal = CPLGetConfigOption(pszAltConfigOption, pszDefaultVal);
1391 2409 : CPLDestroyXMLNode(psNode);
1392 2409 : return pszVal;
1393 : }
1394 0 : CPLDestroyXMLNode(psNode);
1395 0 : return pszDefaultVal;
1396 : }
1397 8718 : psIter = psIter->psNext;
1398 : }
1399 0 : CPLError(CE_Failure, CPLE_AppDefined,
1400 : "Requesting an undocumented open option '%s'", pszOptionName);
1401 0 : CPLDestroyXMLNode(psNode);
1402 0 : return pszDefaultVal;
1403 : }
1404 :
1405 : #ifdef HAVE_PDFIUM
1406 :
1407 : /************************************************************************/
1408 : /* GDALPDFiumOCContext */
1409 : /************************************************************************/
1410 :
1411 : class GDALPDFiumOCContext : public CPDF_OCContextInterface
1412 : {
1413 : PDFDataset *m_poDS;
1414 : RetainPtr<CPDF_OCContext> m_DefaultOCContext;
1415 :
1416 : CPL_DISALLOW_COPY_ASSIGN(GDALPDFiumOCContext)
1417 :
1418 : public:
1419 60 : GDALPDFiumOCContext(PDFDataset *poDS, CPDF_Document *pDoc,
1420 : CPDF_OCContext::UsageType usage)
1421 60 : : m_poDS(poDS),
1422 60 : m_DefaultOCContext(pdfium::MakeRetain<CPDF_OCContext>(pDoc, usage))
1423 : {
1424 60 : }
1425 :
1426 : virtual bool
1427 12996 : CheckOCGDictVisible(const CPDF_Dictionary *pOCGDict) const override
1428 : {
1429 : // CPLDebug("PDF", "CheckOCGDictVisible(%d,%d)",
1430 : // pOCGDict->GetObjNum(), pOCGDict->GetGenNum() );
1431 : PDFDataset::VisibilityState eVisibility =
1432 12996 : m_poDS->GetVisibilityStateForOGCPdfium(pOCGDict->GetObjNum(),
1433 12996 : pOCGDict->GetGenNum());
1434 12996 : if (eVisibility == PDFDataset::VISIBILITY_ON)
1435 3294 : return true;
1436 9702 : if (eVisibility == PDFDataset::VISIBILITY_OFF)
1437 999 : return false;
1438 8703 : return m_DefaultOCContext->CheckOCGDictVisible(pOCGDict);
1439 : }
1440 : };
1441 :
1442 : /************************************************************************/
1443 : /* GDALPDFiumRenderDeviceDriver */
1444 : /************************************************************************/
1445 :
1446 : class GDALPDFiumRenderDeviceDriver : public RenderDeviceDriverIface
1447 : {
1448 : std::unique_ptr<RenderDeviceDriverIface> m_poParent;
1449 : CFX_RenderDevice *m_pDevice;
1450 :
1451 : int bEnableVector;
1452 : int bEnableText;
1453 : int bEnableBitmap;
1454 : int bTemporaryEnableVectorForTextStroking;
1455 :
1456 : CPL_DISALLOW_COPY_ASSIGN(GDALPDFiumRenderDeviceDriver)
1457 :
1458 : public:
1459 6 : GDALPDFiumRenderDeviceDriver(
1460 : std::unique_ptr<RenderDeviceDriverIface> &&poParent,
1461 : CFX_RenderDevice *pDevice)
1462 12 : : m_poParent(std::move(poParent)), m_pDevice(pDevice),
1463 : bEnableVector(TRUE), bEnableText(TRUE), bEnableBitmap(TRUE),
1464 6 : bTemporaryEnableVectorForTextStroking(FALSE)
1465 : {
1466 6 : }
1467 :
1468 12 : virtual ~GDALPDFiumRenderDeviceDriver() = default;
1469 :
1470 6 : void SetEnableVector(int bFlag)
1471 : {
1472 6 : bEnableVector = bFlag;
1473 6 : }
1474 :
1475 6 : void SetEnableText(int bFlag)
1476 : {
1477 6 : bEnableText = bFlag;
1478 6 : }
1479 :
1480 6 : void SetEnableBitmap(int bFlag)
1481 : {
1482 6 : bEnableBitmap = bFlag;
1483 6 : }
1484 :
1485 6 : virtual DeviceType GetDeviceType() const override
1486 : {
1487 6 : return m_poParent->GetDeviceType();
1488 : }
1489 :
1490 24 : virtual int GetDeviceCaps(int caps_id) const override
1491 : {
1492 24 : return m_poParent->GetDeviceCaps(caps_id);
1493 : }
1494 :
1495 36 : virtual void SaveState() override
1496 : {
1497 36 : m_poParent->SaveState();
1498 36 : }
1499 :
1500 54 : virtual void RestoreState(bool bKeepSaved) override
1501 : {
1502 54 : m_poParent->RestoreState(bKeepSaved);
1503 54 : }
1504 :
1505 6 : virtual void SetBaseClip(const FX_RECT &rect) override
1506 : {
1507 6 : m_poParent->SetBaseClip(rect);
1508 6 : }
1509 :
1510 : virtual bool
1511 18 : SetClip_PathFill(const CFX_Path &path, const CFX_Matrix *pObject2Device,
1512 : const CFX_FillRenderOptions &fill_options) override
1513 : {
1514 18 : if (!bEnableVector && !bTemporaryEnableVectorForTextStroking)
1515 9 : return true;
1516 9 : return m_poParent->SetClip_PathFill(path, pObject2Device, fill_options);
1517 : }
1518 :
1519 : virtual bool
1520 0 : SetClip_PathStroke(const CFX_Path &path, const CFX_Matrix *pObject2Device,
1521 : const CFX_GraphStateData *pGraphState) override
1522 : {
1523 0 : if (!bEnableVector && !bTemporaryEnableVectorForTextStroking)
1524 0 : return true;
1525 0 : return m_poParent->SetClip_PathStroke(path, pObject2Device,
1526 0 : pGraphState);
1527 : }
1528 :
1529 18 : virtual bool DrawPath(const CFX_Path &path,
1530 : const CFX_Matrix *pObject2Device,
1531 : const CFX_GraphStateData *pGraphState,
1532 : uint32_t fill_color, uint32_t stroke_color,
1533 : const CFX_FillRenderOptions &fill_options) override
1534 : {
1535 18 : if (!bEnableVector && !bTemporaryEnableVectorForTextStroking)
1536 9 : return true;
1537 18 : return m_poParent->DrawPath(path, pObject2Device, pGraphState,
1538 9 : fill_color, stroke_color, fill_options);
1539 : }
1540 :
1541 0 : virtual bool FillRect(const FX_RECT &rect, uint32_t fill_color) override
1542 : {
1543 0 : return m_poParent->FillRect(rect, fill_color);
1544 : }
1545 :
1546 0 : virtual bool DrawCosmeticLine(const CFX_PointF &ptMoveTo,
1547 : const CFX_PointF &ptLineTo,
1548 : uint32_t color) override
1549 : {
1550 0 : if (!bEnableVector && !bTemporaryEnableVectorForTextStroking)
1551 0 : return TRUE;
1552 0 : return m_poParent->DrawCosmeticLine(ptMoveTo, ptLineTo, color);
1553 : }
1554 :
1555 84 : virtual FX_RECT GetClipBox() const override
1556 : {
1557 84 : return m_poParent->GetClipBox();
1558 : }
1559 :
1560 0 : virtual bool GetDIBits(RetainPtr<CFX_DIBitmap> bitmap, int left,
1561 : int top) const override
1562 : {
1563 0 : return m_poParent->GetDIBits(std::move(bitmap), left, top);
1564 : }
1565 :
1566 0 : virtual RetainPtr<const CFX_DIBitmap> GetBackDrop() const override
1567 : {
1568 0 : return m_poParent->GetBackDrop();
1569 : }
1570 :
1571 3 : virtual bool SetDIBits(RetainPtr<const CFX_DIBBase> bitmap, uint32_t color,
1572 : const FX_RECT &src_rect, int dest_left, int dest_top,
1573 : BlendMode blend_type) override
1574 : {
1575 3 : if (!bEnableBitmap && !bTemporaryEnableVectorForTextStroking)
1576 0 : return true;
1577 6 : return m_poParent->SetDIBits(std::move(bitmap), color, src_rect,
1578 3 : dest_left, dest_top, blend_type);
1579 : }
1580 :
1581 0 : virtual bool StretchDIBits(RetainPtr<const CFX_DIBBase> bitmap,
1582 : uint32_t color, int dest_left, int dest_top,
1583 : int dest_width, int dest_height,
1584 : const FX_RECT *pClipRect,
1585 : const FXDIB_ResampleOptions &options,
1586 : BlendMode blend_type) override
1587 : {
1588 0 : if (!bEnableBitmap && !bTemporaryEnableVectorForTextStroking)
1589 0 : return true;
1590 0 : return m_poParent->StretchDIBits(std::move(bitmap), color, dest_left,
1591 : dest_top, dest_width, dest_height,
1592 0 : pClipRect, options, blend_type);
1593 : }
1594 :
1595 6 : virtual StartResult StartDIBits(RetainPtr<const CFX_DIBBase> bitmap,
1596 : float alpha, uint32_t color,
1597 : const CFX_Matrix &matrix,
1598 : const FXDIB_ResampleOptions &options,
1599 : BlendMode blend_type) override
1600 : {
1601 6 : if (!bEnableBitmap && !bTemporaryEnableVectorForTextStroking)
1602 3 : return StartResult(Result::kSuccess, nullptr);
1603 3 : return m_poParent->StartDIBits(std::move(bitmap), alpha, color, matrix,
1604 3 : options, blend_type);
1605 : }
1606 :
1607 3 : virtual bool ContinueDIBits(CFX_AggImageRenderer *handle,
1608 : PauseIndicatorIface *pPause) override
1609 : {
1610 3 : return m_poParent->ContinueDIBits(handle, pPause);
1611 : }
1612 :
1613 9 : virtual bool DrawDeviceText(const pdfium::span<const TextCharPos> &pCharPos,
1614 : CFX_Font *pFont,
1615 : const CFX_Matrix &mtObject2Device,
1616 : float font_size, uint32_t color,
1617 : const CFX_TextRenderOptions &options) override
1618 : {
1619 9 : if (bEnableText)
1620 : {
1621 : // This is quite tricky. We call again the guy who called us
1622 : // (CFX_RenderDevice::DrawNormalText()) but we set a special flag to
1623 : // allow vector&raster operations so that the rendering will happen
1624 : // in the next phase
1625 6 : if (bTemporaryEnableVectorForTextStroking)
1626 3 : return FALSE; // this is the default behavior of the parent
1627 3 : bTemporaryEnableVectorForTextStroking = true;
1628 3 : bool bRet = m_pDevice->DrawNormalText(
1629 : pCharPos, pFont, font_size, mtObject2Device, color, options);
1630 3 : bTemporaryEnableVectorForTextStroking = FALSE;
1631 3 : return bRet;
1632 : }
1633 : else
1634 3 : return true; // pretend that we did the job
1635 : }
1636 :
1637 0 : virtual int GetDriverType() const override
1638 : {
1639 0 : return m_poParent->GetDriverType();
1640 : }
1641 :
1642 : #if defined(_SKIA_SUPPORT_)
1643 : virtual bool DrawShading(const CPDF_ShadingPattern &pattern,
1644 : const CFX_Matrix &matrix, const FX_RECT &clip_rect,
1645 : int alpha) override
1646 : {
1647 : if (!bEnableBitmap && !bTemporaryEnableVectorForTextStroking)
1648 : return true;
1649 : return m_poParent->DrawShading(pattern, matrix, clip_rect, alpha);
1650 : }
1651 : #endif
1652 :
1653 0 : bool MultiplyAlpha(float alpha) override
1654 : {
1655 0 : return m_poParent->MultiplyAlpha(alpha);
1656 : }
1657 :
1658 0 : bool MultiplyAlphaMask(RetainPtr<const CFX_DIBitmap> mask) override
1659 : {
1660 0 : return m_poParent->MultiplyAlphaMask(std::move(mask));
1661 : }
1662 :
1663 : #if defined(_SKIA_SUPPORT_)
1664 : virtual bool SetBitsWithMask(RetainPtr<const CFX_DIBBase> bitmap,
1665 : RetainPtr<const CFX_DIBBase> mask, int left,
1666 : int top, float alpha,
1667 : BlendMode blend_type) override
1668 : {
1669 : if (!bEnableBitmap && !bTemporaryEnableVectorForTextStroking)
1670 : return true;
1671 : return m_poParent->SetBitsWithMask(std::move(bitmap), std::move(mask),
1672 : left, top, alpha, blend_type);
1673 : }
1674 :
1675 : virtual void SetGroupKnockout(bool group_knockout) override
1676 : {
1677 : m_poParent->SetGroupKnockout(group_knockout);
1678 : }
1679 : #endif
1680 : #if defined _SKIA_SUPPORT_ || defined _SKIA_SUPPORT_PATHS_
1681 : virtual void Flush() override
1682 : {
1683 : return m_poParent->Flush();
1684 : }
1685 : #endif
1686 : };
1687 :
1688 : /************************************************************************/
1689 : /* PDFiumRenderPageBitmap() */
1690 : /************************************************************************/
1691 :
1692 : /* This method is a customization of RenderPageImpl()
1693 : from pdfium/fpdfsdk/cpdfsdk_renderpage.cpp to allow selection of which OGC/layer are
1694 : active. Thus it inherits the following license */
1695 : // Copyright 2014-2020 PDFium Authors. All rights reserved.
1696 : //
1697 : // Redistribution and use in source and binary forms, with or without
1698 : // modification, are permitted provided that the following conditions are
1699 : // met:
1700 : //
1701 : // * Redistributions of source code must retain the above copyright
1702 : // notice, this list of conditions and the following disclaimer.
1703 : // * Redistributions in binary form must reproduce the above
1704 : // copyright notice, this list of conditions and the following disclaimer
1705 : // in the documentation and/or other materials provided with the
1706 : // distribution.
1707 : // * Neither the name of Google Inc. nor the names of its
1708 : // contributors may be used to endorse or promote products derived from
1709 : // this software without specific prior written permission.
1710 : //
1711 : // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
1712 : // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
1713 : // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
1714 : // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
1715 : // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
1716 : // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
1717 : // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
1718 : // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
1719 : // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
1720 : // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
1721 : // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
1722 :
1723 60 : static void myRenderPageImpl(PDFDataset *poDS, CPDF_PageRenderContext *pContext,
1724 : CPDF_Page *pPage, const CFX_Matrix &matrix,
1725 : const FX_RECT &clipping_rect, int flags,
1726 : const FPDF_COLORSCHEME *color_scheme,
1727 : bool bNeedToRestore, CPDFSDK_PauseAdapter *pause)
1728 : {
1729 60 : if (!pContext->m_pOptions)
1730 60 : pContext->m_pOptions = std::make_unique<CPDF_RenderOptions>();
1731 :
1732 60 : auto &options = pContext->m_pOptions->GetOptions();
1733 60 : options.bClearType = !!(flags & FPDF_LCD_TEXT);
1734 60 : options.bNoNativeText = !!(flags & FPDF_NO_NATIVETEXT);
1735 60 : options.bLimitedImageCache = !!(flags & FPDF_RENDER_LIMITEDIMAGECACHE);
1736 60 : options.bForceHalftone = !!(flags & FPDF_RENDER_FORCEHALFTONE);
1737 60 : options.bNoTextSmooth = !!(flags & FPDF_RENDER_NO_SMOOTHTEXT);
1738 60 : options.bNoImageSmooth = !!(flags & FPDF_RENDER_NO_SMOOTHIMAGE);
1739 60 : options.bNoPathSmooth = !!(flags & FPDF_RENDER_NO_SMOOTHPATH);
1740 :
1741 : // Grayscale output
1742 60 : if (flags & FPDF_GRAYSCALE)
1743 0 : pContext->m_pOptions->SetColorMode(CPDF_RenderOptions::kGray);
1744 :
1745 60 : if (color_scheme)
1746 : {
1747 0 : pContext->m_pOptions->SetColorMode(CPDF_RenderOptions::kForcedColor);
1748 0 : SetColorFromScheme(color_scheme, pContext->m_pOptions.get());
1749 0 : options.bConvertFillToStroke = !!(flags & FPDF_CONVERT_FILL_TO_STROKE);
1750 : }
1751 :
1752 60 : const CPDF_OCContext::UsageType usage = (flags & FPDF_PRINTING)
1753 60 : ? CPDF_OCContext::kPrint
1754 : : CPDF_OCContext::kView;
1755 120 : pContext->m_pOptions->SetOCContext(pdfium::MakeRetain<GDALPDFiumOCContext>(
1756 60 : poDS, pPage->GetDocument(), usage));
1757 :
1758 60 : pContext->m_pDevice->SaveState();
1759 60 : pContext->m_pDevice->SetBaseClip(clipping_rect);
1760 60 : pContext->m_pDevice->SetClip_Rect(clipping_rect);
1761 60 : pContext->m_pContext = std::make_unique<CPDF_RenderContext>(
1762 120 : pPage->GetDocument(), pPage->GetMutablePageResources(),
1763 120 : pPage->GetPageImageCache());
1764 :
1765 60 : pContext->m_pContext->AppendLayer(pPage, matrix);
1766 :
1767 60 : if (flags & FPDF_ANNOT)
1768 : {
1769 0 : auto pOwnedList = std::make_unique<CPDF_AnnotList>(pPage);
1770 0 : CPDF_AnnotList *pList = pOwnedList.get();
1771 0 : pContext->m_pAnnots = std::move(pOwnedList);
1772 : bool bPrinting =
1773 0 : pContext->m_pDevice->GetDeviceType() != DeviceType::kDisplay;
1774 :
1775 : // TODO(https://crbug.com/pdfium/993) - maybe pass true here.
1776 0 : const bool bShowWidget = false;
1777 0 : pList->DisplayAnnots(pContext->m_pContext.get(), bPrinting, matrix,
1778 : bShowWidget);
1779 : }
1780 :
1781 60 : pContext->m_pRenderer = std::make_unique<CPDF_ProgressiveRenderer>(
1782 60 : pContext->m_pContext.get(), pContext->m_pDevice.get(),
1783 120 : pContext->m_pOptions.get());
1784 60 : pContext->m_pRenderer->Start(pause);
1785 60 : if (bNeedToRestore)
1786 60 : pContext->m_pDevice->RestoreState(false);
1787 60 : }
1788 :
1789 : static void
1790 60 : myRenderPageWithContext(PDFDataset *poDS, CPDF_PageRenderContext *pContext,
1791 : FPDF_PAGE page, int start_x, int start_y, int size_x,
1792 : int size_y, int rotate, int flags,
1793 : const FPDF_COLORSCHEME *color_scheme,
1794 : bool bNeedToRestore, CPDFSDK_PauseAdapter *pause)
1795 : {
1796 60 : CPDF_Page *pPage = CPDFPageFromFPDFPage(page);
1797 60 : if (!pPage)
1798 0 : return;
1799 :
1800 60 : const FX_RECT rect(start_x, start_y, start_x + size_x, start_y + size_y);
1801 60 : myRenderPageImpl(poDS, pContext, pPage,
1802 120 : pPage->GetDisplayMatrix(rect, rotate), rect, flags,
1803 : color_scheme, bNeedToRestore, pause);
1804 : }
1805 :
1806 : class MyRenderDevice final : public CFX_RenderDevice
1807 : {
1808 :
1809 : public:
1810 : // Substitution for CFX_DefaultRenderDevice::Attach
1811 : bool Attach(const RetainPtr<CFX_DIBitmap> &pBitmap, bool bRgbByteOrder,
1812 : const RetainPtr<CFX_DIBitmap> &pBackdropBitmap,
1813 : bool bGroupKnockout, const char *pszRenderingOptions);
1814 : };
1815 :
1816 60 : bool MyRenderDevice::Attach(const RetainPtr<CFX_DIBitmap> &pBitmap,
1817 : bool bRgbByteOrder,
1818 : const RetainPtr<CFX_DIBitmap> &pBackdropBitmap,
1819 : bool bGroupKnockout,
1820 : const char *pszRenderingOptions)
1821 : {
1822 60 : SetBitmap(pBitmap);
1823 :
1824 : std::unique_ptr<RenderDeviceDriverIface> driver =
1825 60 : std::make_unique<pdfium::CFX_AggDeviceDriver>(
1826 60 : pBitmap, bRgbByteOrder, pBackdropBitmap, bGroupKnockout);
1827 60 : if (pszRenderingOptions != nullptr)
1828 : {
1829 7 : int bEnableVector = FALSE;
1830 7 : int bEnableText = FALSE;
1831 7 : int bEnableBitmap = FALSE;
1832 :
1833 7 : char **papszTokens = CSLTokenizeString2(pszRenderingOptions, " ,", 0);
1834 19 : for (int i = 0; papszTokens[i] != nullptr; i++)
1835 : {
1836 12 : if (EQUAL(papszTokens[i], "VECTOR"))
1837 4 : bEnableVector = TRUE;
1838 8 : else if (EQUAL(papszTokens[i], "TEXT"))
1839 4 : bEnableText = TRUE;
1840 4 : else if (EQUAL(papszTokens[i], "RASTER") ||
1841 0 : EQUAL(papszTokens[i], "BITMAP"))
1842 4 : bEnableBitmap = TRUE;
1843 : else
1844 : {
1845 0 : CPLError(CE_Warning, CPLE_NotSupported,
1846 : "Value %s is not a valid value for "
1847 : "GDAL_PDF_RENDERING_OPTIONS",
1848 0 : papszTokens[i]);
1849 : }
1850 : }
1851 7 : CSLDestroy(papszTokens);
1852 :
1853 7 : if (!bEnableVector || !bEnableText || !bEnableBitmap)
1854 : {
1855 : std::unique_ptr<GDALPDFiumRenderDeviceDriver> poGDALRDDriver =
1856 : std::make_unique<GDALPDFiumRenderDeviceDriver>(
1857 12 : std::move(driver), this);
1858 6 : poGDALRDDriver->SetEnableVector(bEnableVector);
1859 6 : poGDALRDDriver->SetEnableText(bEnableText);
1860 6 : poGDALRDDriver->SetEnableBitmap(bEnableBitmap);
1861 6 : driver = std::move(poGDALRDDriver);
1862 : }
1863 : }
1864 :
1865 60 : SetDeviceDriver(std::move(driver));
1866 120 : return true;
1867 : }
1868 :
1869 60 : void PDFDataset::PDFiumRenderPageBitmap(FPDF_BITMAP bitmap, FPDF_PAGE page,
1870 : int start_x, int start_y, int size_x,
1871 : int size_y,
1872 : const char *pszRenderingOptions)
1873 : {
1874 60 : const int rotate = 0;
1875 60 : const int flags = 0;
1876 :
1877 60 : if (!bitmap)
1878 0 : return;
1879 :
1880 60 : CPDF_Page *pPage = CPDFPageFromFPDFPage(page);
1881 60 : if (!pPage)
1882 0 : return;
1883 :
1884 120 : auto pOwnedContext = std::make_unique<CPDF_PageRenderContext>();
1885 60 : CPDF_PageRenderContext *pContext = pOwnedContext.get();
1886 120 : CPDF_Page::RenderContextClearer clearer(pPage);
1887 60 : pPage->SetRenderContext(std::move(pOwnedContext));
1888 :
1889 120 : auto pOwnedDevice = std::make_unique<MyRenderDevice>();
1890 60 : auto pDevice = pOwnedDevice.get();
1891 60 : pContext->m_pDevice = std::move(pOwnedDevice);
1892 :
1893 120 : RetainPtr<CFX_DIBitmap> pBitmap(CFXDIBitmapFromFPDFBitmap(bitmap));
1894 :
1895 60 : pDevice->Attach(pBitmap, !!(flags & FPDF_REVERSE_BYTE_ORDER), nullptr,
1896 : false, pszRenderingOptions);
1897 :
1898 60 : myRenderPageWithContext(this, pContext, page, start_x, start_y, size_x,
1899 : size_y, rotate, flags,
1900 : /*color_scheme=*/nullptr,
1901 : /*need_to_restore=*/true, /*pause=*/nullptr);
1902 :
1903 : #ifdef _SKIA_SUPPORT_PATHS_
1904 : pDevice->Flush(true);
1905 : pBitmap->UnPreMultiply();
1906 : #endif
1907 : }
1908 :
1909 : #endif /* HAVE_PDFIUM */
1910 :
1911 : /************************************************************************/
1912 : /* ReadPixels() */
1913 : /************************************************************************/
1914 :
1915 107 : CPLErr PDFDataset::ReadPixels(int nReqXOff, int nReqYOff, int nReqXSize,
1916 : int nReqYSize, GSpacing nPixelSpace,
1917 : GSpacing nLineSpace, GSpacing nBandSpace,
1918 : GByte *pabyData)
1919 : {
1920 107 : CPLErr eErr = CE_None;
1921 : const char *pszRenderingOptions =
1922 107 : GetOption(papszOpenOptions, "RENDERING_OPTIONS", nullptr);
1923 :
1924 : #ifdef HAVE_POPPLER
1925 107 : if (m_bUseLib.test(PDFLIB_POPPLER))
1926 : {
1927 : SplashColor sColor;
1928 47 : sColor[0] = 255;
1929 47 : sColor[1] = 255;
1930 47 : sColor[2] = 255;
1931 : GDALPDFOutputDev *poSplashOut = new GDALPDFOutputDev(
1932 47 : (nBands < 4) ? splashModeRGB8 : splashModeXBGR8, 4, false,
1933 47 : (nBands < 4) ? sColor : nullptr);
1934 :
1935 47 : if (pszRenderingOptions != nullptr)
1936 : {
1937 7 : poSplashOut->SetEnableVector(FALSE);
1938 7 : poSplashOut->SetEnableText(FALSE);
1939 7 : poSplashOut->SetEnableBitmap(FALSE);
1940 :
1941 : char **papszTokens =
1942 7 : CSLTokenizeString2(pszRenderingOptions, " ,", 0);
1943 19 : for (int i = 0; papszTokens[i] != nullptr; i++)
1944 : {
1945 12 : if (EQUAL(papszTokens[i], "VECTOR"))
1946 4 : poSplashOut->SetEnableVector(TRUE);
1947 8 : else if (EQUAL(papszTokens[i], "TEXT"))
1948 4 : poSplashOut->SetEnableText(TRUE);
1949 4 : else if (EQUAL(papszTokens[i], "RASTER") ||
1950 0 : EQUAL(papszTokens[i], "BITMAP"))
1951 4 : poSplashOut->SetEnableBitmap(TRUE);
1952 : else
1953 : {
1954 0 : CPLError(CE_Warning, CPLE_NotSupported,
1955 : "Value %s is not a valid value for "
1956 : "GDAL_PDF_RENDERING_OPTIONS",
1957 0 : papszTokens[i]);
1958 : }
1959 : }
1960 7 : CSLDestroy(papszTokens);
1961 : }
1962 :
1963 47 : PDFDoc *poDoc = m_poDocPoppler;
1964 47 : poSplashOut->startDoc(poDoc);
1965 :
1966 : // Note: Poppler 25.2 is certainly not the lowest version where we can
1967 : // avoid the hack.
1968 : #if !(POPPLER_MAJOR_VERSION > 25 || \
1969 : (POPPLER_MAJOR_VERSION == 25 && POPPLER_MINOR_VERSION >= 2))
1970 : #define USE_OPTCONTENT_HACK
1971 : #endif
1972 :
1973 : #ifdef USE_OPTCONTENT_HACK
1974 : /* EVIL: we modify a private member... */
1975 : /* poppler (at least 0.12 and 0.14 versions) don't render correctly */
1976 : /* some PDFs and display an error message 'Could not find a OCG with
1977 : * Ref' */
1978 : /* in those cases. This processing of optional content is an addition of
1979 : */
1980 : /* poppler in comparison to original xpdf, which hasn't the issue. All
1981 : * in */
1982 : /* all, nullifying optContent removes the error message and improves the
1983 : * rendering */
1984 47 : Catalog *poCatalog = poDoc->getCatalog();
1985 47 : OCGs *poOldOCGs = poCatalog->optContent;
1986 47 : if (!m_bUseOCG)
1987 40 : poCatalog->optContent = nullptr;
1988 : #endif
1989 : try
1990 : {
1991 47 : poDoc->displayPageSlice(poSplashOut, m_iPage, m_dfDPI, m_dfDPI, 0,
1992 : TRUE, false, false, nReqXOff, nReqYOff,
1993 : nReqXSize, nReqYSize);
1994 : }
1995 0 : catch (const std::exception &e)
1996 : {
1997 0 : CPLError(CE_Failure, CPLE_AppDefined,
1998 0 : "PDFDoc::displayPageSlice() failed with %s", e.what());
1999 :
2000 : #ifdef USE_OPTCONTENT_HACK
2001 : /* Restore back */
2002 0 : poCatalog->optContent = poOldOCGs;
2003 : #endif
2004 0 : delete poSplashOut;
2005 0 : return CE_Failure;
2006 : }
2007 :
2008 : #ifdef USE_OPTCONTENT_HACK
2009 : /* Restore back */
2010 47 : poCatalog->optContent = poOldOCGs;
2011 : #endif
2012 :
2013 47 : SplashBitmap *poBitmap = poSplashOut->getBitmap();
2014 94 : if (poBitmap->getWidth() != nReqXSize ||
2015 47 : poBitmap->getHeight() != nReqYSize)
2016 : {
2017 0 : CPLError(
2018 : CE_Failure, CPLE_AppDefined,
2019 : "Bitmap decoded size (%dx%d) doesn't match raster size (%dx%d)",
2020 : poBitmap->getWidth(), poBitmap->getHeight(), nReqXSize,
2021 : nReqYSize);
2022 0 : delete poSplashOut;
2023 0 : return CE_Failure;
2024 : }
2025 :
2026 47 : GByte *pabyDataR = pabyData;
2027 47 : GByte *pabyDataG = pabyData + nBandSpace;
2028 47 : GByte *pabyDataB = pabyData + 2 * nBandSpace;
2029 47 : GByte *pabyDataA = pabyData + 3 * nBandSpace;
2030 47 : GByte *pabySrc = poBitmap->getDataPtr();
2031 : GByte *pabyAlphaSrc =
2032 47 : reinterpret_cast<GByte *>(poBitmap->getAlphaPtr());
2033 : int i, j;
2034 19718 : for (j = 0; j < nReqYSize; j++)
2035 : {
2036 19170200 : for (i = 0; i < nReqXSize; i++)
2037 : {
2038 19150500 : if (nBands < 4)
2039 : {
2040 19101900 : pabyDataR[i * nPixelSpace] = pabySrc[i * 3 + 0];
2041 19101900 : pabyDataG[i * nPixelSpace] = pabySrc[i * 3 + 1];
2042 19101900 : pabyDataB[i * nPixelSpace] = pabySrc[i * 3 + 2];
2043 : }
2044 : else
2045 : {
2046 48600 : pabyDataR[i * nPixelSpace] = pabySrc[i * 4 + 2];
2047 48600 : pabyDataG[i * nPixelSpace] = pabySrc[i * 4 + 1];
2048 48600 : pabyDataB[i * nPixelSpace] = pabySrc[i * 4 + 0];
2049 48600 : pabyDataA[i * nPixelSpace] = pabyAlphaSrc[i];
2050 : }
2051 : }
2052 19671 : pabyDataR += nLineSpace;
2053 19671 : pabyDataG += nLineSpace;
2054 19671 : pabyDataB += nLineSpace;
2055 19671 : pabyDataA += nLineSpace;
2056 19671 : pabyAlphaSrc += poBitmap->getAlphaRowSize();
2057 19671 : pabySrc += poBitmap->getRowSize();
2058 : }
2059 47 : delete poSplashOut;
2060 : }
2061 : #endif // HAVE_POPPLER
2062 :
2063 : #ifdef HAVE_PODOFO
2064 : if (m_bUseLib.test(PDFLIB_PODOFO))
2065 : {
2066 : if (m_bPdfToPpmFailed)
2067 : return CE_Failure;
2068 :
2069 : if (pszRenderingOptions != nullptr &&
2070 : !EQUAL(pszRenderingOptions, "RASTER,VECTOR,TEXT"))
2071 : {
2072 : CPLError(CE_Warning, CPLE_NotSupported,
2073 : "GDAL_PDF_RENDERING_OPTIONS only supported "
2074 : "when PDF lib is Poppler.");
2075 : }
2076 :
2077 : CPLString osTmpFilename;
2078 : int nRet;
2079 :
2080 : #ifdef notdef
2081 : int bUseSpawn =
2082 : CPLTestBool(CPLGetConfigOption("GDAL_PDF_USE_SPAWN", "YES"));
2083 : if (!bUseSpawn)
2084 : {
2085 : CPLString osCmd = CPLSPrintf(
2086 : "pdftoppm -r %f -x %d -y %d -W %d -H %d -f %d -l %d \"%s\"",
2087 : dfDPI, nReqXOff, nReqYOff, nReqXSize, nReqYSize, iPage, iPage,
2088 : osFilename.c_str());
2089 :
2090 : if (!osUserPwd.empty())
2091 : {
2092 : osCmd += " -upw \"";
2093 : osCmd += osUserPwd;
2094 : osCmd += "\"";
2095 : }
2096 :
2097 : CPLString osTmpFilenamePrefix = CPLGenerateTempFilenameSafe("pdf");
2098 : osTmpFilename =
2099 : CPLSPrintf("%s-%d.ppm", osTmpFilenamePrefix.c_str(), iPage);
2100 : osCmd += CPLSPrintf(" \"%s\"", osTmpFilenamePrefix.c_str());
2101 :
2102 : CPLDebug("PDF", "Running '%s'", osCmd.c_str());
2103 : nRet = CPLSystem(nullptr, osCmd.c_str());
2104 : }
2105 : else
2106 : #endif // notdef
2107 : {
2108 : char **papszArgs = nullptr;
2109 : papszArgs = CSLAddString(papszArgs, "pdftoppm");
2110 : papszArgs = CSLAddString(papszArgs, "-r");
2111 : papszArgs = CSLAddString(papszArgs, CPLSPrintf("%f", m_dfDPI));
2112 : papszArgs = CSLAddString(papszArgs, "-x");
2113 : papszArgs = CSLAddString(papszArgs, CPLSPrintf("%d", nReqXOff));
2114 : papszArgs = CSLAddString(papszArgs, "-y");
2115 : papszArgs = CSLAddString(papszArgs, CPLSPrintf("%d", nReqYOff));
2116 : papszArgs = CSLAddString(papszArgs, "-W");
2117 : papszArgs = CSLAddString(papszArgs, CPLSPrintf("%d", nReqXSize));
2118 : papszArgs = CSLAddString(papszArgs, "-H");
2119 : papszArgs = CSLAddString(papszArgs, CPLSPrintf("%d", nReqYSize));
2120 : papszArgs = CSLAddString(papszArgs, "-f");
2121 : papszArgs = CSLAddString(papszArgs, CPLSPrintf("%d", m_iPage));
2122 : papszArgs = CSLAddString(papszArgs, "-l");
2123 : papszArgs = CSLAddString(papszArgs, CPLSPrintf("%d", m_iPage));
2124 : if (!m_osUserPwd.empty())
2125 : {
2126 : papszArgs = CSLAddString(papszArgs, "-upw");
2127 : papszArgs = CSLAddString(papszArgs, m_osUserPwd.c_str());
2128 : }
2129 : papszArgs = CSLAddString(papszArgs, m_osFilename.c_str());
2130 :
2131 : osTmpFilename = VSIMemGenerateHiddenFilename("pdf_temp.ppm");
2132 : VSILFILE *fpOut = VSIFOpenL(osTmpFilename, "wb");
2133 : if (fpOut != nullptr)
2134 : {
2135 : nRet = CPLSpawn(papszArgs, nullptr, fpOut, FALSE);
2136 : VSIFCloseL(fpOut);
2137 : }
2138 : else
2139 : nRet = -1;
2140 :
2141 : CSLDestroy(papszArgs);
2142 : }
2143 :
2144 : if (nRet == 0)
2145 : {
2146 : auto poDS = std::unique_ptr<GDALDataset>(GDALDataset::Open(
2147 : osTmpFilename, GDAL_OF_RASTER, nullptr, nullptr, nullptr));
2148 : if (poDS)
2149 : {
2150 : if (poDS->GetRasterCount() == 3)
2151 : {
2152 : eErr = poDS->RasterIO(GF_Read, 0, 0, nReqXSize, nReqYSize,
2153 : pabyData, nReqXSize, nReqYSize,
2154 : GDT_Byte, 3, nullptr, nPixelSpace,
2155 : nLineSpace, nBandSpace, nullptr);
2156 : }
2157 : }
2158 : }
2159 : else
2160 : {
2161 : CPLDebug("PDF", "Ret code = %d", nRet);
2162 : m_bPdfToPpmFailed = true;
2163 : eErr = CE_Failure;
2164 : }
2165 : VSIUnlink(osTmpFilename);
2166 : }
2167 : #endif // HAVE_PODOFO
2168 : #ifdef HAVE_PDFIUM
2169 107 : if (m_bUseLib.test(PDFLIB_PDFIUM))
2170 : {
2171 60 : if (!m_poPagePdfium)
2172 : {
2173 0 : return CE_Failure;
2174 : }
2175 :
2176 : // Pdfium does not support multithreading
2177 60 : CPLCreateOrAcquireMutex(&g_oPdfiumReadMutex, PDFIUM_MUTEX_TIMEOUT);
2178 :
2179 60 : CPLCreateOrAcquireMutex(&(m_poPagePdfium->readMutex),
2180 : PDFIUM_MUTEX_TIMEOUT);
2181 :
2182 : // Parsing content required before rastering
2183 : // can takes too long for PDF with large number of objects/layers
2184 60 : m_poPagePdfium->page->ParseContent();
2185 :
2186 : FPDF_BITMAP bitmap =
2187 60 : FPDFBitmap_Create(nReqXSize, nReqYSize, nBands == 4 /*alpha*/);
2188 : // As coded now, FPDFBitmap_Create cannot allocate more than 1 GB
2189 60 : if (bitmap == nullptr)
2190 : {
2191 : // Release mutex - following code is thread-safe
2192 0 : CPLReleaseMutex(m_poPagePdfium->readMutex);
2193 0 : CPLReleaseMutex(g_oPdfiumReadMutex);
2194 :
2195 : #ifdef notdef
2196 : // If the requested area is not too small, then try subdividing
2197 : if ((GIntBig)nReqXSize * nReqYSize * 4 > 1024 * 1024)
2198 : {
2199 : #ifdef DEBUG
2200 : CPLDebug(
2201 : "PDF",
2202 : "Subdividing PDFDataset::ReadPixels(%d, %d, %d, %d, "
2203 : "scaleFactor=%d)",
2204 : nReqXOff, nReqYOff, nReqXSize, nReqYSize,
2205 : 1 << ((PDFRasterBand *)GetRasterBand(1))->nResolutionLevel);
2206 : #endif
2207 : if (nReqXSize >= nReqYSize)
2208 : {
2209 : eErr = ReadPixels(nReqXOff, nReqYOff, nReqXSize / 2,
2210 : nReqYSize, nPixelSpace, nLineSpace,
2211 : nBandSpace, pabyData);
2212 : if (eErr == CE_None)
2213 : {
2214 : eErr = ReadPixels(
2215 : nReqXSize / 2, nReqYOff, nReqXSize - nReqXSize / 2,
2216 : nReqYSize, nPixelSpace, nLineSpace, nBandSpace,
2217 : pabyData + nPixelSpace * (nReqXSize / 2));
2218 : }
2219 : }
2220 : else
2221 : {
2222 : eErr = ReadPixels(nReqXOff, nReqYOff, nReqXSize,
2223 : nReqYSize - nReqYSize / 2, nPixelSpace,
2224 : nLineSpace, nBandSpace, pabyData);
2225 : if (eErr == CE_None)
2226 : {
2227 : eErr =
2228 : ReadPixels(nReqXOff, nReqYSize / 2, nReqXSize,
2229 : nReqYSize - nReqYSize / 2, nPixelSpace,
2230 : nLineSpace, nBandSpace,
2231 : pabyData + nLineSpace * (nReqYSize / 2));
2232 : }
2233 : }
2234 : return eErr;
2235 : }
2236 : #endif
2237 :
2238 0 : CPLError(CE_Failure, CPLE_AppDefined,
2239 : "FPDFBitmap_Create(%d,%d) failed", nReqXSize, nReqYSize);
2240 :
2241 0 : return CE_Failure;
2242 : }
2243 : // alpha is 0% which is transported to FF if not alpha
2244 : // Default background color is white
2245 60 : FPDF_DWORD color = 0x00FFFFFF; // A,R,G,B
2246 60 : FPDFBitmap_FillRect(bitmap, 0, 0, nReqXSize, nReqYSize, color);
2247 :
2248 : #ifdef DEBUG
2249 : // start_x, start_y, size_x, size_y, rotate, flags
2250 60 : CPLDebug("PDF",
2251 : "PDFDataset::ReadPixels(%d, %d, %d, %d, scaleFactor=%d)",
2252 : nReqXOff, nReqYOff, nReqXSize, nReqYSize,
2253 60 : 1 << cpl::down_cast<PDFRasterBand *>(GetRasterBand(1))
2254 60 : ->nResolutionLevel);
2255 :
2256 60 : CPLDebug("PDF", "FPDF_RenderPageBitmap(%d, %d, %d, %d)", -nReqXOff,
2257 : -nReqYOff, nRasterXSize, nRasterYSize);
2258 : #endif
2259 :
2260 : // Part of PDF is render with -x, -y, page_width, page_height
2261 : // (not requested size!)
2262 60 : PDFiumRenderPageBitmap(
2263 60 : bitmap, FPDFPageFromIPDFPage(m_poPagePdfium->page), -nReqXOff,
2264 : -nReqYOff, nRasterXSize, nRasterYSize, pszRenderingOptions);
2265 :
2266 60 : int stride = FPDFBitmap_GetStride(bitmap);
2267 : const GByte *buffer =
2268 60 : reinterpret_cast<const GByte *>(FPDFBitmap_GetBuffer(bitmap));
2269 :
2270 : // Release mutex - following code is thread-safe
2271 60 : CPLReleaseMutex(m_poPagePdfium->readMutex);
2272 60 : CPLReleaseMutex(g_oPdfiumReadMutex);
2273 :
2274 : // Source data is B, G, R, unused.
2275 : // Destination data is R, G, B (,A if is alpha)
2276 60 : GByte *pabyDataR = pabyData;
2277 60 : GByte *pabyDataG = pabyData + 1 * nBandSpace;
2278 60 : GByte *pabyDataB = pabyData + 2 * nBandSpace;
2279 60 : GByte *pabyDataA = pabyData + 3 * nBandSpace;
2280 : // Copied from Poppler
2281 : int i, j;
2282 23455 : for (j = 0; j < nReqYSize; j++)
2283 : {
2284 20752600 : for (i = 0; i < nReqXSize; i++)
2285 : {
2286 20729200 : pabyDataR[i * nPixelSpace] = buffer[(i * 4) + 2];
2287 20729200 : pabyDataG[i * nPixelSpace] = buffer[(i * 4) + 1];
2288 20729200 : pabyDataB[i * nPixelSpace] = buffer[(i * 4) + 0];
2289 20729200 : if (nBands == 4)
2290 : {
2291 20729200 : pabyDataA[i * nPixelSpace] = buffer[(i * 4) + 3];
2292 : }
2293 : }
2294 23395 : pabyDataR += nLineSpace;
2295 23395 : pabyDataG += nLineSpace;
2296 23395 : pabyDataB += nLineSpace;
2297 23395 : pabyDataA += nLineSpace;
2298 23395 : buffer += stride;
2299 : }
2300 60 : FPDFBitmap_Destroy(bitmap);
2301 : }
2302 : #endif // ~ HAVE_PDFIUM
2303 :
2304 107 : return eErr;
2305 : }
2306 :
2307 : /************************************************************************/
2308 : /* ==================================================================== */
2309 : /* PDFImageRasterBand */
2310 : /* ==================================================================== */
2311 : /************************************************************************/
2312 :
2313 : class PDFImageRasterBand final : public PDFRasterBand
2314 : {
2315 : friend class PDFDataset;
2316 :
2317 : public:
2318 : PDFImageRasterBand(PDFDataset *, int);
2319 :
2320 : virtual CPLErr IReadBlock(int, int, void *) override;
2321 : };
2322 :
2323 : /************************************************************************/
2324 : /* PDFImageRasterBand() */
2325 : /************************************************************************/
2326 :
2327 0 : PDFImageRasterBand::PDFImageRasterBand(PDFDataset *poDSIn, int nBandIn)
2328 0 : : PDFRasterBand(poDSIn, nBandIn, 0)
2329 : {
2330 0 : }
2331 :
2332 : /************************************************************************/
2333 : /* IReadBlock() */
2334 : /************************************************************************/
2335 :
2336 0 : CPLErr PDFImageRasterBand::IReadBlock(int /* nBlockXOff */, int nBlockYOff,
2337 : void *pImage)
2338 : {
2339 0 : PDFDataset *poGDS = cpl::down_cast<PDFDataset *>(poDS);
2340 0 : CPLAssert(poGDS->m_poImageObj != nullptr);
2341 :
2342 0 : if (!poGDS->m_bTried)
2343 : {
2344 0 : int nBands = (poGDS->nBands == 1) ? 1 : 3;
2345 0 : poGDS->m_bTried = true;
2346 0 : if (nBands == 3)
2347 : {
2348 0 : poGDS->m_pabyCachedData = static_cast<GByte *>(
2349 0 : VSIMalloc3(nBands, nRasterXSize, nRasterYSize));
2350 0 : if (poGDS->m_pabyCachedData == nullptr)
2351 0 : return CE_Failure;
2352 : }
2353 :
2354 0 : GDALPDFStream *poStream = poGDS->m_poImageObj->GetStream();
2355 0 : GByte *pabyStream = nullptr;
2356 :
2357 0 : if (poStream == nullptr ||
2358 0 : static_cast<size_t>(poStream->GetLength()) !=
2359 0 : static_cast<size_t>(nBands) * nRasterXSize * nRasterYSize ||
2360 0 : (pabyStream = reinterpret_cast<GByte *>(poStream->GetBytes())) ==
2361 : nullptr)
2362 : {
2363 0 : VSIFree(poGDS->m_pabyCachedData);
2364 0 : poGDS->m_pabyCachedData = nullptr;
2365 0 : return CE_Failure;
2366 : }
2367 :
2368 0 : if (nBands == 3)
2369 : {
2370 : /* pixel interleaved to band interleaved */
2371 0 : for (size_t i = 0;
2372 0 : i < static_cast<size_t>(nRasterXSize) * nRasterYSize; i++)
2373 : {
2374 0 : poGDS->m_pabyCachedData[0 * static_cast<size_t>(nRasterXSize) *
2375 : nRasterYSize +
2376 0 : i] = pabyStream[3 * i + 0];
2377 0 : poGDS->m_pabyCachedData[1 * static_cast<size_t>(nRasterXSize) *
2378 0 : nRasterYSize +
2379 0 : i] = pabyStream[3 * i + 1];
2380 0 : poGDS->m_pabyCachedData[2 * static_cast<size_t>(nRasterXSize) *
2381 0 : nRasterYSize +
2382 0 : i] = pabyStream[3 * i + 2];
2383 : }
2384 0 : VSIFree(pabyStream);
2385 : }
2386 : else
2387 0 : poGDS->m_pabyCachedData = pabyStream;
2388 : }
2389 :
2390 0 : if (poGDS->m_pabyCachedData == nullptr)
2391 0 : return CE_Failure;
2392 :
2393 0 : if (nBand == 4)
2394 0 : memset(pImage, 255, nRasterXSize);
2395 : else
2396 0 : memcpy(pImage,
2397 0 : poGDS->m_pabyCachedData +
2398 0 : static_cast<size_t>(nBand - 1) * nRasterXSize *
2399 0 : nRasterYSize +
2400 0 : static_cast<size_t>(nBlockYOff) * nRasterXSize,
2401 0 : nRasterXSize);
2402 :
2403 0 : return CE_None;
2404 : }
2405 :
2406 : /************************************************************************/
2407 : /* PDFDataset() */
2408 : /************************************************************************/
2409 :
2410 382 : PDFDataset::PDFDataset(PDFDataset *poParentDSIn, int nXSize, int nYSize)
2411 382 : : m_bIsOvrDS(poParentDSIn != nullptr),
2412 : #ifdef HAVE_PDFIUM
2413 382 : m_poDocPdfium(poParentDSIn ? poParentDSIn->m_poDocPdfium : nullptr),
2414 382 : m_poPagePdfium(poParentDSIn ? poParentDSIn->m_poPagePdfium : nullptr),
2415 : #endif
2416 1146 : m_bSetStyle(CPLTestBool(CPLGetConfigOption("OGR_PDF_SET_STYLE", "YES")))
2417 : {
2418 382 : m_oSRS.SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER);
2419 382 : nRasterXSize = nXSize;
2420 382 : nRasterYSize = nYSize;
2421 382 : if (poParentDSIn)
2422 2 : m_bUseLib = poParentDSIn->m_bUseLib;
2423 :
2424 382 : InitMapOperators();
2425 382 : }
2426 :
2427 : /************************************************************************/
2428 : /* IBuildOverviews() */
2429 : /************************************************************************/
2430 :
2431 2 : CPLErr PDFDataset::IBuildOverviews(const char *pszResampling, int nOverviews,
2432 : const int *panOverviewList, int nListBands,
2433 : const int *panBandList,
2434 : GDALProgressFunc pfnProgress,
2435 : void *pProgressData,
2436 : CSLConstList papszOptions)
2437 :
2438 : {
2439 : /* -------------------------------------------------------------------- */
2440 : /* In order for building external overviews to work properly we */
2441 : /* discard any concept of internal overviews when the user */
2442 : /* first requests to build external overviews. */
2443 : /* -------------------------------------------------------------------- */
2444 2 : if (!m_apoOvrDS.empty())
2445 : {
2446 2 : m_apoOvrDSBackup = std::move(m_apoOvrDS);
2447 2 : m_apoOvrDS.clear();
2448 : }
2449 :
2450 : // Prevents InitOverviews() to run
2451 2 : m_apoOvrDSBackup.emplace_back(nullptr);
2452 2 : const CPLErr eErr = GDALPamDataset::IBuildOverviews(
2453 : pszResampling, nOverviews, panOverviewList, nListBands, panBandList,
2454 : pfnProgress, pProgressData, papszOptions);
2455 2 : m_apoOvrDSBackup.pop_back();
2456 2 : return eErr;
2457 : }
2458 :
2459 : /************************************************************************/
2460 : /* PDFFreeDoc() */
2461 : /************************************************************************/
2462 :
2463 : #ifdef HAVE_POPPLER
2464 170 : static void PDFFreeDoc(PDFDoc *poDoc)
2465 : {
2466 170 : if (poDoc)
2467 : {
2468 : /* hack to avoid potential cross heap issues on Win32 */
2469 : /* str is the VSIPDFFileStream object passed in the constructor of
2470 : * PDFDoc */
2471 : // NOTE: This is potentially very dangerous. See comment in
2472 : // VSIPDFFileStream::FillBuffer() */
2473 170 : delete poDoc->str;
2474 170 : poDoc->str = nullptr;
2475 :
2476 170 : delete poDoc;
2477 : }
2478 170 : }
2479 : #endif
2480 :
2481 : /************************************************************************/
2482 : /* GetCatalog() */
2483 : /************************************************************************/
2484 :
2485 1214 : GDALPDFObject *PDFDataset::GetCatalog()
2486 : {
2487 1214 : if (m_poCatalogObject)
2488 834 : return m_poCatalogObject;
2489 :
2490 : #ifdef HAVE_POPPLER
2491 380 : if (m_bUseLib.test(PDFLIB_POPPLER) && m_poDocPoppler)
2492 : {
2493 : m_poCatalogObjectPoppler =
2494 167 : std::make_unique<Object>(m_poDocPoppler->getXRef()->getCatalog());
2495 167 : if (!m_poCatalogObjectPoppler->isNull())
2496 167 : m_poCatalogObject =
2497 167 : new GDALPDFObjectPoppler(m_poCatalogObjectPoppler.get(), FALSE);
2498 : }
2499 : #endif
2500 :
2501 : #ifdef HAVE_PODOFO
2502 : if (m_bUseLib.test(PDFLIB_PODOFO) && m_poDocPodofo)
2503 : {
2504 : int nCatalogNum = 0;
2505 : int nCatalogGen = 0;
2506 : VSILFILE *fp = VSIFOpenL(m_osFilename.c_str(), "rb");
2507 : if (fp != nullptr)
2508 : {
2509 : GDALPDFUpdateWriter oWriter(fp);
2510 : if (oWriter.ParseTrailerAndXRef())
2511 : {
2512 : nCatalogNum = oWriter.GetCatalogNum().toInt();
2513 : nCatalogGen = oWriter.GetCatalogGen();
2514 : }
2515 : oWriter.Close();
2516 : }
2517 :
2518 : PoDoFo::PdfObject *poCatalogPodofo =
2519 : m_poDocPodofo->GetObjects().GetObject(
2520 : PoDoFo::PdfReference(nCatalogNum, nCatalogGen));
2521 : if (poCatalogPodofo)
2522 : m_poCatalogObject = new GDALPDFObjectPodofo(
2523 : poCatalogPodofo, m_poDocPodofo->GetObjects());
2524 : }
2525 : #endif
2526 :
2527 : #ifdef HAVE_PDFIUM
2528 380 : if (m_bUseLib.test(PDFLIB_PDFIUM) && m_poDocPdfium)
2529 : {
2530 213 : const CPDF_Dictionary *catalog = m_poDocPdfium->doc->GetRoot();
2531 213 : if (catalog)
2532 213 : m_poCatalogObject =
2533 : // coverity is confused by WrapRetain(), believing that multiple
2534 : // smart pointers manage the same raw pointer. Which is actually
2535 : // true, but a RetainPtr holds a reference counted object. It is
2536 : // thus safe to have several RetainPtr holding it.
2537 : // coverity[multiple_init_smart_ptr]
2538 213 : GDALPDFObjectPdfium::Build(pdfium::WrapRetain(catalog));
2539 : }
2540 : #endif // ~ HAVE_PDFIUM
2541 :
2542 380 : return m_poCatalogObject;
2543 : }
2544 :
2545 : /************************************************************************/
2546 : /* ~PDFDataset() */
2547 : /************************************************************************/
2548 :
2549 764 : PDFDataset::~PDFDataset()
2550 : {
2551 : #ifdef HAVE_PDFIUM
2552 382 : m_apoOvrDS.clear();
2553 382 : m_apoOvrDSBackup.clear();
2554 : #endif
2555 :
2556 382 : CPLFree(m_pabyCachedData);
2557 382 : m_pabyCachedData = nullptr;
2558 :
2559 382 : delete m_poNeatLine;
2560 382 : m_poNeatLine = nullptr;
2561 :
2562 : /* Collect data necessary to update */
2563 382 : int nNum = 0;
2564 382 : int nGen = 0;
2565 382 : GDALPDFDictionaryRW *poPageDictCopy = nullptr;
2566 382 : GDALPDFDictionaryRW *poCatalogDictCopy = nullptr;
2567 382 : if (m_poPageObj)
2568 : {
2569 380 : nNum = m_poPageObj->GetRefNum().toInt();
2570 380 : nGen = m_poPageObj->GetRefGen();
2571 783 : if (eAccess == GA_Update &&
2572 23 : (m_bProjDirty || m_bNeatLineDirty || m_bInfoDirty || m_bXMPDirty) &&
2573 426 : nNum != 0 && m_poPageObj != nullptr &&
2574 23 : m_poPageObj->GetType() == PDFObjectType_Dictionary)
2575 : {
2576 23 : poPageDictCopy = m_poPageObj->GetDictionary()->Clone();
2577 :
2578 23 : if (m_bXMPDirty)
2579 : {
2580 : /* We need the catalog because it points to the XMP Metadata
2581 : * object */
2582 6 : GetCatalog();
2583 12 : if (m_poCatalogObject &&
2584 6 : m_poCatalogObject->GetType() == PDFObjectType_Dictionary)
2585 : poCatalogDictCopy =
2586 6 : m_poCatalogObject->GetDictionary()->Clone();
2587 : }
2588 : }
2589 : }
2590 :
2591 : /* Close document (and file descriptor) to be able to open it */
2592 : /* in read-write mode afterwards */
2593 382 : delete m_poPageObj;
2594 382 : m_poPageObj = nullptr;
2595 382 : delete m_poCatalogObject;
2596 382 : m_poCatalogObject = nullptr;
2597 : #ifdef HAVE_POPPLER
2598 382 : if (m_bUseLib.test(PDFLIB_POPPLER))
2599 : {
2600 167 : m_poCatalogObjectPoppler.reset();
2601 167 : PDFFreeDoc(m_poDocPoppler);
2602 : }
2603 382 : m_poDocPoppler = nullptr;
2604 : #endif
2605 : #ifdef HAVE_PODOFO
2606 : if (m_bUseLib.test(PDFLIB_PODOFO))
2607 : {
2608 : delete m_poDocPodofo;
2609 : }
2610 : m_poDocPodofo = nullptr;
2611 : #endif
2612 : #ifdef HAVE_PDFIUM
2613 382 : if (!m_bIsOvrDS)
2614 : {
2615 378 : if (m_bUseLib.test(PDFLIB_PDFIUM))
2616 : {
2617 213 : UnloadPdfiumDocumentPage(&m_poDocPdfium, &m_poPagePdfium);
2618 : }
2619 : }
2620 382 : m_poDocPdfium = nullptr;
2621 382 : m_poPagePdfium = nullptr;
2622 : #endif // ~ HAVE_PDFIUM
2623 :
2624 : /* Now do the update */
2625 382 : if (poPageDictCopy)
2626 : {
2627 23 : VSILFILE *fp = VSIFOpenL(m_osFilename, "rb+");
2628 23 : if (fp != nullptr)
2629 : {
2630 46 : GDALPDFUpdateWriter oWriter(fp);
2631 23 : if (oWriter.ParseTrailerAndXRef())
2632 : {
2633 23 : if ((m_bProjDirty || m_bNeatLineDirty) &&
2634 : poPageDictCopy != nullptr)
2635 11 : oWriter.UpdateProj(this, m_dfDPI, poPageDictCopy,
2636 22 : GDALPDFObjectNum(nNum), nGen);
2637 :
2638 23 : if (m_bInfoDirty)
2639 6 : oWriter.UpdateInfo(this);
2640 :
2641 23 : if (m_bXMPDirty && poCatalogDictCopy != nullptr)
2642 6 : oWriter.UpdateXMP(this, poCatalogDictCopy);
2643 : }
2644 23 : oWriter.Close();
2645 : }
2646 : else
2647 : {
2648 0 : CPLError(CE_Failure, CPLE_AppDefined,
2649 : "Cannot open %s in update mode", m_osFilename.c_str());
2650 : }
2651 : }
2652 382 : delete poPageDictCopy;
2653 382 : poPageDictCopy = nullptr;
2654 382 : delete poCatalogDictCopy;
2655 382 : poCatalogDictCopy = nullptr;
2656 :
2657 382 : if (m_nGCPCount > 0)
2658 : {
2659 2 : GDALDeinitGCPs(m_nGCPCount, m_pasGCPList);
2660 2 : CPLFree(m_pasGCPList);
2661 2 : m_pasGCPList = nullptr;
2662 2 : m_nGCPCount = 0;
2663 : }
2664 :
2665 382 : CleanupIntermediateResources();
2666 :
2667 382 : m_apoLayers.clear();
2668 :
2669 : // Do that only after having destroyed Poppler objects
2670 382 : m_fp.reset();
2671 764 : }
2672 :
2673 : /************************************************************************/
2674 : /* IRasterIO() */
2675 : /************************************************************************/
2676 :
2677 1674 : CPLErr PDFDataset::IRasterIO(GDALRWFlag eRWFlag, int nXOff, int nYOff,
2678 : int nXSize, int nYSize, void *pData, int nBufXSize,
2679 : int nBufYSize, GDALDataType eBufType,
2680 : int nBandCount, BANDMAP_TYPE panBandMap,
2681 : GSpacing nPixelSpace, GSpacing nLineSpace,
2682 : GSpacing nBandSpace,
2683 : GDALRasterIOExtraArg *psExtraArg)
2684 : {
2685 : // Try to pass the request to the most appropriate overview dataset.
2686 1674 : if (nBufXSize < nXSize && nBufYSize < nYSize)
2687 : {
2688 0 : int bTried = FALSE;
2689 0 : const CPLErr eErr = TryOverviewRasterIO(
2690 : eRWFlag, nXOff, nYOff, nXSize, nYSize, pData, nBufXSize, nBufYSize,
2691 : eBufType, nBandCount, panBandMap, nPixelSpace, nLineSpace,
2692 : nBandSpace, psExtraArg, &bTried);
2693 0 : if (bTried)
2694 0 : return eErr;
2695 : }
2696 :
2697 : int nBandBlockXSize, nBandBlockYSize;
2698 1674 : int bReadPixels = FALSE;
2699 1674 : GetRasterBand(1)->GetBlockSize(&nBandBlockXSize, &nBandBlockYSize);
2700 3348 : if (m_aiTiles.empty() && eRWFlag == GF_Read && nXSize == nBufXSize &&
2701 1674 : nYSize == nBufYSize &&
2702 1674 : (nBufXSize > nBandBlockXSize || nBufYSize > nBandBlockYSize) &&
2703 3350 : eBufType == GDT_Byte && nBandCount == nBands &&
2704 2 : IsAllBands(nBandCount, panBandMap))
2705 : {
2706 2 : bReadPixels = TRUE;
2707 : #ifdef HAVE_PODOFO
2708 : if (m_bUseLib.test(PDFLIB_PODOFO) && nBands == 4)
2709 : {
2710 : bReadPixels = FALSE;
2711 : }
2712 : #endif
2713 : }
2714 :
2715 1674 : if (bReadPixels)
2716 2 : return ReadPixels(nXOff, nYOff, nXSize, nYSize, nPixelSpace, nLineSpace,
2717 2 : nBandSpace, static_cast<GByte *>(pData));
2718 :
2719 1672 : if (nBufXSize != nXSize || nBufYSize != nYSize || eBufType != GDT_Byte)
2720 : {
2721 0 : m_bCacheBlocksForOtherBands = true;
2722 : }
2723 1672 : CPLErr eErr = GDALPamDataset::IRasterIO(
2724 : eRWFlag, nXOff, nYOff, nXSize, nYSize, pData, nBufXSize, nBufYSize,
2725 : eBufType, nBandCount, panBandMap, nPixelSpace, nLineSpace, nBandSpace,
2726 : psExtraArg);
2727 1672 : m_bCacheBlocksForOtherBands = false;
2728 1672 : return eErr;
2729 : }
2730 :
2731 : /************************************************************************/
2732 : /* IRasterIO() */
2733 : /************************************************************************/
2734 :
2735 43215 : CPLErr PDFRasterBand::IRasterIO(GDALRWFlag eRWFlag, int nXOff, int nYOff,
2736 : int nXSize, int nYSize, void *pData,
2737 : int nBufXSize, int nBufYSize,
2738 : GDALDataType eBufType, GSpacing nPixelSpace,
2739 : GSpacing nLineSpace,
2740 : GDALRasterIOExtraArg *psExtraArg)
2741 : {
2742 43215 : PDFDataset *poGDS = cpl::down_cast<PDFDataset *>(poDS);
2743 :
2744 : // Try to pass the request to the most appropriate overview dataset.
2745 43215 : if (nBufXSize < nXSize && nBufYSize < nYSize)
2746 : {
2747 0 : int bTried = FALSE;
2748 0 : const CPLErr eErr = TryOverviewRasterIO(
2749 : eRWFlag, nXOff, nYOff, nXSize, nYSize, pData, nBufXSize, nBufYSize,
2750 : eBufType, nPixelSpace, nLineSpace, psExtraArg, &bTried);
2751 0 : if (bTried)
2752 0 : return eErr;
2753 : }
2754 :
2755 43215 : if (nBufXSize != nXSize || nBufYSize != nYSize || eBufType != GDT_Byte)
2756 : {
2757 38177 : poGDS->m_bCacheBlocksForOtherBands = true;
2758 : }
2759 43215 : CPLErr eErr = GDALPamRasterBand::IRasterIO(
2760 : eRWFlag, nXOff, nYOff, nXSize, nYSize, pData, nBufXSize, nBufYSize,
2761 : eBufType, nPixelSpace, nLineSpace, psExtraArg);
2762 43215 : poGDS->m_bCacheBlocksForOtherBands = false;
2763 43215 : return eErr;
2764 : }
2765 :
2766 : /************************************************************************/
2767 : /* PDFDatasetErrorFunction() */
2768 : /************************************************************************/
2769 :
2770 : #ifdef HAVE_POPPLER
2771 :
2772 2 : static void PDFDatasetErrorFunctionCommon(const CPLString &osError)
2773 : {
2774 2 : if (strcmp(osError.c_str(), "Incorrect password") == 0)
2775 2 : return;
2776 : /* Reported on newer USGS GeoPDF */
2777 0 : if (strcmp(osError.c_str(),
2778 0 : "Couldn't find group for reference to set OFF") == 0)
2779 : {
2780 0 : CPLDebug("PDF", "%s", osError.c_str());
2781 0 : return;
2782 : }
2783 :
2784 0 : CPLError(CE_Failure, CPLE_AppDefined, "%s", osError.c_str());
2785 : }
2786 :
2787 : static int g_nPopplerErrors = 0;
2788 : constexpr int MAX_POPPLER_ERRORS = 1000;
2789 :
2790 2 : static void PDFDatasetErrorFunction(ErrorCategory /* eErrCategory */,
2791 : Goffset nPos, const char *pszMsg)
2792 : {
2793 2 : if (g_nPopplerErrors >= MAX_POPPLER_ERRORS)
2794 : {
2795 : // If there are too many errors, then unregister ourselves and turn
2796 : // quiet error mode, as the error() function in poppler can spend
2797 : // significant time formatting an error message we won't emit...
2798 0 : setErrorCallback(nullptr);
2799 0 : globalParams->setErrQuiet(true);
2800 0 : return;
2801 : }
2802 :
2803 2 : g_nPopplerErrors++;
2804 4 : CPLString osError;
2805 :
2806 2 : if (nPos >= 0)
2807 : osError.Printf("Pos = " CPL_FRMT_GUIB ", ",
2808 0 : static_cast<GUIntBig>(nPos));
2809 2 : osError += pszMsg;
2810 2 : PDFDatasetErrorFunctionCommon(osError);
2811 : }
2812 : #endif
2813 :
2814 : /************************************************************************/
2815 : /* GDALPDFParseStreamContentOnlyDrawForm() */
2816 : /************************************************************************/
2817 :
2818 354 : static CPLString GDALPDFParseStreamContentOnlyDrawForm(const char *pszContent)
2819 : {
2820 708 : CPLString osToken;
2821 : char ch;
2822 354 : int nCurIdx = 0;
2823 708 : CPLString osCurrentForm;
2824 :
2825 : // CPLDebug("PDF", "content = %s", pszContent);
2826 :
2827 1198 : while ((ch = *pszContent) != '\0')
2828 : {
2829 1198 : if (ch == '%')
2830 : {
2831 : /* Skip comments until end-of-line */
2832 0 : while ((ch = *pszContent) != '\0')
2833 : {
2834 0 : if (ch == '\r' || ch == '\n')
2835 : break;
2836 0 : pszContent++;
2837 : }
2838 0 : if (ch == 0)
2839 0 : break;
2840 : }
2841 1198 : else if (ch == ' ' || ch == '\r' || ch == '\n')
2842 : {
2843 408 : if (!osToken.empty())
2844 : {
2845 408 : if (nCurIdx == 0 && osToken[0] == '/')
2846 : {
2847 54 : osCurrentForm = osToken.substr(1);
2848 54 : nCurIdx++;
2849 : }
2850 354 : else if (nCurIdx == 1 && osToken == "Do")
2851 : {
2852 0 : nCurIdx++;
2853 : }
2854 : else
2855 : {
2856 354 : return "";
2857 : }
2858 : }
2859 54 : osToken = "";
2860 : }
2861 : else
2862 790 : osToken += ch;
2863 844 : pszContent++;
2864 : }
2865 :
2866 0 : return osCurrentForm;
2867 : }
2868 :
2869 : /************************************************************************/
2870 : /* GDALPDFParseStreamContent() */
2871 : /************************************************************************/
2872 :
2873 : typedef enum
2874 : {
2875 : STATE_INIT,
2876 : STATE_AFTER_q,
2877 : STATE_AFTER_cm,
2878 : STATE_AFTER_Do
2879 : } PDFStreamState;
2880 :
2881 : /* This parser is reduced to understanding sequences that draw rasters, such as
2882 : :
2883 : q
2884 : scaleX 0 0 scaleY translateX translateY cm
2885 : /ImXXX Do
2886 : Q
2887 :
2888 : All other sequences will abort the parsing.
2889 :
2890 : Returns TRUE if the stream only contains images.
2891 : */
2892 :
2893 354 : static int GDALPDFParseStreamContent(const char *pszContent,
2894 : GDALPDFDictionary *poXObjectDict,
2895 : double *pdfDPI, int *pbDPISet,
2896 : int *pnBands,
2897 : std::vector<GDALPDFTileDesc> &asTiles,
2898 : int bAcceptRotationTerms)
2899 : {
2900 708 : CPLString osToken;
2901 : char ch;
2902 354 : PDFStreamState nState = STATE_INIT;
2903 354 : int nCurIdx = 0;
2904 : double adfVals[6];
2905 708 : CPLString osCurrentImage;
2906 :
2907 354 : double dfDPI = DEFAULT_DPI;
2908 354 : *pbDPISet = FALSE;
2909 :
2910 21695 : while ((ch = *pszContent) != '\0')
2911 : {
2912 21426 : if (ch == '%')
2913 : {
2914 : /* Skip comments until end-of-line */
2915 0 : while ((ch = *pszContent) != '\0')
2916 : {
2917 0 : if (ch == '\r' || ch == '\n')
2918 : break;
2919 0 : pszContent++;
2920 : }
2921 0 : if (ch == 0)
2922 0 : break;
2923 : }
2924 21426 : else if (ch == ' ' || ch == '\t' || ch == '\r' || ch == '\n')
2925 : {
2926 6454 : if (!osToken.empty())
2927 : {
2928 6454 : if (nState == STATE_INIT)
2929 : {
2930 664 : if (osToken == "q")
2931 : {
2932 579 : nState = STATE_AFTER_q;
2933 579 : nCurIdx = 0;
2934 : }
2935 85 : else if (osToken != "Q")
2936 85 : return FALSE;
2937 : }
2938 5790 : else if (nState == STATE_AFTER_q)
2939 : {
2940 4053 : if (osToken == "q")
2941 : {
2942 : // ignore
2943 : }
2944 4053 : else if (nCurIdx < 6)
2945 : {
2946 3474 : adfVals[nCurIdx++] = CPLAtof(osToken);
2947 : }
2948 579 : else if (nCurIdx == 6 && osToken == "cm")
2949 : {
2950 579 : nState = STATE_AFTER_cm;
2951 579 : nCurIdx = 0;
2952 : }
2953 : else
2954 0 : return FALSE;
2955 : }
2956 1737 : else if (nState == STATE_AFTER_cm)
2957 : {
2958 1158 : if (nCurIdx == 0 && osToken[0] == '/')
2959 : {
2960 579 : osCurrentImage = osToken.substr(1);
2961 : }
2962 579 : else if (osToken == "Do")
2963 : {
2964 579 : nState = STATE_AFTER_Do;
2965 : }
2966 : else
2967 0 : return FALSE;
2968 : }
2969 579 : else if (nState == STATE_AFTER_Do)
2970 : {
2971 579 : if (osToken == "Q")
2972 : {
2973 : GDALPDFObject *poImage =
2974 579 : poXObjectDict->Get(osCurrentImage);
2975 1158 : if (poImage != nullptr &&
2976 579 : poImage->GetType() == PDFObjectType_Dictionary)
2977 : {
2978 : GDALPDFTileDesc sTile;
2979 : GDALPDFDictionary *poImageDict =
2980 579 : poImage->GetDictionary();
2981 579 : GDALPDFObject *poWidth = poImageDict->Get("Width");
2982 : GDALPDFObject *poHeight =
2983 579 : poImageDict->Get("Height");
2984 : GDALPDFObject *poColorSpace =
2985 579 : poImageDict->Get("ColorSpace");
2986 579 : GDALPDFObject *poSMask = poImageDict->Get("SMask");
2987 1158 : if (poColorSpace &&
2988 579 : poColorSpace->GetType() == PDFObjectType_Name)
2989 : {
2990 573 : if (poColorSpace->GetName() == "DeviceRGB")
2991 : {
2992 221 : sTile.nBands = 3;
2993 221 : if (*pnBands < 3)
2994 47 : *pnBands = 3;
2995 : }
2996 352 : else if (poColorSpace->GetName() ==
2997 : "DeviceGray")
2998 : {
2999 352 : sTile.nBands = 1;
3000 352 : if (*pnBands < 1)
3001 244 : *pnBands = 1;
3002 : }
3003 : else
3004 0 : sTile.nBands = 0;
3005 : }
3006 579 : if (poSMask != nullptr)
3007 190 : *pnBands = 4;
3008 :
3009 579 : if (poWidth && poHeight &&
3010 0 : ((bAcceptRotationTerms &&
3011 579 : adfVals[1] == -adfVals[2]) ||
3012 579 : (!bAcceptRotationTerms && adfVals[1] == 0.0 &&
3013 579 : adfVals[2] == 0.0)))
3014 : {
3015 579 : double dfWidth = Get(poWidth);
3016 579 : double dfHeight = Get(poHeight);
3017 579 : double dfScaleX = adfVals[0];
3018 579 : double dfScaleY = adfVals[3];
3019 579 : if (dfWidth > 0 && dfHeight > 0 &&
3020 579 : dfScaleX > 0 && dfScaleY > 0 &&
3021 579 : dfWidth / dfScaleX * DEFAULT_DPI <
3022 579 : INT_MAX &&
3023 579 : dfHeight / dfScaleY * DEFAULT_DPI < INT_MAX)
3024 : {
3025 1158 : double dfDPI_X = ROUND_IF_CLOSE(
3026 579 : dfWidth / dfScaleX * DEFAULT_DPI, 1e-3);
3027 1158 : double dfDPI_Y = ROUND_IF_CLOSE(
3028 579 : dfHeight / dfScaleY * DEFAULT_DPI,
3029 : 1e-3);
3030 : // CPLDebug("PDF", "Image %s, width = %.16g,
3031 : // height = %.16g, scaleX = %.16g, scaleY =
3032 : // %.16g --> DPI_X = %.16g, DPI_Y = %.16g",
3033 : // osCurrentImage.c_str(),
3034 : // dfWidth, dfHeight,
3035 : // dfScaleX, dfScaleY,
3036 : // dfDPI_X, dfDPI_Y);
3037 579 : if (dfDPI_X > dfDPI)
3038 40 : dfDPI = dfDPI_X;
3039 579 : if (dfDPI_Y > dfDPI)
3040 0 : dfDPI = dfDPI_Y;
3041 :
3042 579 : memcpy(&(sTile.adfCM), adfVals,
3043 : 6 * sizeof(double));
3044 579 : sTile.poImage = poImage;
3045 579 : sTile.dfWidth = dfWidth;
3046 579 : sTile.dfHeight = dfHeight;
3047 579 : asTiles.push_back(sTile);
3048 :
3049 579 : *pbDPISet = TRUE;
3050 579 : *pdfDPI = dfDPI;
3051 : }
3052 : }
3053 : }
3054 579 : nState = STATE_INIT;
3055 : }
3056 : else
3057 0 : return FALSE;
3058 : }
3059 : }
3060 6369 : osToken = "";
3061 : }
3062 : else
3063 14972 : osToken += ch;
3064 21341 : pszContent++;
3065 : }
3066 :
3067 269 : return TRUE;
3068 : }
3069 :
3070 : /************************************************************************/
3071 : /* CheckTiledRaster() */
3072 : /************************************************************************/
3073 :
3074 297 : int PDFDataset::CheckTiledRaster()
3075 : {
3076 : size_t i;
3077 297 : int l_nBlockXSize = 0;
3078 297 : int l_nBlockYSize = 0;
3079 297 : const double dfUserUnit = m_dfDPI * USER_UNIT_IN_INCH;
3080 :
3081 : /* First pass : check that all tiles have same DPI, */
3082 : /* are contained entirely in the raster size, */
3083 : /* and determine the block size */
3084 870 : for (i = 0; i < m_asTiles.size(); i++)
3085 : {
3086 579 : double dfDrawWidth = m_asTiles[i].adfCM[0] * dfUserUnit;
3087 579 : double dfDrawHeight = m_asTiles[i].adfCM[3] * dfUserUnit;
3088 579 : double dfX = m_asTiles[i].adfCM[4] * dfUserUnit;
3089 579 : double dfY = m_asTiles[i].adfCM[5] * dfUserUnit;
3090 579 : int nX = static_cast<int>(dfX + 0.1);
3091 579 : int nY = static_cast<int>(dfY + 0.1);
3092 579 : int nWidth = static_cast<int>(m_asTiles[i].dfWidth + 1e-8);
3093 579 : int nHeight = static_cast<int>(m_asTiles[i].dfHeight + 1e-8);
3094 :
3095 579 : GDALPDFDictionary *poImageDict = m_asTiles[i].poImage->GetDictionary();
3096 : GDALPDFObject *poBitsPerComponent =
3097 579 : poImageDict->Get("BitsPerComponent");
3098 579 : GDALPDFObject *poColorSpace = poImageDict->Get("ColorSpace");
3099 579 : GDALPDFObject *poFilter = poImageDict->Get("Filter");
3100 :
3101 : /* Podofo cannot uncompress JPEG2000 streams */
3102 579 : if (m_bUseLib.test(PDFLIB_PODOFO) && poFilter != nullptr &&
3103 579 : poFilter->GetType() == PDFObjectType_Name &&
3104 0 : poFilter->GetName() == "JPXDecode")
3105 : {
3106 0 : CPLDebug("PDF", "Tile %d : Incompatible image for tiled reading",
3107 : static_cast<int>(i));
3108 0 : return FALSE;
3109 : }
3110 :
3111 579 : if (poBitsPerComponent == nullptr || Get(poBitsPerComponent) != 8 ||
3112 579 : poColorSpace == nullptr ||
3113 2083 : poColorSpace->GetType() != PDFObjectType_Name ||
3114 925 : (poColorSpace->GetName() != "DeviceRGB" &&
3115 352 : poColorSpace->GetName() != "DeviceGray"))
3116 : {
3117 6 : CPLDebug("PDF", "Tile %d : Incompatible image for tiled reading",
3118 : static_cast<int>(i));
3119 6 : return FALSE;
3120 : }
3121 :
3122 573 : if (fabs(dfDrawWidth - m_asTiles[i].dfWidth) > 1e-2 ||
3123 573 : fabs(dfDrawHeight - m_asTiles[i].dfHeight) > 1e-2 ||
3124 573 : fabs(nWidth - m_asTiles[i].dfWidth) > 1e-8 ||
3125 573 : fabs(nHeight - m_asTiles[i].dfHeight) > 1e-8 ||
3126 573 : fabs(nX - dfX) > 1e-1 || fabs(nY - dfY) > 1e-1 || nX < 0 ||
3127 1146 : nY < 0 || nX + nWidth > nRasterXSize || nY >= nRasterYSize)
3128 : {
3129 0 : CPLDebug("PDF", "Tile %d : %f %f %f %f %f %f", static_cast<int>(i),
3130 0 : dfX, dfY, dfDrawWidth, dfDrawHeight, m_asTiles[i].dfWidth,
3131 0 : m_asTiles[i].dfHeight);
3132 0 : return FALSE;
3133 : }
3134 573 : if (l_nBlockXSize == 0 && l_nBlockYSize == 0 && nX == 0 && nY != 0)
3135 : {
3136 18 : l_nBlockXSize = nWidth;
3137 18 : l_nBlockYSize = nHeight;
3138 : }
3139 : }
3140 291 : if (l_nBlockXSize <= 0 || l_nBlockYSize <= 0 || l_nBlockXSize > 2048 ||
3141 : l_nBlockYSize > 2048)
3142 273 : return FALSE;
3143 :
3144 18 : int nXBlocks = DIV_ROUND_UP(nRasterXSize, l_nBlockXSize);
3145 18 : int nYBlocks = DIV_ROUND_UP(nRasterYSize, l_nBlockYSize);
3146 :
3147 : /* Second pass to determine that all tiles are properly aligned on block
3148 : * size */
3149 318 : for (i = 0; i < m_asTiles.size(); i++)
3150 : {
3151 300 : double dfX = m_asTiles[i].adfCM[4] * dfUserUnit;
3152 300 : double dfY = m_asTiles[i].adfCM[5] * dfUserUnit;
3153 300 : int nX = static_cast<int>(dfX + 0.1);
3154 300 : int nY = static_cast<int>(dfY + 0.1);
3155 300 : int nWidth = static_cast<int>(m_asTiles[i].dfWidth + 1e-8);
3156 300 : int nHeight = static_cast<int>(m_asTiles[i].dfHeight + 1e-8);
3157 300 : int bOK = TRUE;
3158 300 : int nBlockXOff = nX / l_nBlockXSize;
3159 300 : if ((nX % l_nBlockXSize) != 0)
3160 0 : bOK = FALSE;
3161 300 : if (nBlockXOff < nXBlocks - 1 && nWidth != l_nBlockXSize)
3162 0 : bOK = FALSE;
3163 300 : if (nBlockXOff == nXBlocks - 1 && nX + nWidth != nRasterXSize)
3164 0 : bOK = FALSE;
3165 :
3166 300 : if (nY > 0 && nHeight != l_nBlockYSize)
3167 0 : bOK = FALSE;
3168 300 : if (nY == 0 && nHeight != nRasterYSize - (nYBlocks - 1) * l_nBlockYSize)
3169 0 : bOK = FALSE;
3170 :
3171 300 : if (!bOK)
3172 : {
3173 0 : CPLDebug("PDF", "Tile %d : %d %d %d %d", static_cast<int>(i), nX,
3174 : nY, nWidth, nHeight);
3175 0 : return FALSE;
3176 : }
3177 : }
3178 :
3179 : /* Third pass to set the aiTiles array */
3180 18 : m_aiTiles.resize(static_cast<size_t>(nXBlocks) * nYBlocks, -1);
3181 318 : for (i = 0; i < m_asTiles.size(); i++)
3182 : {
3183 300 : double dfX = m_asTiles[i].adfCM[4] * dfUserUnit;
3184 300 : double dfY = m_asTiles[i].adfCM[5] * dfUserUnit;
3185 300 : int nHeight = static_cast<int>(m_asTiles[i].dfHeight + 1e-8);
3186 300 : int nX = static_cast<int>(dfX + 0.1);
3187 300 : int nY = nRasterYSize - (static_cast<int>(dfY + 0.1) + nHeight);
3188 300 : int nBlockXOff = nX / l_nBlockXSize;
3189 300 : int nBlockYOff = nY / l_nBlockYSize;
3190 300 : m_aiTiles[nBlockYOff * nXBlocks + nBlockXOff] = static_cast<int>(i);
3191 : }
3192 :
3193 18 : this->m_nBlockXSize = l_nBlockXSize;
3194 18 : this->m_nBlockYSize = l_nBlockYSize;
3195 :
3196 18 : return TRUE;
3197 : }
3198 :
3199 : /************************************************************************/
3200 : /* GuessDPI() */
3201 : /************************************************************************/
3202 :
3203 380 : void PDFDataset::GuessDPI(GDALPDFDictionary *poPageDict, int *pnBands)
3204 : {
3205 380 : const char *pszDPI = GetOption(papszOpenOptions, "DPI", nullptr);
3206 380 : if (pszDPI != nullptr)
3207 : {
3208 : // coverity[tainted_data]
3209 4 : m_dfDPI = CPLAtof(pszDPI);
3210 : }
3211 : else
3212 : {
3213 : /* Try to get a better value from the images that are drawn */
3214 : /* Very simplistic logic. Will only work for raster only PDF */
3215 :
3216 376 : GDALPDFObject *poContents = poPageDict->Get("Contents");
3217 750 : if (poContents != nullptr &&
3218 374 : poContents->GetType() == PDFObjectType_Array)
3219 : {
3220 1 : GDALPDFArray *poContentsArray = poContents->GetArray();
3221 1 : if (poContentsArray->GetLength() == 1)
3222 : {
3223 1 : poContents = poContentsArray->Get(0);
3224 : }
3225 : }
3226 :
3227 : GDALPDFObject *poXObject =
3228 376 : poPageDict->LookupObject("Resources.XObject");
3229 750 : if (poContents != nullptr &&
3230 374 : poContents->GetType() == PDFObjectType_Dictionary &&
3231 750 : poXObject != nullptr &&
3232 356 : poXObject->GetType() == PDFObjectType_Dictionary)
3233 : {
3234 356 : GDALPDFDictionary *poXObjectDict = poXObject->GetDictionary();
3235 356 : GDALPDFDictionary *poContentDict = poXObjectDict;
3236 356 : GDALPDFStream *poPageStream = poContents->GetStream();
3237 356 : if (poPageStream != nullptr)
3238 : {
3239 354 : char *pszContent = nullptr;
3240 354 : const int64_t MAX_LENGTH = 10 * 1000 * 1000;
3241 354 : int64_t nLength = poPageStream->GetLength(MAX_LENGTH);
3242 354 : int bResetTiles = FALSE;
3243 354 : double dfScaleDPI = 1.0;
3244 :
3245 354 : if (nLength < MAX_LENGTH)
3246 : {
3247 708 : CPLString osForm;
3248 354 : pszContent = poPageStream->GetBytes();
3249 354 : if (pszContent != nullptr)
3250 : {
3251 : #ifdef DEBUG
3252 : const char *pszDumpStream =
3253 354 : CPLGetConfigOption("PDF_DUMP_STREAM", nullptr);
3254 354 : if (pszDumpStream != nullptr)
3255 : {
3256 0 : VSILFILE *fpDump = VSIFOpenL(pszDumpStream, "wb");
3257 0 : if (fpDump)
3258 : {
3259 0 : VSIFWriteL(pszContent, 1,
3260 : static_cast<int>(nLength), fpDump);
3261 0 : VSIFCloseL(fpDump);
3262 : }
3263 : }
3264 : #endif // DEBUG
3265 : osForm =
3266 354 : GDALPDFParseStreamContentOnlyDrawForm(pszContent);
3267 354 : if (osForm.empty())
3268 : {
3269 : /* Special case for USGS Topo PDF, like
3270 : * CA_Hollywood_20090811_OM_geo.pdf */
3271 : const char *pszOGCDo =
3272 354 : strstr(pszContent, " /XO1 Do");
3273 354 : if (pszOGCDo)
3274 : {
3275 0 : const char *pszcm = strstr(pszContent, " cm ");
3276 0 : if (pszcm != nullptr && pszcm < pszOGCDo)
3277 : {
3278 : const char *pszNextcm =
3279 0 : strstr(pszcm + 2, "cm");
3280 0 : if (pszNextcm == nullptr ||
3281 : pszNextcm > pszOGCDo)
3282 : {
3283 0 : const char *pszIter = pszcm;
3284 0 : while (pszIter > pszContent)
3285 : {
3286 0 : if ((*pszIter >= '0' &&
3287 0 : *pszIter <= '9') ||
3288 0 : *pszIter == '-' ||
3289 0 : *pszIter == '.' ||
3290 0 : *pszIter == ' ')
3291 0 : pszIter--;
3292 : else
3293 : {
3294 0 : pszIter++;
3295 0 : break;
3296 : }
3297 : }
3298 0 : CPLString oscm(pszIter);
3299 0 : oscm.resize(pszcm - pszIter);
3300 : char **papszTokens =
3301 0 : CSLTokenizeString(oscm);
3302 0 : double dfScaleX = -1.0;
3303 0 : double dfScaleY = -2.0;
3304 0 : if (CSLCount(papszTokens) == 6)
3305 : {
3306 0 : dfScaleX = CPLAtof(papszTokens[0]);
3307 0 : dfScaleY = CPLAtof(papszTokens[3]);
3308 : }
3309 0 : CSLDestroy(papszTokens);
3310 0 : if (dfScaleX == dfScaleY &&
3311 : dfScaleX > 0.0)
3312 : {
3313 0 : osForm = "XO1";
3314 0 : bResetTiles = TRUE;
3315 0 : dfScaleDPI = 1.0 / dfScaleX;
3316 : }
3317 0 : }
3318 : }
3319 : else
3320 : {
3321 0 : osForm = "XO1";
3322 0 : bResetTiles = TRUE;
3323 : }
3324 : }
3325 : /* Special case for USGS Topo PDF, like
3326 : * CA_Sacramento_East_20120308_TM_geo.pdf */
3327 : else
3328 : {
3329 : CPLString osOCG =
3330 708 : FindLayerOCG(poPageDict, "Orthoimage");
3331 354 : if (!osOCG.empty())
3332 : {
3333 0 : const char *pszBDCLookup = CPLSPrintf(
3334 : "/OC /%s BDC", osOCG.c_str());
3335 : const char *pszBDC =
3336 0 : strstr(pszContent, pszBDCLookup);
3337 0 : if (pszBDC != nullptr)
3338 : {
3339 0 : const char *pszIter =
3340 0 : pszBDC + strlen(pszBDCLookup);
3341 0 : while (*pszIter != '\0')
3342 : {
3343 0 : if (*pszIter == 13 ||
3344 0 : *pszIter == 10 ||
3345 0 : *pszIter == ' ' ||
3346 0 : *pszIter == 'q')
3347 0 : pszIter++;
3348 : else
3349 : break;
3350 : }
3351 0 : if (STARTS_WITH(pszIter,
3352 : "1 0 0 1 0 0 cm\n"))
3353 0 : pszIter +=
3354 : strlen("1 0 0 1 0 0 cm\n");
3355 0 : if (*pszIter == '/')
3356 : {
3357 0 : pszIter++;
3358 : const char *pszDo =
3359 0 : strstr(pszIter, " Do");
3360 0 : if (pszDo != nullptr)
3361 : {
3362 0 : osForm = pszIter;
3363 0 : osForm.resize(pszDo - pszIter);
3364 0 : bResetTiles = TRUE;
3365 : }
3366 : }
3367 : }
3368 : }
3369 : }
3370 : }
3371 : }
3372 :
3373 354 : if (!osForm.empty())
3374 : {
3375 0 : CPLFree(pszContent);
3376 0 : pszContent = nullptr;
3377 :
3378 0 : GDALPDFObject *poObjForm = poXObjectDict->Get(osForm);
3379 0 : if (poObjForm != nullptr &&
3380 0 : poObjForm->GetType() == PDFObjectType_Dictionary &&
3381 0 : (poPageStream = poObjForm->GetStream()) != nullptr)
3382 : {
3383 : GDALPDFDictionary *poObjFormDict =
3384 0 : poObjForm->GetDictionary();
3385 : GDALPDFObject *poSubtype =
3386 0 : poObjFormDict->Get("Subtype");
3387 0 : if (poSubtype != nullptr &&
3388 0 : poSubtype->GetType() == PDFObjectType_Name &&
3389 0 : poSubtype->GetName() == "Form")
3390 : {
3391 0 : nLength = poPageStream->GetLength(MAX_LENGTH);
3392 0 : if (nLength < MAX_LENGTH)
3393 : {
3394 0 : pszContent = poPageStream->GetBytes();
3395 :
3396 : GDALPDFObject *poXObject2 =
3397 0 : poObjFormDict->LookupObject(
3398 : "Resources.XObject");
3399 0 : if (poXObject2 != nullptr &&
3400 0 : poXObject2->GetType() ==
3401 : PDFObjectType_Dictionary)
3402 : poContentDict =
3403 0 : poXObject2->GetDictionary();
3404 : }
3405 : }
3406 : }
3407 : }
3408 : }
3409 :
3410 354 : if (pszContent != nullptr)
3411 : {
3412 354 : int bDPISet = FALSE;
3413 :
3414 354 : const char *pszContentToParse = pszContent;
3415 354 : if (bResetTiles)
3416 : {
3417 0 : while (*pszContentToParse != '\0')
3418 : {
3419 0 : if (*pszContentToParse == 13 ||
3420 0 : *pszContentToParse == 10 ||
3421 0 : *pszContentToParse == ' ' ||
3422 0 : (*pszContentToParse >= '0' &&
3423 0 : *pszContentToParse <= '9') ||
3424 0 : *pszContentToParse == '.' ||
3425 0 : *pszContentToParse == '-' ||
3426 0 : *pszContentToParse == 'l' ||
3427 0 : *pszContentToParse == 'm' ||
3428 0 : *pszContentToParse == 'n' ||
3429 0 : *pszContentToParse == 'W')
3430 0 : pszContentToParse++;
3431 : else
3432 : break;
3433 : }
3434 : }
3435 :
3436 354 : GDALPDFParseStreamContent(pszContentToParse, poContentDict,
3437 : &(m_dfDPI), &bDPISet, pnBands,
3438 354 : m_asTiles, bResetTiles);
3439 354 : CPLFree(pszContent);
3440 354 : if (bDPISet)
3441 : {
3442 297 : m_dfDPI *= dfScaleDPI;
3443 :
3444 297 : CPLDebug("PDF",
3445 : "DPI guessed from contents stream = %.16g",
3446 : m_dfDPI);
3447 297 : SetMetadataItem("DPI", CPLSPrintf("%.16g", m_dfDPI));
3448 297 : if (bResetTiles)
3449 0 : m_asTiles.resize(0);
3450 : }
3451 : else
3452 57 : m_asTiles.resize(0);
3453 : }
3454 : }
3455 : }
3456 :
3457 376 : GDALPDFObject *poUserUnit = nullptr;
3458 688 : if ((poUserUnit = poPageDict->Get("UserUnit")) != nullptr &&
3459 312 : (poUserUnit->GetType() == PDFObjectType_Int ||
3460 23 : poUserUnit->GetType() == PDFObjectType_Real))
3461 : {
3462 312 : m_dfDPI = ROUND_IF_CLOSE(Get(poUserUnit) * DEFAULT_DPI, 1e-5);
3463 312 : CPLDebug("PDF", "Found UserUnit in Page --> DPI = %.16g", m_dfDPI);
3464 312 : SetMetadataItem("DPI", CPLSPrintf("%.16g", m_dfDPI));
3465 : }
3466 : }
3467 :
3468 380 : if (m_dfDPI < 1e-2 || m_dfDPI > 7200)
3469 : {
3470 0 : CPLError(CE_Warning, CPLE_AppDefined,
3471 : "Invalid value for GDAL_PDF_DPI. Using default value instead");
3472 0 : m_dfDPI = GDAL_DEFAULT_DPI;
3473 : }
3474 380 : }
3475 :
3476 : /************************************************************************/
3477 : /* FindXMP() */
3478 : /************************************************************************/
3479 :
3480 0 : void PDFDataset::FindXMP(GDALPDFObject *poObj)
3481 : {
3482 0 : if (poObj->GetType() != PDFObjectType_Dictionary)
3483 0 : return;
3484 :
3485 0 : GDALPDFDictionary *poDict = poObj->GetDictionary();
3486 0 : GDALPDFObject *poType = poDict->Get("Type");
3487 0 : GDALPDFObject *poSubtype = poDict->Get("Subtype");
3488 0 : if (poType == nullptr || poType->GetType() != PDFObjectType_Name ||
3489 0 : poType->GetName() != "Metadata" || poSubtype == nullptr ||
3490 0 : poSubtype->GetType() != PDFObjectType_Name ||
3491 0 : poSubtype->GetName() != "XML")
3492 : {
3493 0 : return;
3494 : }
3495 :
3496 0 : GDALPDFStream *poStream = poObj->GetStream();
3497 0 : if (poStream == nullptr)
3498 0 : return;
3499 :
3500 0 : char *pszContent = poStream->GetBytes();
3501 0 : const auto nLength = poStream->GetLength();
3502 0 : if (pszContent != nullptr && nLength > 15 &&
3503 0 : STARTS_WITH(pszContent, "<?xpacket begin="))
3504 : {
3505 : char *apszMDList[2];
3506 0 : apszMDList[0] = pszContent;
3507 0 : apszMDList[1] = nullptr;
3508 0 : SetMetadata(apszMDList, "xml:XMP");
3509 : }
3510 0 : CPLFree(pszContent);
3511 : }
3512 :
3513 : /************************************************************************/
3514 : /* ParseInfo() */
3515 : /************************************************************************/
3516 :
3517 206 : void PDFDataset::ParseInfo(GDALPDFObject *poInfoObj)
3518 : {
3519 206 : if (poInfoObj->GetType() != PDFObjectType_Dictionary)
3520 136 : return;
3521 :
3522 70 : GDALPDFDictionary *poInfoObjDict = poInfoObj->GetDictionary();
3523 70 : GDALPDFObject *poItem = nullptr;
3524 70 : int bOneMDISet = FALSE;
3525 87 : if ((poItem = poInfoObjDict->Get("Author")) != nullptr &&
3526 17 : poItem->GetType() == PDFObjectType_String)
3527 : {
3528 17 : SetMetadataItem("AUTHOR", poItem->GetString().c_str());
3529 17 : bOneMDISet = TRUE;
3530 : }
3531 117 : if ((poItem = poInfoObjDict->Get("Creator")) != nullptr &&
3532 47 : poItem->GetType() == PDFObjectType_String)
3533 : {
3534 47 : SetMetadataItem("CREATOR", poItem->GetString().c_str());
3535 47 : bOneMDISet = TRUE;
3536 : }
3537 78 : if ((poItem = poInfoObjDict->Get("Keywords")) != nullptr &&
3538 8 : poItem->GetType() == PDFObjectType_String)
3539 : {
3540 8 : SetMetadataItem("KEYWORDS", poItem->GetString().c_str());
3541 8 : bOneMDISet = TRUE;
3542 : }
3543 81 : if ((poItem = poInfoObjDict->Get("Subject")) != nullptr &&
3544 11 : poItem->GetType() == PDFObjectType_String)
3545 : {
3546 11 : SetMetadataItem("SUBJECT", poItem->GetString().c_str());
3547 11 : bOneMDISet = TRUE;
3548 : }
3549 82 : if ((poItem = poInfoObjDict->Get("Title")) != nullptr &&
3550 12 : poItem->GetType() == PDFObjectType_String)
3551 : {
3552 12 : SetMetadataItem("TITLE", poItem->GetString().c_str());
3553 12 : bOneMDISet = TRUE;
3554 : }
3555 93 : if ((poItem = poInfoObjDict->Get("Producer")) != nullptr &&
3556 23 : poItem->GetType() == PDFObjectType_String)
3557 : {
3558 34 : if (bOneMDISet ||
3559 11 : poItem->GetString() != "PoDoFo - http://podofo.sf.net")
3560 : {
3561 12 : SetMetadataItem("PRODUCER", poItem->GetString().c_str());
3562 12 : bOneMDISet = TRUE;
3563 : }
3564 : }
3565 120 : if ((poItem = poInfoObjDict->Get("CreationDate")) != nullptr &&
3566 50 : poItem->GetType() == PDFObjectType_String)
3567 : {
3568 50 : if (bOneMDISet)
3569 39 : SetMetadataItem("CREATION_DATE", poItem->GetString().c_str());
3570 : }
3571 : }
3572 :
3573 : #if defined(HAVE_POPPLER) || defined(HAVE_PDFIUM)
3574 :
3575 : /************************************************************************/
3576 : /* AddLayer() */
3577 : /************************************************************************/
3578 :
3579 478 : void PDFDataset::AddLayer(const std::string &osName, int iPage)
3580 : {
3581 956 : LayerStruct layerStruct;
3582 478 : layerStruct.osName = osName;
3583 478 : layerStruct.nInsertIdx = static_cast<int>(m_oLayerNameSet.size());
3584 478 : layerStruct.iPage = iPage;
3585 478 : m_oLayerNameSet.emplace_back(std::move(layerStruct));
3586 478 : }
3587 :
3588 : /************************************************************************/
3589 : /* CreateLayerList() */
3590 : /************************************************************************/
3591 :
3592 251 : void PDFDataset::CreateLayerList()
3593 : {
3594 : // Sort layers by prioritizing page number and then insertion index
3595 251 : std::sort(m_oLayerNameSet.begin(), m_oLayerNameSet.end(),
3596 1954 : [](const LayerStruct &a, const LayerStruct &b)
3597 : {
3598 1954 : if (a.iPage < b.iPage)
3599 78 : return true;
3600 1876 : if (a.iPage > b.iPage)
3601 0 : return false;
3602 1876 : return a.nInsertIdx < b.nInsertIdx;
3603 : });
3604 :
3605 251 : if (m_oLayerNameSet.size() >= 100)
3606 : {
3607 199 : for (const auto &oLayerStruct : m_oLayerNameSet)
3608 : {
3609 : m_aosLayerNames.AddNameValue(
3610 : CPLSPrintf("LAYER_%03d_NAME", m_aosLayerNames.size()),
3611 198 : oLayerStruct.osName.c_str());
3612 : }
3613 : }
3614 : else
3615 : {
3616 530 : for (const auto &oLayerStruct : m_oLayerNameSet)
3617 : {
3618 : m_aosLayerNames.AddNameValue(
3619 : CPLSPrintf("LAYER_%02d_NAME", m_aosLayerNames.size()),
3620 280 : oLayerStruct.osName.c_str());
3621 : }
3622 : }
3623 251 : }
3624 :
3625 : /************************************************************************/
3626 : /* BuildPostfixedLayerNameAndAddLayer() */
3627 : /************************************************************************/
3628 :
3629 : /** Append a suffix with the page number(s) to the provided layer name, if
3630 : * it makes sense (that is if it is a multiple page PDF and we haven't selected
3631 : * a specific name). And also call AddLayer() on it if successful.
3632 : * If may return an empty string if the layer isn't used by the page of interest
3633 : */
3634 622 : std::string PDFDataset::BuildPostfixedLayerNameAndAddLayer(
3635 : const std::string &osName, const std::pair<int, int> &oOCGRef,
3636 : int iPageOfInterest, int nPageCount)
3637 : {
3638 1244 : std::string osPostfixedName = osName;
3639 622 : int iLayerPage = 0;
3640 622 : if (nPageCount > 1 && !m_oMapOCGNumGenToPages.empty())
3641 : {
3642 216 : const auto oIterToPages = m_oMapOCGNumGenToPages.find(oOCGRef);
3643 216 : if (oIterToPages != m_oMapOCGNumGenToPages.end())
3644 : {
3645 216 : const auto &anPages = oIterToPages->second;
3646 216 : if (iPageOfInterest > 0)
3647 : {
3648 192 : if (std::find(anPages.begin(), anPages.end(),
3649 192 : iPageOfInterest) == anPages.end())
3650 : {
3651 144 : return std::string();
3652 : }
3653 : }
3654 24 : else if (anPages.size() == 1)
3655 : {
3656 24 : iLayerPage = anPages.front();
3657 24 : osPostfixedName += CPLSPrintf(" (page %d)", anPages.front());
3658 : }
3659 : else
3660 : {
3661 0 : osPostfixedName += " (pages ";
3662 0 : for (size_t j = 0; j < anPages.size(); ++j)
3663 : {
3664 0 : if (j > 0)
3665 0 : osPostfixedName += ", ";
3666 0 : osPostfixedName += CPLSPrintf("%d", anPages[j]);
3667 : }
3668 0 : osPostfixedName += ')';
3669 : }
3670 : }
3671 : }
3672 :
3673 478 : AddLayer(osPostfixedName, iLayerPage);
3674 :
3675 478 : return osPostfixedName;
3676 : }
3677 :
3678 : #endif // defined(HAVE_POPPLER) || defined(HAVE_PDFIUM)
3679 :
3680 : #ifdef HAVE_POPPLER
3681 :
3682 : /************************************************************************/
3683 : /* ExploreLayersPoppler() */
3684 : /************************************************************************/
3685 :
3686 135 : void PDFDataset::ExploreLayersPoppler(GDALPDFArray *poArray,
3687 : int iPageOfInterest, int nPageCount,
3688 : CPLString osTopLayer, int nRecLevel,
3689 : int &nVisited, bool &bStop)
3690 : {
3691 135 : if (nRecLevel == 16 || nVisited == 1000)
3692 : {
3693 0 : CPLError(
3694 : CE_Failure, CPLE_AppDefined,
3695 : "ExploreLayersPoppler(): too deep exploration or too many items");
3696 0 : bStop = true;
3697 0 : return;
3698 : }
3699 135 : if (bStop)
3700 0 : return;
3701 :
3702 135 : int nLength = poArray->GetLength();
3703 135 : CPLString osCurLayer;
3704 414 : for (int i = 0; i < nLength; i++)
3705 : {
3706 279 : nVisited++;
3707 279 : GDALPDFObject *poObj = poArray->Get(i);
3708 279 : if (poObj == nullptr)
3709 0 : continue;
3710 279 : if (i == 0 && poObj->GetType() == PDFObjectType_String)
3711 : {
3712 : std::string osName =
3713 0 : PDFSanitizeLayerName(poObj->GetString().c_str());
3714 0 : if (!osTopLayer.empty())
3715 : {
3716 0 : osTopLayer += '.';
3717 0 : osTopLayer += osName;
3718 : }
3719 : else
3720 0 : osTopLayer = std::move(osName);
3721 0 : AddLayer(osTopLayer, 0);
3722 0 : m_oLayerOCGListPoppler.push_back(std::pair(osTopLayer, nullptr));
3723 : }
3724 279 : else if (poObj->GetType() == PDFObjectType_Array)
3725 : {
3726 97 : ExploreLayersPoppler(poObj->GetArray(), iPageOfInterest, nPageCount,
3727 : osCurLayer, nRecLevel + 1, nVisited, bStop);
3728 97 : if (bStop)
3729 0 : return;
3730 97 : osCurLayer = "";
3731 : }
3732 182 : else if (poObj->GetType() == PDFObjectType_Dictionary)
3733 : {
3734 182 : GDALPDFDictionary *poDict = poObj->GetDictionary();
3735 182 : GDALPDFObject *poName = poDict->Get("Name");
3736 182 : if (poName != nullptr && poName->GetType() == PDFObjectType_String)
3737 : {
3738 : std::string osName =
3739 182 : PDFSanitizeLayerName(poName->GetString().c_str());
3740 : /* coverity[copy_paste_error] */
3741 182 : if (!osTopLayer.empty())
3742 : {
3743 103 : osCurLayer = osTopLayer;
3744 103 : osCurLayer += '.';
3745 103 : osCurLayer += osName;
3746 : }
3747 : else
3748 79 : osCurLayer = std::move(osName);
3749 : // CPLDebug("PDF", "Layer %s", osCurLayer.c_str());
3750 :
3751 : #if POPPLER_MAJOR_VERSION > 25 || \
3752 : (POPPLER_MAJOR_VERSION == 25 && POPPLER_MINOR_VERSION >= 2)
3753 : const
3754 : #endif
3755 : OCGs *optContentConfig =
3756 182 : m_poDocPoppler->getOptContentConfig();
3757 : struct Ref r;
3758 182 : r.num = poObj->GetRefNum().toInt();
3759 182 : r.gen = poObj->GetRefGen();
3760 182 : OptionalContentGroup *ocg = optContentConfig->findOcgByRef(r);
3761 182 : if (ocg)
3762 : {
3763 182 : const auto oRefPair = std::pair(poObj->GetRefNum().toInt(),
3764 364 : poObj->GetRefGen());
3765 : const std::string osPostfixedName =
3766 : BuildPostfixedLayerNameAndAddLayer(
3767 182 : osCurLayer, oRefPair, iPageOfInterest, nPageCount);
3768 182 : if (osPostfixedName.empty())
3769 72 : continue;
3770 :
3771 110 : m_oLayerOCGListPoppler.push_back(
3772 220 : std::make_pair(osPostfixedName, ocg));
3773 110 : m_aoLayerWithRef.emplace_back(osPostfixedName.c_str(),
3774 220 : poObj->GetRefNum(), r.gen);
3775 : }
3776 : }
3777 : }
3778 : }
3779 : }
3780 :
3781 : /************************************************************************/
3782 : /* FindLayersPoppler() */
3783 : /************************************************************************/
3784 :
3785 167 : void PDFDataset::FindLayersPoppler(int iPageOfInterest)
3786 : {
3787 167 : int nPageCount = 0;
3788 167 : const auto poPages = GetPagesKids();
3789 167 : if (poPages)
3790 167 : nPageCount = poPages->GetLength();
3791 :
3792 : #if POPPLER_MAJOR_VERSION > 25 || \
3793 : (POPPLER_MAJOR_VERSION == 25 && POPPLER_MINOR_VERSION >= 2)
3794 : const
3795 : #endif
3796 167 : OCGs *optContentConfig = m_poDocPoppler->getOptContentConfig();
3797 167 : if (optContentConfig == nullptr || !optContentConfig->isOk())
3798 129 : return;
3799 :
3800 : #if POPPLER_MAJOR_VERSION > 25 || \
3801 : (POPPLER_MAJOR_VERSION == 25 && POPPLER_MINOR_VERSION >= 2)
3802 : const
3803 : #endif
3804 38 : Array *array = optContentConfig->getOrderArray();
3805 38 : if (array)
3806 : {
3807 38 : GDALPDFArray *poArray = GDALPDFCreateArray(array);
3808 38 : int nVisited = 0;
3809 38 : bool bStop = false;
3810 38 : ExploreLayersPoppler(poArray, iPageOfInterest, nPageCount, CPLString(),
3811 : 0, nVisited, bStop);
3812 38 : delete poArray;
3813 : }
3814 : else
3815 : {
3816 0 : for (const auto &refOCGPair : optContentConfig->getOCGs())
3817 : {
3818 0 : auto ocg = refOCGPair.second.get();
3819 0 : if (ocg != nullptr && ocg->getName() != nullptr)
3820 : {
3821 : const char *pszLayerName =
3822 0 : reinterpret_cast<const char *>(ocg->getName()->c_str());
3823 0 : AddLayer(pszLayerName, 0);
3824 0 : m_oLayerOCGListPoppler.push_back(
3825 0 : std::make_pair(CPLString(pszLayerName), ocg));
3826 : }
3827 : }
3828 : }
3829 :
3830 38 : CreateLayerList();
3831 38 : m_oMDMD_PDF.SetMetadata(m_aosLayerNames.List(), "LAYERS");
3832 : }
3833 :
3834 : /************************************************************************/
3835 : /* TurnLayersOnOffPoppler() */
3836 : /************************************************************************/
3837 :
3838 167 : void PDFDataset::TurnLayersOnOffPoppler()
3839 : {
3840 : #if POPPLER_MAJOR_VERSION > 25 || \
3841 : (POPPLER_MAJOR_VERSION == 25 && POPPLER_MINOR_VERSION >= 2)
3842 : const
3843 : #endif
3844 167 : OCGs *optContentConfig = m_poDocPoppler->getOptContentConfig();
3845 167 : if (optContentConfig == nullptr || !optContentConfig->isOk())
3846 129 : return;
3847 :
3848 : // Which layers to turn ON ?
3849 38 : const char *pszLayers = GetOption(papszOpenOptions, "LAYERS", nullptr);
3850 38 : if (pszLayers)
3851 : {
3852 : int i;
3853 2 : int bAll = EQUAL(pszLayers, "ALL");
3854 12 : for (const auto &refOCGPair : optContentConfig->getOCGs())
3855 : {
3856 10 : auto ocg = refOCGPair.second.get();
3857 10 : ocg->setState((bAll) ? OptionalContentGroup::On
3858 : : OptionalContentGroup::Off);
3859 : }
3860 :
3861 2 : char **papszLayers = CSLTokenizeString2(pszLayers, ",", 0);
3862 4 : for (i = 0; !bAll && papszLayers[i] != nullptr; i++)
3863 : {
3864 2 : bool isFound = false;
3865 12 : for (auto oIter2 = m_oLayerOCGListPoppler.begin();
3866 22 : oIter2 != m_oLayerOCGListPoppler.end(); ++oIter2)
3867 : {
3868 10 : if (oIter2->first != papszLayers[i])
3869 8 : continue;
3870 :
3871 2 : isFound = true;
3872 2 : auto oIter = oIter2;
3873 2 : if (oIter->second)
3874 : {
3875 : // CPLDebug("PDF", "Turn '%s' on", papszLayers[i]);
3876 2 : oIter->second->setState(OptionalContentGroup::On);
3877 : }
3878 :
3879 : // Turn child layers on, unless there's one of them explicitly
3880 : // listed in the list.
3881 2 : size_t nLen = strlen(papszLayers[i]);
3882 2 : int bFoundChildLayer = FALSE;
3883 2 : oIter = m_oLayerOCGListPoppler.begin();
3884 10 : for (;
3885 12 : oIter != m_oLayerOCGListPoppler.end() && !bFoundChildLayer;
3886 10 : ++oIter)
3887 : {
3888 10 : if (oIter->first.size() > nLen &&
3889 5 : strncmp(oIter->first.c_str(), papszLayers[i], nLen) ==
3890 15 : 0 &&
3891 2 : oIter->first[nLen] == '.')
3892 : {
3893 4 : for (int j = 0; papszLayers[j] != nullptr; j++)
3894 : {
3895 2 : if (strcmp(papszLayers[j], oIter->first.c_str()) ==
3896 : 0)
3897 : {
3898 0 : bFoundChildLayer = TRUE;
3899 0 : break;
3900 : }
3901 : }
3902 : }
3903 : }
3904 :
3905 2 : if (!bFoundChildLayer)
3906 : {
3907 2 : oIter = m_oLayerOCGListPoppler.begin();
3908 12 : for (; oIter != m_oLayerOCGListPoppler.end() &&
3909 : !bFoundChildLayer;
3910 10 : ++oIter)
3911 : {
3912 10 : if (oIter->first.size() > nLen &&
3913 5 : strncmp(oIter->first.c_str(), papszLayers[i],
3914 15 : nLen) == 0 &&
3915 2 : oIter->first[nLen] == '.')
3916 : {
3917 2 : if (oIter->second)
3918 : {
3919 : // CPLDebug("PDF", "Turn '%s' on too",
3920 : // oIter->first.c_str());
3921 2 : oIter->second->setState(
3922 : OptionalContentGroup::On);
3923 : }
3924 : }
3925 : }
3926 : }
3927 :
3928 : // Turn parent layers on too
3929 6 : std::string layer(papszLayers[i]);
3930 : std::string::size_type j;
3931 3 : while ((j = layer.find_last_of('.')) != std::string::npos)
3932 : {
3933 1 : layer.resize(j);
3934 1 : oIter = m_oLayerOCGListPoppler.begin();
3935 6 : for (; oIter != m_oLayerOCGListPoppler.end(); ++oIter)
3936 : {
3937 5 : if (oIter->first == layer && oIter->second)
3938 : {
3939 : // CPLDebug("PDF", "Turn '%s' on too",
3940 : // layer.c_str());
3941 1 : oIter->second->setState(OptionalContentGroup::On);
3942 : }
3943 : }
3944 : }
3945 : }
3946 2 : if (!isFound)
3947 : {
3948 0 : CPLError(CE_Warning, CPLE_AppDefined, "Unknown layer '%s'",
3949 0 : papszLayers[i]);
3950 : }
3951 : }
3952 2 : CSLDestroy(papszLayers);
3953 :
3954 2 : m_bUseOCG = true;
3955 : }
3956 :
3957 : // Which layers to turn OFF ?
3958 : const char *pszLayersOFF =
3959 38 : GetOption(papszOpenOptions, "LAYERS_OFF", nullptr);
3960 38 : if (pszLayersOFF)
3961 : {
3962 5 : char **papszLayersOFF = CSLTokenizeString2(pszLayersOFF, ",", 0);
3963 10 : for (int i = 0; papszLayersOFF[i] != nullptr; i++)
3964 : {
3965 5 : bool isFound = false;
3966 22 : for (auto oIter2 = m_oLayerOCGListPoppler.begin();
3967 39 : oIter2 != m_oLayerOCGListPoppler.end(); ++oIter2)
3968 : {
3969 17 : if (oIter2->first != papszLayersOFF[i])
3970 12 : continue;
3971 :
3972 5 : isFound = true;
3973 5 : auto oIter = oIter2;
3974 5 : if (oIter->second)
3975 : {
3976 : // CPLDebug("PDF", "Turn '%s' off", papszLayersOFF[i]);
3977 5 : oIter->second->setState(OptionalContentGroup::Off);
3978 : }
3979 :
3980 : // Turn child layers off too
3981 5 : size_t nLen = strlen(papszLayersOFF[i]);
3982 5 : oIter = m_oLayerOCGListPoppler.begin();
3983 22 : for (; oIter != m_oLayerOCGListPoppler.end(); ++oIter)
3984 : {
3985 17 : if (oIter->first.size() > nLen &&
3986 3 : strncmp(oIter->first.c_str(), papszLayersOFF[i],
3987 20 : nLen) == 0 &&
3988 1 : oIter->first[nLen] == '.')
3989 : {
3990 1 : if (oIter->second)
3991 : {
3992 : // CPLDebug("PDF", "Turn '%s' off too",
3993 : // oIter->first.c_str());
3994 1 : oIter->second->setState(OptionalContentGroup::Off);
3995 : }
3996 : }
3997 : }
3998 : }
3999 5 : if (!isFound)
4000 : {
4001 0 : CPLError(CE_Warning, CPLE_AppDefined, "Unknown layer '%s'",
4002 0 : papszLayersOFF[i]);
4003 : }
4004 : }
4005 5 : CSLDestroy(papszLayersOFF);
4006 :
4007 5 : m_bUseOCG = true;
4008 : }
4009 : }
4010 :
4011 : #endif
4012 :
4013 : #ifdef HAVE_PDFIUM
4014 :
4015 : /************************************************************************/
4016 : /* ExploreLayersPdfium() */
4017 : /************************************************************************/
4018 :
4019 215 : void PDFDataset::ExploreLayersPdfium(GDALPDFArray *poArray, int iPageOfInterest,
4020 : int nPageCount, int nRecLevel,
4021 : CPLString osTopLayer)
4022 : {
4023 215 : if (nRecLevel == 16)
4024 0 : return;
4025 :
4026 215 : const int nLength = poArray->GetLength();
4027 430 : std::string osCurLayer;
4028 807 : for (int i = 0; i < nLength; i++)
4029 : {
4030 592 : GDALPDFObject *poObj = poArray->Get(i);
4031 592 : if (poObj == nullptr)
4032 0 : continue;
4033 592 : if (i == 0 && poObj->GetType() == PDFObjectType_String)
4034 : {
4035 : const std::string osName =
4036 0 : PDFSanitizeLayerName(poObj->GetString().c_str());
4037 0 : if (!osTopLayer.empty())
4038 0 : osTopLayer = std::string(osTopLayer).append(".").append(osName);
4039 : else
4040 0 : osTopLayer = osName;
4041 0 : AddLayer(osTopLayer, 0);
4042 0 : m_oMapLayerNameToOCGNumGenPdfium[osTopLayer] = std::pair(-1, -1);
4043 : }
4044 592 : else if (poObj->GetType() == PDFObjectType_Array)
4045 : {
4046 152 : ExploreLayersPdfium(poObj->GetArray(), iPageOfInterest, nPageCount,
4047 : nRecLevel + 1, osCurLayer);
4048 152 : osCurLayer.clear();
4049 : }
4050 440 : else if (poObj->GetType() == PDFObjectType_Dictionary)
4051 : {
4052 440 : GDALPDFDictionary *poDict = poObj->GetDictionary();
4053 440 : GDALPDFObject *poName = poDict->Get("Name");
4054 440 : if (poName != nullptr && poName->GetType() == PDFObjectType_String)
4055 : {
4056 : std::string osName =
4057 440 : PDFSanitizeLayerName(poName->GetString().c_str());
4058 : // coverity[copy_paste_error]
4059 440 : if (!osTopLayer.empty())
4060 : {
4061 : osCurLayer =
4062 310 : std::string(osTopLayer).append(".").append(osName);
4063 : }
4064 : else
4065 130 : osCurLayer = std::move(osName);
4066 : // CPLDebug("PDF", "Layer %s", osCurLayer.c_str());
4067 :
4068 : const auto oRefPair =
4069 440 : std::pair(poObj->GetRefNum().toInt(), poObj->GetRefGen());
4070 : const std::string osPostfixedName =
4071 : BuildPostfixedLayerNameAndAddLayer(
4072 440 : osCurLayer, oRefPair, iPageOfInterest, nPageCount);
4073 440 : if (osPostfixedName.empty())
4074 72 : continue;
4075 :
4076 : m_aoLayerWithRef.emplace_back(
4077 368 : osPostfixedName, poObj->GetRefNum(), poObj->GetRefGen());
4078 368 : m_oMapLayerNameToOCGNumGenPdfium[osPostfixedName] = oRefPair;
4079 : }
4080 : }
4081 : }
4082 : }
4083 :
4084 : /************************************************************************/
4085 : /* FindLayersPdfium() */
4086 : /************************************************************************/
4087 :
4088 213 : void PDFDataset::FindLayersPdfium(int iPageOfInterest)
4089 : {
4090 213 : int nPageCount = 0;
4091 213 : const auto poPages = GetPagesKids();
4092 213 : if (poPages)
4093 213 : nPageCount = poPages->GetLength();
4094 :
4095 213 : GDALPDFObject *poCatalog = GetCatalog();
4096 426 : if (poCatalog == nullptr ||
4097 213 : poCatalog->GetType() != PDFObjectType_Dictionary)
4098 0 : return;
4099 213 : GDALPDFObject *poOrder = poCatalog->LookupObject("OCProperties.D.Order");
4100 213 : if (poOrder != nullptr && poOrder->GetType() == PDFObjectType_Array)
4101 : {
4102 63 : ExploreLayersPdfium(poOrder->GetArray(), iPageOfInterest, nPageCount,
4103 : 0);
4104 : }
4105 : #if 0
4106 : else
4107 : {
4108 : GDALPDFObject* poOCGs = poD->GetDictionary()->Get("OCGs");
4109 : if( poOCGs != nullptr && poOCGs->GetType() == PDFObjectType_Array )
4110 : {
4111 : GDALPDFArray* poArray = poOCGs->GetArray();
4112 : int nLength = poArray->GetLength();
4113 : for(int i=0;i<nLength;i++)
4114 : {
4115 : GDALPDFObject* poObj = poArray->Get(i);
4116 : if( poObj != nullptr )
4117 : {
4118 : // TODO ?
4119 : }
4120 : }
4121 : }
4122 : }
4123 : #endif
4124 :
4125 213 : CreateLayerList();
4126 213 : m_oMDMD_PDF.SetMetadata(m_aosLayerNames.List(), "LAYERS");
4127 : }
4128 :
4129 : /************************************************************************/
4130 : /* TurnLayersOnOffPdfium() */
4131 : /************************************************************************/
4132 :
4133 213 : void PDFDataset::TurnLayersOnOffPdfium()
4134 : {
4135 213 : GDALPDFObject *poCatalog = GetCatalog();
4136 426 : if (poCatalog == nullptr ||
4137 213 : poCatalog->GetType() != PDFObjectType_Dictionary)
4138 0 : return;
4139 213 : GDALPDFObject *poOCGs = poCatalog->LookupObject("OCProperties.OCGs");
4140 213 : if (poOCGs == nullptr || poOCGs->GetType() != PDFObjectType_Array)
4141 150 : return;
4142 :
4143 : // Which layers to turn ON ?
4144 63 : const char *pszLayers = GetOption(papszOpenOptions, "LAYERS", nullptr);
4145 63 : if (pszLayers)
4146 : {
4147 : int i;
4148 2 : int bAll = EQUAL(pszLayers, "ALL");
4149 :
4150 2 : GDALPDFArray *poOCGsArray = poOCGs->GetArray();
4151 2 : int nLength = poOCGsArray->GetLength();
4152 12 : for (i = 0; i < nLength; i++)
4153 : {
4154 10 : GDALPDFObject *poOCG = poOCGsArray->Get(i);
4155 0 : m_oMapOCGNumGenToVisibilityStatePdfium[std::pair(
4156 10 : poOCG->GetRefNum().toInt(), poOCG->GetRefGen())] =
4157 10 : (bAll) ? VISIBILITY_ON : VISIBILITY_OFF;
4158 : }
4159 :
4160 2 : char **papszLayers = CSLTokenizeString2(pszLayers, ",", 0);
4161 4 : for (i = 0; !bAll && papszLayers[i] != nullptr; i++)
4162 : {
4163 2 : auto oIter = m_oMapLayerNameToOCGNumGenPdfium.find(papszLayers[i]);
4164 2 : if (oIter != m_oMapLayerNameToOCGNumGenPdfium.end())
4165 : {
4166 2 : if (oIter->second.first >= 0)
4167 : {
4168 : // CPLDebug("PDF", "Turn '%s' on", papszLayers[i]);
4169 2 : m_oMapOCGNumGenToVisibilityStatePdfium[oIter->second] =
4170 : VISIBILITY_ON;
4171 : }
4172 :
4173 : // Turn child layers on, unless there's one of them explicitly
4174 : // listed in the list.
4175 2 : size_t nLen = strlen(papszLayers[i]);
4176 2 : int bFoundChildLayer = FALSE;
4177 2 : oIter = m_oMapLayerNameToOCGNumGenPdfium.begin();
4178 12 : for (; oIter != m_oMapLayerNameToOCGNumGenPdfium.end() &&
4179 : !bFoundChildLayer;
4180 10 : oIter++)
4181 : {
4182 10 : if (oIter->first.size() > nLen &&
4183 5 : strncmp(oIter->first.c_str(), papszLayers[i], nLen) ==
4184 15 : 0 &&
4185 2 : oIter->first[nLen] == '.')
4186 : {
4187 4 : for (int j = 0; papszLayers[j] != nullptr; j++)
4188 : {
4189 2 : if (strcmp(papszLayers[j], oIter->first.c_str()) ==
4190 : 0)
4191 0 : bFoundChildLayer = TRUE;
4192 : }
4193 : }
4194 : }
4195 :
4196 2 : if (!bFoundChildLayer)
4197 : {
4198 2 : oIter = m_oMapLayerNameToOCGNumGenPdfium.begin();
4199 12 : for (; oIter != m_oMapLayerNameToOCGNumGenPdfium.end() &&
4200 : !bFoundChildLayer;
4201 10 : oIter++)
4202 : {
4203 10 : if (oIter->first.size() > nLen &&
4204 5 : strncmp(oIter->first.c_str(), papszLayers[i],
4205 15 : nLen) == 0 &&
4206 2 : oIter->first[nLen] == '.')
4207 : {
4208 2 : if (oIter->second.first >= 0)
4209 : {
4210 : // CPLDebug("PDF", "Turn '%s' on too",
4211 : // oIter->first.c_str());
4212 : m_oMapOCGNumGenToVisibilityStatePdfium
4213 2 : [oIter->second] = VISIBILITY_ON;
4214 : }
4215 : }
4216 : }
4217 : }
4218 :
4219 : // Turn parent layers on too
4220 2 : char *pszLastDot = nullptr;
4221 3 : while ((pszLastDot = strrchr(papszLayers[i], '.')) != nullptr)
4222 : {
4223 1 : *pszLastDot = '\0';
4224 : oIter =
4225 1 : m_oMapLayerNameToOCGNumGenPdfium.find(papszLayers[i]);
4226 1 : if (oIter != m_oMapLayerNameToOCGNumGenPdfium.end())
4227 : {
4228 1 : if (oIter->second.first >= 0)
4229 : {
4230 : // CPLDebug("PDF", "Turn '%s' on too",
4231 : // papszLayers[i]);
4232 : m_oMapOCGNumGenToVisibilityStatePdfium
4233 1 : [oIter->second] = VISIBILITY_ON;
4234 : }
4235 : }
4236 : }
4237 : }
4238 : else
4239 : {
4240 0 : CPLError(CE_Warning, CPLE_AppDefined, "Unknown layer '%s'",
4241 0 : papszLayers[i]);
4242 : }
4243 : }
4244 2 : CSLDestroy(papszLayers);
4245 :
4246 2 : m_bUseOCG = true;
4247 : }
4248 :
4249 : // Which layers to turn OFF ?
4250 : const char *pszLayersOFF =
4251 63 : GetOption(papszOpenOptions, "LAYERS_OFF", nullptr);
4252 63 : if (pszLayersOFF)
4253 : {
4254 5 : char **papszLayersOFF = CSLTokenizeString2(pszLayersOFF, ",", 0);
4255 10 : for (int i = 0; papszLayersOFF[i] != nullptr; i++)
4256 : {
4257 : auto oIter =
4258 5 : m_oMapLayerNameToOCGNumGenPdfium.find(papszLayersOFF[i]);
4259 5 : if (oIter != m_oMapLayerNameToOCGNumGenPdfium.end())
4260 : {
4261 5 : if (oIter->second.first >= 0)
4262 : {
4263 : // CPLDebug("PDF", "Turn '%s' (%d,%d) off",
4264 : // papszLayersOFF[i], oIter->second.first,
4265 : // oIter->second.second);
4266 5 : m_oMapOCGNumGenToVisibilityStatePdfium[oIter->second] =
4267 : VISIBILITY_OFF;
4268 : }
4269 :
4270 : // Turn child layers off too
4271 5 : size_t nLen = strlen(papszLayersOFF[i]);
4272 5 : oIter = m_oMapLayerNameToOCGNumGenPdfium.begin();
4273 22 : for (; oIter != m_oMapLayerNameToOCGNumGenPdfium.end(); oIter++)
4274 : {
4275 17 : if (oIter->first.size() > nLen &&
4276 3 : strncmp(oIter->first.c_str(), papszLayersOFF[i],
4277 20 : nLen) == 0 &&
4278 1 : oIter->first[nLen] == '.')
4279 : {
4280 1 : if (oIter->second.first >= 0)
4281 : {
4282 : // CPLDebug("PDF", "Turn '%s' off too",
4283 : // oIter->first.c_str());
4284 : m_oMapOCGNumGenToVisibilityStatePdfium
4285 1 : [oIter->second] = VISIBILITY_OFF;
4286 : }
4287 : }
4288 : }
4289 : }
4290 : else
4291 : {
4292 0 : CPLError(CE_Warning, CPLE_AppDefined, "Unknown layer '%s'",
4293 0 : papszLayersOFF[i]);
4294 : }
4295 : }
4296 5 : CSLDestroy(papszLayersOFF);
4297 :
4298 5 : m_bUseOCG = true;
4299 : }
4300 : }
4301 :
4302 : /************************************************************************/
4303 : /* GetVisibilityStateForOGCPdfium() */
4304 : /************************************************************************/
4305 :
4306 12996 : PDFDataset::VisibilityState PDFDataset::GetVisibilityStateForOGCPdfium(int nNum,
4307 : int nGen)
4308 : {
4309 : auto oIter =
4310 12996 : m_oMapOCGNumGenToVisibilityStatePdfium.find(std::pair(nNum, nGen));
4311 12996 : if (oIter == m_oMapOCGNumGenToVisibilityStatePdfium.end())
4312 8703 : return VISIBILITY_DEFAULT;
4313 4293 : return oIter->second;
4314 : }
4315 :
4316 : #endif /* HAVE_PDFIUM */
4317 :
4318 : /************************************************************************/
4319 : /* GetPagesKids() */
4320 : /************************************************************************/
4321 :
4322 760 : GDALPDFArray *PDFDataset::GetPagesKids()
4323 : {
4324 760 : const auto poCatalog = GetCatalog();
4325 760 : if (!poCatalog || poCatalog->GetType() != PDFObjectType_Dictionary)
4326 : {
4327 0 : return nullptr;
4328 : }
4329 760 : const auto poKids = poCatalog->LookupObject("Pages.Kids");
4330 760 : if (!poKids || poKids->GetType() != PDFObjectType_Array)
4331 : {
4332 0 : return nullptr;
4333 : }
4334 760 : return poKids->GetArray();
4335 : }
4336 :
4337 : /************************************************************************/
4338 : /* MapOCGsToPages() */
4339 : /************************************************************************/
4340 :
4341 380 : void PDFDataset::MapOCGsToPages()
4342 : {
4343 380 : const auto poKidsArray = GetPagesKids();
4344 380 : if (!poKidsArray)
4345 : {
4346 0 : return;
4347 : }
4348 380 : const int nKidsArrayLength = poKidsArray->GetLength();
4349 824 : for (int iPage = 0; iPage < nKidsArrayLength; ++iPage)
4350 : {
4351 444 : const auto poPage = poKidsArray->Get(iPage);
4352 444 : if (poPage && poPage->GetType() == PDFObjectType_Dictionary)
4353 : {
4354 444 : const auto poXObject = poPage->LookupObject("Resources.XObject");
4355 444 : if (poXObject && poXObject->GetType() == PDFObjectType_Dictionary)
4356 : {
4357 959 : for (const auto &oNameObjectPair :
4358 2342 : poXObject->GetDictionary()->GetValues())
4359 : {
4360 : const auto poProperties =
4361 959 : oNameObjectPair.second->LookupObject(
4362 : "Resources.Properties");
4363 1032 : if (poProperties &&
4364 73 : poProperties->GetType() == PDFObjectType_Dictionary)
4365 : {
4366 : const auto &oMap =
4367 73 : poProperties->GetDictionary()->GetValues();
4368 426 : for (const auto &[osKey, poObj] : oMap)
4369 : {
4370 706 : if (poObj->GetRefNum().toBool() &&
4371 353 : poObj->GetType() == PDFObjectType_Dictionary)
4372 : {
4373 : GDALPDFObject *poType =
4374 353 : poObj->GetDictionary()->Get("Type");
4375 : GDALPDFObject *poName =
4376 353 : poObj->GetDictionary()->Get("Name");
4377 706 : if (poType &&
4378 706 : poType->GetType() == PDFObjectType_Name &&
4379 1412 : poType->GetName() == "OCG" && poName &&
4380 353 : poName->GetType() == PDFObjectType_String)
4381 : {
4382 : m_oMapOCGNumGenToPages
4383 353 : [std::pair(poObj->GetRefNum().toInt(),
4384 706 : poObj->GetRefGen())]
4385 353 : .push_back(iPage + 1);
4386 : }
4387 : }
4388 : }
4389 : }
4390 : }
4391 : }
4392 : }
4393 : }
4394 : }
4395 :
4396 : /************************************************************************/
4397 : /* FindLayerOCG() */
4398 : /************************************************************************/
4399 :
4400 354 : CPLString PDFDataset::FindLayerOCG(GDALPDFDictionary *poPageDict,
4401 : const char *pszLayerName)
4402 : {
4403 : GDALPDFObject *poProperties =
4404 354 : poPageDict->LookupObject("Resources.Properties");
4405 420 : if (poProperties != nullptr &&
4406 66 : poProperties->GetType() == PDFObjectType_Dictionary)
4407 : {
4408 66 : const auto &oMap = poProperties->GetDictionary()->GetValues();
4409 187 : for (const auto &[osKey, poObj] : oMap)
4410 : {
4411 241 : if (poObj->GetRefNum().toBool() &&
4412 120 : poObj->GetType() == PDFObjectType_Dictionary)
4413 : {
4414 120 : GDALPDFObject *poType = poObj->GetDictionary()->Get("Type");
4415 120 : GDALPDFObject *poName = poObj->GetDictionary()->Get("Name");
4416 240 : if (poType != nullptr &&
4417 240 : poType->GetType() == PDFObjectType_Name &&
4418 480 : poType->GetName() == "OCG" && poName != nullptr &&
4419 120 : poName->GetType() == PDFObjectType_String)
4420 : {
4421 120 : if (poName->GetString() == pszLayerName)
4422 0 : return osKey;
4423 : }
4424 : }
4425 : }
4426 : }
4427 354 : return "";
4428 : }
4429 :
4430 : /************************************************************************/
4431 : /* FindLayersGeneric() */
4432 : /************************************************************************/
4433 :
4434 0 : void PDFDataset::FindLayersGeneric(GDALPDFDictionary *poPageDict)
4435 : {
4436 : GDALPDFObject *poProperties =
4437 0 : poPageDict->LookupObject("Resources.Properties");
4438 0 : if (poProperties != nullptr &&
4439 0 : poProperties->GetType() == PDFObjectType_Dictionary)
4440 : {
4441 0 : const auto &oMap = poProperties->GetDictionary()->GetValues();
4442 0 : for (const auto &[osKey, poObj] : oMap)
4443 : {
4444 0 : if (poObj->GetRefNum().toBool() &&
4445 0 : poObj->GetType() == PDFObjectType_Dictionary)
4446 : {
4447 0 : GDALPDFObject *poType = poObj->GetDictionary()->Get("Type");
4448 0 : GDALPDFObject *poName = poObj->GetDictionary()->Get("Name");
4449 0 : if (poType != nullptr &&
4450 0 : poType->GetType() == PDFObjectType_Name &&
4451 0 : poType->GetName() == "OCG" && poName != nullptr &&
4452 0 : poName->GetType() == PDFObjectType_String)
4453 : {
4454 : m_aoLayerWithRef.emplace_back(
4455 0 : PDFSanitizeLayerName(poName->GetString().c_str())
4456 0 : .c_str(),
4457 0 : poObj->GetRefNum(), poObj->GetRefGen());
4458 : }
4459 : }
4460 : }
4461 : }
4462 0 : }
4463 :
4464 : /************************************************************************/
4465 : /* Open() */
4466 : /************************************************************************/
4467 :
4468 402 : PDFDataset *PDFDataset::Open(GDALOpenInfo *poOpenInfo)
4469 :
4470 : {
4471 402 : if (!PDFDatasetIdentify(poOpenInfo))
4472 2 : return nullptr;
4473 :
4474 : const char *pszUserPwd =
4475 400 : GetOption(poOpenInfo->papszOpenOptions, "USER_PWD", nullptr);
4476 :
4477 400 : const bool bOpenSubdataset = STARTS_WITH(poOpenInfo->pszFilename, "PDF:");
4478 400 : const bool bOpenSubdatasetImage =
4479 400 : STARTS_WITH(poOpenInfo->pszFilename, "PDF_IMAGE:");
4480 400 : int iPage = -1;
4481 400 : int nImageNum = -1;
4482 800 : std::string osSubdatasetName;
4483 400 : const char *pszFilename = poOpenInfo->pszFilename;
4484 :
4485 400 : if (bOpenSubdataset)
4486 : {
4487 30 : iPage = atoi(pszFilename + 4);
4488 30 : if (iPage <= 0)
4489 2 : return nullptr;
4490 28 : pszFilename = strchr(pszFilename + 4, ':');
4491 28 : if (pszFilename == nullptr)
4492 0 : return nullptr;
4493 28 : pszFilename++;
4494 28 : osSubdatasetName = CPLSPrintf("Page %d", iPage);
4495 : }
4496 370 : else if (bOpenSubdatasetImage)
4497 : {
4498 0 : iPage = atoi(pszFilename + 10);
4499 0 : if (iPage <= 0)
4500 0 : return nullptr;
4501 0 : const char *pszNext = strchr(pszFilename + 10, ':');
4502 0 : if (pszNext == nullptr)
4503 0 : return nullptr;
4504 0 : nImageNum = atoi(pszNext + 1);
4505 0 : if (nImageNum <= 0)
4506 0 : return nullptr;
4507 0 : pszFilename = strchr(pszNext + 1, ':');
4508 0 : if (pszFilename == nullptr)
4509 0 : return nullptr;
4510 0 : pszFilename++;
4511 0 : osSubdatasetName = CPLSPrintf("Image %d", nImageNum);
4512 : }
4513 : else
4514 370 : iPage = 1;
4515 :
4516 398 : std::bitset<PDFLIB_COUNT> bHasLib;
4517 398 : bHasLib.reset();
4518 : // Each library set their flag
4519 : #if defined(HAVE_POPPLER)
4520 398 : bHasLib.set(PDFLIB_POPPLER);
4521 : #endif // HAVE_POPPLER
4522 : #if defined(HAVE_PODOFO)
4523 : bHasLib.set(PDFLIB_PODOFO);
4524 : #endif // HAVE_PODOFO
4525 : #if defined(HAVE_PDFIUM)
4526 398 : bHasLib.set(PDFLIB_PDFIUM);
4527 : #endif // HAVE_PDFIUM
4528 :
4529 398 : std::bitset<PDFLIB_COUNT> bUseLib;
4530 :
4531 : // More than one library available
4532 : // Detect which one
4533 398 : if (bHasLib.count() != 1)
4534 : {
4535 398 : const char *pszDefaultLib = bHasLib.test(PDFLIB_PDFIUM) ? "PDFIUM"
4536 0 : : bHasLib.test(PDFLIB_POPPLER) ? "POPPLER"
4537 398 : : "PODOFO";
4538 : const char *pszPDFLib =
4539 398 : GetOption(poOpenInfo->papszOpenOptions, "PDF_LIB", pszDefaultLib);
4540 : while (true)
4541 : {
4542 398 : if (EQUAL(pszPDFLib, "POPPLER"))
4543 171 : bUseLib.set(PDFLIB_POPPLER);
4544 227 : else if (EQUAL(pszPDFLib, "PODOFO"))
4545 0 : bUseLib.set(PDFLIB_PODOFO);
4546 227 : else if (EQUAL(pszPDFLib, "PDFIUM"))
4547 227 : bUseLib.set(PDFLIB_PDFIUM);
4548 :
4549 398 : if (bUseLib.count() != 1 || (bHasLib & bUseLib) == 0)
4550 : {
4551 0 : CPLDebug("PDF",
4552 : "Invalid value for GDAL_PDF_LIB config option: %s. "
4553 : "Fallback to %s",
4554 : pszPDFLib, pszDefaultLib);
4555 0 : pszPDFLib = pszDefaultLib;
4556 0 : bUseLib.reset();
4557 : }
4558 : else
4559 398 : break;
4560 : }
4561 : }
4562 : else
4563 0 : bUseLib = bHasLib;
4564 :
4565 398 : GDALPDFObject *poPageObj = nullptr;
4566 : #ifdef HAVE_POPPLER
4567 398 : PDFDoc *poDocPoppler = nullptr;
4568 398 : Page *poPagePoppler = nullptr;
4569 398 : Catalog *poCatalogPoppler = nullptr;
4570 : #endif
4571 : #ifdef HAVE_PODOFO
4572 : std::unique_ptr<PoDoFo::PdfMemDocument> poDocPodofo;
4573 : PoDoFo::PdfPage *poPagePodofo = nullptr;
4574 : #endif
4575 : #ifdef HAVE_PDFIUM
4576 398 : TPdfiumDocumentStruct *poDocPdfium = nullptr;
4577 398 : TPdfiumPageStruct *poPagePdfium = nullptr;
4578 : #endif
4579 398 : int nPages = 0;
4580 398 : VSIVirtualHandleUniquePtr fp;
4581 :
4582 : #ifdef HAVE_POPPLER
4583 398 : if (bUseLib.test(PDFLIB_POPPLER))
4584 : {
4585 : static bool globalParamsCreatedByGDAL = false;
4586 : {
4587 342 : CPLMutexHolderD(&hGlobalParamsMutex);
4588 : /* poppler global variable */
4589 171 : if (globalParams == nullptr)
4590 : {
4591 2 : globalParamsCreatedByGDAL = true;
4592 2 : globalParams.reset(new GlobalParams());
4593 : }
4594 :
4595 171 : globalParams->setPrintCommands(CPLTestBool(
4596 : CPLGetConfigOption("GDAL_PDF_PRINT_COMMANDS", "FALSE")));
4597 : }
4598 :
4599 340 : const auto registerErrorCallback = []()
4600 : {
4601 : /* Set custom error handler for poppler errors */
4602 340 : setErrorCallback(PDFDatasetErrorFunction);
4603 340 : assert(globalParams); // avoid CSA false positive
4604 340 : globalParams->setErrQuiet(false);
4605 340 : };
4606 :
4607 171 : fp.reset(VSIFOpenL(pszFilename, "rb"));
4608 171 : if (!fp)
4609 4 : return nullptr;
4610 :
4611 : #ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
4612 : {
4613 : // Workaround for ossfuzz only due to
4614 : // https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=37584
4615 : // https://gitlab.freedesktop.org/poppler/poppler/-/issues/1137
4616 : GByte *pabyRet = nullptr;
4617 : vsi_l_offset nSize = 0;
4618 : if (VSIIngestFile(fp.get(), pszFilename, &pabyRet, &nSize,
4619 : 10 * 1024 * 1024))
4620 : {
4621 : // Replace nul byte by something else so that strstr() works
4622 : for (size_t i = 0; i < nSize; i++)
4623 : {
4624 : if (pabyRet[i] == 0)
4625 : pabyRet[i] = ' ';
4626 : }
4627 : if (strstr(reinterpret_cast<const char *>(pabyRet),
4628 : "/JBIG2Decode"))
4629 : {
4630 : CPLError(CE_Failure, CPLE_AppDefined,
4631 : "/JBIG2Decode found. Giving up due to potential "
4632 : "very long processing time.");
4633 : CPLFree(pabyRet);
4634 : return nullptr;
4635 : }
4636 : }
4637 : CPLFree(pabyRet);
4638 : }
4639 : #endif
4640 :
4641 170 : fp.reset(VSICreateBufferedReaderHandle(fp.release()));
4642 : while (true)
4643 : {
4644 170 : fp->Seek(0, SEEK_SET);
4645 170 : g_nPopplerErrors = 0;
4646 170 : if (globalParamsCreatedByGDAL)
4647 170 : registerErrorCallback();
4648 170 : Object oObj;
4649 : auto poStream =
4650 170 : new VSIPDFFileStream(fp.get(), pszFilename, std::move(oObj));
4651 : #if POPPLER_MAJOR_VERSION > 22 || \
4652 : (POPPLER_MAJOR_VERSION == 22 && POPPLER_MINOR_VERSION > 2)
4653 : std::optional<GooString> osUserPwd;
4654 : if (pszUserPwd)
4655 : osUserPwd = std::optional<GooString>(pszUserPwd);
4656 : try
4657 : {
4658 : poDocPoppler =
4659 : new PDFDoc(poStream, std::optional<GooString>(), osUserPwd);
4660 : }
4661 : catch (const std::exception &e)
4662 : {
4663 : CPLError(CE_Failure, CPLE_AppDefined,
4664 : "PDFDoc::PDFDoc() failed with %s", e.what());
4665 : return nullptr;
4666 : }
4667 : #else
4668 170 : GooString *poUserPwd = nullptr;
4669 170 : if (pszUserPwd)
4670 2 : poUserPwd = new GooString(pszUserPwd);
4671 170 : poDocPoppler = new PDFDoc(poStream, nullptr, poUserPwd);
4672 170 : delete poUserPwd;
4673 : #endif
4674 170 : if (globalParamsCreatedByGDAL)
4675 170 : registerErrorCallback();
4676 170 : if (g_nPopplerErrors >= MAX_POPPLER_ERRORS)
4677 : {
4678 0 : PDFFreeDoc(poDocPoppler);
4679 0 : return nullptr;
4680 : }
4681 :
4682 170 : if (!poDocPoppler->isOk() || poDocPoppler->getNumPages() == 0)
4683 : {
4684 2 : if (poDocPoppler->getErrorCode() == errEncrypted)
4685 : {
4686 2 : if (pszUserPwd && EQUAL(pszUserPwd, "ASK_INTERACTIVE"))
4687 : {
4688 : pszUserPwd =
4689 0 : PDFEnterPasswordFromConsoleIfNeeded(pszUserPwd);
4690 0 : PDFFreeDoc(poDocPoppler);
4691 :
4692 : /* Reset errors that could have been issued during
4693 : * opening and that */
4694 : /* did not result in an invalid document */
4695 0 : CPLErrorReset();
4696 :
4697 0 : continue;
4698 : }
4699 2 : else if (pszUserPwd == nullptr)
4700 : {
4701 1 : CPLError(CE_Failure, CPLE_AppDefined,
4702 : "A password is needed. You can specify it "
4703 : "through the PDF_USER_PWD "
4704 : "configuration option / USER_PWD open option "
4705 : "(that can be set to ASK_INTERACTIVE)");
4706 : }
4707 : else
4708 : {
4709 1 : CPLError(CE_Failure, CPLE_AppDefined,
4710 : "Invalid password");
4711 : }
4712 : }
4713 : else
4714 : {
4715 0 : CPLError(CE_Failure, CPLE_AppDefined, "Invalid PDF");
4716 : }
4717 :
4718 2 : PDFFreeDoc(poDocPoppler);
4719 2 : return nullptr;
4720 : }
4721 168 : else if (poDocPoppler->isLinearized() &&
4722 0 : !poStream->FoundLinearizedHint())
4723 : {
4724 : // This is a likely defect of poppler Linearization.cc file that
4725 : // recognizes a file as linearized if the /Linearized hint is
4726 : // missing, but the content of this dictionary are present. But
4727 : // given the hacks of PDFFreeDoc() and
4728 : // VSIPDFFileStream::FillBuffer() opening such a file will
4729 : // result in a null-ptr deref at closing if we try to access a
4730 : // page and build the page cache, so just exit now
4731 0 : CPLError(CE_Failure, CPLE_AppDefined, "Invalid PDF");
4732 :
4733 0 : PDFFreeDoc(poDocPoppler);
4734 0 : return nullptr;
4735 : }
4736 : else
4737 : {
4738 168 : break;
4739 : }
4740 0 : }
4741 :
4742 168 : poCatalogPoppler = poDocPoppler->getCatalog();
4743 168 : if (poCatalogPoppler == nullptr || !poCatalogPoppler->isOk())
4744 : {
4745 0 : CPLError(CE_Failure, CPLE_AppDefined,
4746 : "Invalid PDF : invalid catalog");
4747 0 : PDFFreeDoc(poDocPoppler);
4748 0 : return nullptr;
4749 : }
4750 :
4751 168 : nPages = poDocPoppler->getNumPages();
4752 :
4753 168 : if (iPage == 1 && nPages > 10000 &&
4754 0 : CPLTestBool(CPLGetConfigOption("GDAL_PDF_LIMIT_PAGE_COUNT", "YES")))
4755 : {
4756 0 : CPLError(CE_Warning, CPLE_AppDefined,
4757 : "This PDF document reports %d pages. "
4758 : "Limiting count to 10000 for performance reasons. "
4759 : "You may remove this limit by setting the "
4760 : "GDAL_PDF_LIMIT_PAGE_COUNT configuration option to NO",
4761 : nPages);
4762 0 : nPages = 10000;
4763 : }
4764 :
4765 168 : if (iPage < 1 || iPage > nPages)
4766 : {
4767 1 : CPLError(CE_Failure, CPLE_AppDefined, "Invalid page number (%d/%d)",
4768 : iPage, nPages);
4769 1 : PDFFreeDoc(poDocPoppler);
4770 1 : return nullptr;
4771 : }
4772 :
4773 : /* Sanity check to validate page count */
4774 167 : if (iPage > 1 && nPages <= 10000 && iPage != nPages)
4775 : {
4776 4 : poPagePoppler = poCatalogPoppler->getPage(nPages);
4777 4 : if (poPagePoppler == nullptr || !poPagePoppler->isOk())
4778 : {
4779 0 : CPLError(CE_Failure, CPLE_AppDefined,
4780 : "Invalid PDF : invalid page count");
4781 0 : PDFFreeDoc(poDocPoppler);
4782 0 : return nullptr;
4783 : }
4784 : }
4785 :
4786 167 : poPagePoppler = poCatalogPoppler->getPage(iPage);
4787 167 : if (poPagePoppler == nullptr || !poPagePoppler->isOk())
4788 : {
4789 0 : CPLError(CE_Failure, CPLE_AppDefined, "Invalid PDF : invalid page");
4790 0 : PDFFreeDoc(poDocPoppler);
4791 0 : return nullptr;
4792 : }
4793 :
4794 : #if POPPLER_MAJOR_VERSION > 25 || \
4795 : (POPPLER_MAJOR_VERSION == 25 && POPPLER_MINOR_VERSION >= 3)
4796 : const Object &oPageObj = poPagePoppler->getPageObj();
4797 : #else
4798 : /* Here's the dirty part: this is a private member */
4799 : /* so we had to #define private public to get it ! */
4800 167 : const Object &oPageObj = poPagePoppler->pageObj;
4801 : #endif
4802 167 : if (!oPageObj.isDict())
4803 : {
4804 0 : CPLError(CE_Failure, CPLE_AppDefined,
4805 : "Invalid PDF : !oPageObj.isDict()");
4806 0 : PDFFreeDoc(poDocPoppler);
4807 0 : return nullptr;
4808 : }
4809 :
4810 167 : poPageObj = new GDALPDFObjectPoppler(&oPageObj);
4811 167 : Ref *poPageRef = poCatalogPoppler->getPageRef(iPage);
4812 167 : if (poPageRef != nullptr)
4813 : {
4814 334 : cpl::down_cast<GDALPDFObjectPoppler *>(poPageObj)->SetRefNumAndGen(
4815 334 : GDALPDFObjectNum(poPageRef->num), poPageRef->gen);
4816 : }
4817 : }
4818 : #endif // ~ HAVE_POPPLER
4819 :
4820 : #ifdef HAVE_PODOFO
4821 : if (bUseLib.test(PDFLIB_PODOFO) && poPageObj == nullptr)
4822 : {
4823 : #if !(PODOFO_VERSION_MAJOR > 0 || \
4824 : (PODOFO_VERSION_MAJOR == 0 && PODOFO_VERSION_MINOR >= 10))
4825 : PoDoFo::PdfError::EnableDebug(false);
4826 : PoDoFo::PdfError::EnableLogging(false);
4827 : #endif
4828 :
4829 : poDocPodofo = std::make_unique<PoDoFo::PdfMemDocument>();
4830 : try
4831 : {
4832 : poDocPodofo->Load(pszFilename);
4833 : }
4834 : catch (PoDoFo::PdfError &oError)
4835 : {
4836 : #if PODOFO_VERSION_MAJOR > 0 || \
4837 : (PODOFO_VERSION_MAJOR == 0 && PODOFO_VERSION_MINOR >= 10)
4838 : if (oError.GetCode() == PoDoFo::PdfErrorCode::InvalidPassword)
4839 : #else
4840 : if (oError.GetError() == PoDoFo::ePdfError_InvalidPassword)
4841 : #endif
4842 : {
4843 : if (pszUserPwd)
4844 : {
4845 : pszUserPwd =
4846 : PDFEnterPasswordFromConsoleIfNeeded(pszUserPwd);
4847 :
4848 : try
4849 : {
4850 : #if PODOFO_VERSION_MAJOR > 0 || \
4851 : (PODOFO_VERSION_MAJOR == 0 && PODOFO_VERSION_MINOR >= 10)
4852 : poDocPodofo =
4853 : std::make_unique<PoDoFo::PdfMemDocument>();
4854 : poDocPodofo->Load(pszFilename, pszUserPwd);
4855 : #else
4856 : poDocPodofo->SetPassword(pszUserPwd);
4857 : #endif
4858 : }
4859 : catch (PoDoFo::PdfError &oError2)
4860 : {
4861 : #if PODOFO_VERSION_MAJOR > 0 || \
4862 : (PODOFO_VERSION_MAJOR == 0 && PODOFO_VERSION_MINOR >= 10)
4863 : if (oError2.GetCode() ==
4864 : PoDoFo::PdfErrorCode::InvalidPassword)
4865 : #else
4866 : if (oError2.GetError() ==
4867 : PoDoFo::ePdfError_InvalidPassword)
4868 : #endif
4869 : {
4870 : CPLError(CE_Failure, CPLE_AppDefined,
4871 : "Invalid password");
4872 : }
4873 : else
4874 : {
4875 : CPLError(CE_Failure, CPLE_AppDefined,
4876 : "Invalid PDF : %s", oError2.what());
4877 : }
4878 : return nullptr;
4879 : }
4880 : catch (...)
4881 : {
4882 : CPLError(CE_Failure, CPLE_AppDefined, "Invalid PDF");
4883 : return nullptr;
4884 : }
4885 : }
4886 : else
4887 : {
4888 : CPLError(CE_Failure, CPLE_AppDefined,
4889 : "A password is needed. You can specify it through "
4890 : "the PDF_USER_PWD "
4891 : "configuration option / USER_PWD open option "
4892 : "(that can be set to ASK_INTERACTIVE)");
4893 : return nullptr;
4894 : }
4895 : }
4896 : else
4897 : {
4898 : CPLError(CE_Failure, CPLE_AppDefined, "Invalid PDF : %s",
4899 : oError.what());
4900 : return nullptr;
4901 : }
4902 : }
4903 : catch (...)
4904 : {
4905 : CPLError(CE_Failure, CPLE_AppDefined, "Invalid PDF");
4906 : return nullptr;
4907 : }
4908 :
4909 : #if PODOFO_VERSION_MAJOR > 0 || \
4910 : (PODOFO_VERSION_MAJOR == 0 && PODOFO_VERSION_MINOR >= 10)
4911 : auto &oPageCollections = poDocPodofo->GetPages();
4912 : nPages = static_cast<int>(oPageCollections.GetCount());
4913 : #else
4914 : nPages = poDocPodofo->GetPageCount();
4915 : #endif
4916 : if (iPage < 1 || iPage > nPages)
4917 : {
4918 : CPLError(CE_Failure, CPLE_AppDefined, "Invalid page number (%d/%d)",
4919 : iPage, nPages);
4920 : return nullptr;
4921 : }
4922 :
4923 : try
4924 : {
4925 : #if PODOFO_VERSION_MAJOR > 0 || \
4926 : (PODOFO_VERSION_MAJOR == 0 && PODOFO_VERSION_MINOR >= 10)
4927 : /* Sanity check to validate page count */
4928 : if (iPage != nPages)
4929 : CPL_IGNORE_RET_VAL(oPageCollections.GetPageAt(nPages - 1));
4930 :
4931 : poPagePodofo = &oPageCollections.GetPageAt(iPage - 1);
4932 : #else
4933 : /* Sanity check to validate page count */
4934 : if (iPage != nPages)
4935 : CPL_IGNORE_RET_VAL(poDocPodofo->GetPage(nPages - 1));
4936 :
4937 : poPagePodofo = poDocPodofo->GetPage(iPage - 1);
4938 : #endif
4939 : }
4940 : catch (PoDoFo::PdfError &oError)
4941 : {
4942 : CPLError(CE_Failure, CPLE_AppDefined, "Invalid PDF : %s",
4943 : oError.what());
4944 : return nullptr;
4945 : }
4946 : catch (...)
4947 : {
4948 : CPLError(CE_Failure, CPLE_AppDefined, "Invalid PDF");
4949 : return nullptr;
4950 : }
4951 :
4952 : if (poPagePodofo == nullptr)
4953 : {
4954 : CPLError(CE_Failure, CPLE_AppDefined, "Invalid PDF : invalid page");
4955 : return nullptr;
4956 : }
4957 :
4958 : #if PODOFO_VERSION_MAJOR > 0 || \
4959 : (PODOFO_VERSION_MAJOR == 0 && PODOFO_VERSION_MINOR >= 10)
4960 : const PoDoFo::PdfObject *pObj = &poPagePodofo->GetObject();
4961 : #else
4962 : const PoDoFo::PdfObject *pObj = poPagePodofo->GetObject();
4963 : #endif
4964 : poPageObj = new GDALPDFObjectPodofo(pObj, poDocPodofo->GetObjects());
4965 : }
4966 : #endif // ~ HAVE_PODOFO
4967 :
4968 : #ifdef HAVE_PDFIUM
4969 394 : if (bUseLib.test(PDFLIB_PDFIUM) && poPageObj == nullptr)
4970 : {
4971 227 : if (!LoadPdfiumDocumentPage(pszFilename, pszUserPwd, iPage,
4972 : &poDocPdfium, &poPagePdfium, &nPages))
4973 : {
4974 : // CPLError is called inside function
4975 14 : return nullptr;
4976 : }
4977 :
4978 213 : const auto pageObj = poPagePdfium->page->GetDict();
4979 213 : if (pageObj == nullptr)
4980 : {
4981 0 : CPLError(CE_Failure, CPLE_AppDefined,
4982 : "Invalid PDF : invalid page object");
4983 0 : UnloadPdfiumDocumentPage(&poDocPdfium, &poPagePdfium);
4984 0 : return nullptr;
4985 : }
4986 213 : poPageObj = GDALPDFObjectPdfium::Build(pageObj);
4987 : }
4988 : #endif // ~ HAVE_PDFIUM
4989 :
4990 380 : if (poPageObj == nullptr)
4991 0 : return nullptr;
4992 380 : GDALPDFDictionary *poPageDict = poPageObj->GetDictionary();
4993 380 : if (poPageDict == nullptr)
4994 : {
4995 0 : delete poPageObj;
4996 :
4997 0 : CPLError(CE_Failure, CPLE_AppDefined,
4998 : "Invalid PDF : poPageDict == nullptr");
4999 : #ifdef HAVE_POPPLER
5000 0 : if (bUseLib.test(PDFLIB_POPPLER))
5001 0 : PDFFreeDoc(poDocPoppler);
5002 : #endif
5003 : #ifdef HAVE_PDFIUM
5004 0 : if (bUseLib.test(PDFLIB_PDFIUM))
5005 : {
5006 0 : UnloadPdfiumDocumentPage(&poDocPdfium, &poPagePdfium);
5007 : }
5008 : #endif
5009 0 : return nullptr;
5010 : }
5011 :
5012 380 : const char *pszDumpObject = CPLGetConfigOption("PDF_DUMP_OBJECT", nullptr);
5013 380 : if (pszDumpObject != nullptr)
5014 : {
5015 4 : GDALPDFDumper oDumper(pszFilename, pszDumpObject);
5016 2 : oDumper.Dump(poPageObj);
5017 : }
5018 :
5019 380 : PDFDataset *poDS = new PDFDataset();
5020 380 : poDS->m_fp = std::move(fp);
5021 380 : poDS->papszOpenOptions = CSLDuplicate(poOpenInfo->papszOpenOptions);
5022 380 : poDS->m_bUseLib = bUseLib;
5023 380 : poDS->m_osFilename = pszFilename;
5024 380 : poDS->eAccess = poOpenInfo->eAccess;
5025 :
5026 380 : if (nPages > 1 && !bOpenSubdataset)
5027 : {
5028 : int i;
5029 8 : CPLStringList aosList;
5030 16 : for (i = 0; i < nPages; i++)
5031 : {
5032 : char szKey[32];
5033 12 : snprintf(szKey, sizeof(szKey), "SUBDATASET_%d_NAME", i + 1);
5034 : aosList.AddNameValue(
5035 12 : szKey, CPLSPrintf("PDF:%d:%s", i + 1, poOpenInfo->pszFilename));
5036 12 : snprintf(szKey, sizeof(szKey), "SUBDATASET_%d_DESC", i + 1);
5037 : aosList.AddNameValue(szKey, CPLSPrintf("Page %d of %s", i + 1,
5038 12 : poOpenInfo->pszFilename));
5039 : }
5040 4 : poDS->SetMetadata(aosList.List(), "SUBDATASETS");
5041 : }
5042 :
5043 : #ifdef HAVE_POPPLER
5044 380 : poDS->m_poDocPoppler = poDocPoppler;
5045 : #endif
5046 : #ifdef HAVE_PODOFO
5047 : poDS->m_poDocPodofo = poDocPodofo.release();
5048 : #endif
5049 : #ifdef HAVE_PDFIUM
5050 380 : poDS->m_poDocPdfium = poDocPdfium;
5051 380 : poDS->m_poPagePdfium = poPagePdfium;
5052 : #endif
5053 380 : poDS->m_poPageObj = poPageObj;
5054 380 : poDS->m_osUserPwd = pszUserPwd ? pszUserPwd : "";
5055 380 : poDS->m_iPage = iPage;
5056 :
5057 : const char *pszDumpCatalog =
5058 380 : CPLGetConfigOption("PDF_DUMP_CATALOG", nullptr);
5059 380 : if (pszDumpCatalog != nullptr)
5060 : {
5061 0 : GDALPDFDumper oDumper(pszFilename, pszDumpCatalog);
5062 0 : auto poCatalog = poDS->GetCatalog();
5063 0 : if (poCatalog)
5064 0 : oDumper.Dump(poCatalog);
5065 : }
5066 :
5067 380 : int nBandsGuessed = 0;
5068 380 : if (nImageNum < 0)
5069 : {
5070 380 : poDS->GuessDPI(poPageDict, &nBandsGuessed);
5071 380 : if (nBandsGuessed < 4)
5072 364 : nBandsGuessed = 0;
5073 : }
5074 : else
5075 : {
5076 : const char *pszDPI =
5077 0 : GetOption(poOpenInfo->papszOpenOptions, "DPI", nullptr);
5078 0 : if (pszDPI != nullptr)
5079 : {
5080 : // coverity[tainted_data]
5081 0 : poDS->m_dfDPI = CPLAtof(pszDPI);
5082 : }
5083 : }
5084 :
5085 380 : double dfX1 = 0.0;
5086 380 : double dfY1 = 0.0;
5087 380 : double dfX2 = 0.0;
5088 380 : double dfY2 = 0.0;
5089 :
5090 : #ifdef HAVE_POPPLER
5091 380 : if (bUseLib.test(PDFLIB_POPPLER))
5092 : {
5093 167 : const auto *psMediaBox = poPagePoppler->getMediaBox();
5094 167 : dfX1 = psMediaBox->x1;
5095 167 : dfY1 = psMediaBox->y1;
5096 167 : dfX2 = psMediaBox->x2;
5097 167 : dfY2 = psMediaBox->y2;
5098 : }
5099 : #endif
5100 :
5101 : #ifdef HAVE_PODOFO
5102 : if (bUseLib.test(PDFLIB_PODOFO))
5103 : {
5104 : CPLAssert(poPagePodofo);
5105 : auto oMediaBox = poPagePodofo->GetMediaBox();
5106 : dfX1 = oMediaBox.GetLeft();
5107 : dfY1 = oMediaBox.GetBottom();
5108 : #if PODOFO_VERSION_MAJOR > 0 || \
5109 : (PODOFO_VERSION_MAJOR == 0 && PODOFO_VERSION_MINOR >= 10)
5110 : dfX2 = dfX1 + oMediaBox.Width;
5111 : dfY2 = dfY1 + oMediaBox.Height;
5112 : #else
5113 : dfX2 = dfX1 + oMediaBox.GetWidth();
5114 : dfY2 = dfY1 + oMediaBox.GetHeight();
5115 : #endif
5116 : }
5117 : #endif
5118 :
5119 : #ifdef HAVE_PDFIUM
5120 380 : if (bUseLib.test(PDFLIB_PDFIUM))
5121 : {
5122 213 : CPLAssert(poPagePdfium);
5123 213 : CFX_FloatRect rect = poPagePdfium->page->GetBBox();
5124 213 : dfX1 = rect.left;
5125 213 : dfX2 = rect.right;
5126 213 : dfY1 = rect.bottom;
5127 213 : dfY2 = rect.top;
5128 : }
5129 : #endif // ~ HAVE_PDFIUM
5130 :
5131 380 : double dfUserUnit = poDS->m_dfDPI * USER_UNIT_IN_INCH;
5132 380 : poDS->m_dfPageWidth = dfX2 - dfX1;
5133 380 : poDS->m_dfPageHeight = dfY2 - dfY1;
5134 : // CPLDebug("PDF", "left=%f right=%f bottom=%f top=%f", dfX1, dfX2, dfY1,
5135 : // dfY2);
5136 380 : const double dfXSize = floor((dfX2 - dfX1) * dfUserUnit + 0.5);
5137 380 : const double dfYSize = floor((dfY2 - dfY1) * dfUserUnit + 0.5);
5138 380 : if (!(dfXSize >= 0 && dfXSize <= INT_MAX && dfYSize >= 0 &&
5139 380 : dfYSize <= INT_MAX))
5140 : {
5141 0 : delete poDS;
5142 0 : return nullptr;
5143 : }
5144 380 : poDS->nRasterXSize = static_cast<int>(dfXSize);
5145 380 : poDS->nRasterYSize = static_cast<int>(dfYSize);
5146 :
5147 380 : if (!GDALCheckDatasetDimensions(poDS->nRasterXSize, poDS->nRasterYSize))
5148 : {
5149 0 : delete poDS;
5150 0 : return nullptr;
5151 : }
5152 :
5153 380 : double dfRotation = 0;
5154 : #ifdef HAVE_POPPLER
5155 380 : if (bUseLib.test(PDFLIB_POPPLER))
5156 167 : dfRotation = poDocPoppler->getPageRotate(iPage);
5157 : #endif
5158 :
5159 : #ifdef HAVE_PODOFO
5160 : if (bUseLib.test(PDFLIB_PODOFO))
5161 : {
5162 : CPLAssert(poPagePodofo);
5163 : #if PODOFO_VERSION_MAJOR > 0 || \
5164 : (PODOFO_VERSION_MAJOR == 0 && PODOFO_VERSION_MINOR >= 10)
5165 : dfRotation = poPagePodofo->GetRotationRaw();
5166 : #else
5167 : dfRotation = poPagePodofo->GetRotation();
5168 : #endif
5169 : }
5170 : #endif
5171 :
5172 : #ifdef HAVE_PDFIUM
5173 380 : if (bUseLib.test(PDFLIB_PDFIUM))
5174 : {
5175 213 : CPLAssert(poPagePdfium);
5176 213 : dfRotation = poPagePdfium->page->GetPageRotation() * 90;
5177 : }
5178 : #endif
5179 :
5180 380 : if (dfRotation == 90 || dfRotation == -90 || dfRotation == 270)
5181 : {
5182 : /* FIXME: the podofo case should be implemented. This needs to rotate */
5183 : /* the output of pdftoppm */
5184 : #if defined(HAVE_POPPLER) || defined(HAVE_PDFIUM)
5185 0 : if (bUseLib.test(PDFLIB_POPPLER) || bUseLib.test(PDFLIB_PDFIUM))
5186 : {
5187 0 : int nTmp = poDS->nRasterXSize;
5188 0 : poDS->nRasterXSize = poDS->nRasterYSize;
5189 0 : poDS->nRasterYSize = nTmp;
5190 : }
5191 : #endif
5192 : }
5193 :
5194 380 : if (CSLFetchNameValue(poOpenInfo->papszOpenOptions, "@OPEN_FOR_OVERVIEW"))
5195 : {
5196 2 : poDS->m_nBlockXSize = 512;
5197 2 : poDS->m_nBlockYSize = 512;
5198 : }
5199 : /* Check if the PDF is only made of regularly tiled images */
5200 : /* (like some USGS GeoPDF production) */
5201 675 : else if (dfRotation == 0.0 && !poDS->m_asTiles.empty() &&
5202 297 : EQUAL(GetOption(poOpenInfo->papszOpenOptions, "LAYERS", "ALL"),
5203 : "ALL"))
5204 : {
5205 297 : poDS->CheckTiledRaster();
5206 297 : if (!poDS->m_aiTiles.empty())
5207 18 : poDS->SetMetadataItem("INTERLEAVE", "PIXEL", "IMAGE_STRUCTURE");
5208 : }
5209 :
5210 380 : GDALPDFObject *poLGIDict = nullptr;
5211 380 : GDALPDFObject *poVP = nullptr;
5212 380 : int bIsOGCBP = FALSE;
5213 380 : if ((poLGIDict = poPageDict->Get("LGIDict")) != nullptr && nImageNum < 0)
5214 : {
5215 : /* Cf 08-139r3_GeoPDF_Encoding_Best_Practice_Version_2.2.pdf */
5216 0 : CPLDebug("PDF", "OGC Encoding Best Practice style detected");
5217 0 : if (poDS->ParseLGIDictObject(poLGIDict))
5218 : {
5219 0 : if (poDS->m_bHasCTM)
5220 : {
5221 0 : if (dfRotation == 90)
5222 : {
5223 0 : poDS->m_adfGeoTransform[0] = poDS->m_adfCTM[4];
5224 0 : poDS->m_adfGeoTransform[1] = poDS->m_adfCTM[2] / dfUserUnit;
5225 0 : poDS->m_adfGeoTransform[2] = poDS->m_adfCTM[0] / dfUserUnit;
5226 0 : poDS->m_adfGeoTransform[3] = poDS->m_adfCTM[5];
5227 0 : poDS->m_adfGeoTransform[4] = poDS->m_adfCTM[3] / dfUserUnit;
5228 0 : poDS->m_adfGeoTransform[5] = poDS->m_adfCTM[1] / dfUserUnit;
5229 : }
5230 0 : else if (dfRotation == -90 || dfRotation == 270)
5231 : {
5232 0 : poDS->m_adfGeoTransform[0] =
5233 0 : poDS->m_adfCTM[4] +
5234 0 : poDS->m_adfCTM[2] * poDS->m_dfPageHeight +
5235 0 : poDS->m_adfCTM[0] * poDS->m_dfPageWidth;
5236 0 : poDS->m_adfGeoTransform[1] =
5237 0 : -poDS->m_adfCTM[2] / dfUserUnit;
5238 0 : poDS->m_adfGeoTransform[2] =
5239 0 : -poDS->m_adfCTM[0] / dfUserUnit;
5240 0 : poDS->m_adfGeoTransform[3] =
5241 0 : poDS->m_adfCTM[5] +
5242 0 : poDS->m_adfCTM[3] * poDS->m_dfPageHeight +
5243 0 : poDS->m_adfCTM[1] * poDS->m_dfPageWidth;
5244 0 : poDS->m_adfGeoTransform[4] =
5245 0 : -poDS->m_adfCTM[3] / dfUserUnit;
5246 0 : poDS->m_adfGeoTransform[5] =
5247 0 : -poDS->m_adfCTM[1] / dfUserUnit;
5248 : }
5249 : else
5250 : {
5251 0 : poDS->m_adfGeoTransform[0] = poDS->m_adfCTM[4] +
5252 0 : poDS->m_adfCTM[2] * dfY2 +
5253 0 : poDS->m_adfCTM[0] * dfX1;
5254 0 : poDS->m_adfGeoTransform[1] = poDS->m_adfCTM[0] / dfUserUnit;
5255 0 : poDS->m_adfGeoTransform[2] =
5256 0 : -poDS->m_adfCTM[2] / dfUserUnit;
5257 0 : poDS->m_adfGeoTransform[3] = poDS->m_adfCTM[5] +
5258 0 : poDS->m_adfCTM[3] * dfY2 +
5259 0 : poDS->m_adfCTM[1] * dfX1;
5260 0 : poDS->m_adfGeoTransform[4] = poDS->m_adfCTM[1] / dfUserUnit;
5261 0 : poDS->m_adfGeoTransform[5] =
5262 0 : -poDS->m_adfCTM[3] / dfUserUnit;
5263 : }
5264 :
5265 0 : poDS->m_bGeoTransformValid = true;
5266 : }
5267 :
5268 0 : bIsOGCBP = TRUE;
5269 :
5270 : int i;
5271 0 : for (i = 0; i < poDS->m_nGCPCount; i++)
5272 : {
5273 0 : if (dfRotation == 90)
5274 : {
5275 0 : double dfPixel =
5276 0 : poDS->m_pasGCPList[i].dfGCPPixel * dfUserUnit;
5277 0 : double dfLine =
5278 0 : poDS->m_pasGCPList[i].dfGCPLine * dfUserUnit;
5279 0 : poDS->m_pasGCPList[i].dfGCPPixel = dfLine;
5280 0 : poDS->m_pasGCPList[i].dfGCPLine = dfPixel;
5281 : }
5282 0 : else if (dfRotation == -90 || dfRotation == 270)
5283 : {
5284 0 : double dfPixel =
5285 0 : poDS->m_pasGCPList[i].dfGCPPixel * dfUserUnit;
5286 0 : double dfLine =
5287 0 : poDS->m_pasGCPList[i].dfGCPLine * dfUserUnit;
5288 0 : poDS->m_pasGCPList[i].dfGCPPixel =
5289 0 : poDS->nRasterXSize - dfLine;
5290 0 : poDS->m_pasGCPList[i].dfGCPLine =
5291 0 : poDS->nRasterYSize - dfPixel;
5292 : }
5293 : else
5294 : {
5295 0 : poDS->m_pasGCPList[i].dfGCPPixel =
5296 0 : (-dfX1 + poDS->m_pasGCPList[i].dfGCPPixel) * dfUserUnit;
5297 0 : poDS->m_pasGCPList[i].dfGCPLine =
5298 0 : (dfY2 - poDS->m_pasGCPList[i].dfGCPLine) * dfUserUnit;
5299 : }
5300 : }
5301 : }
5302 : }
5303 380 : else if ((poVP = poPageDict->Get("VP")) != nullptr && nImageNum < 0)
5304 : {
5305 : /* Cf adobe_supplement_iso32000.pdf */
5306 281 : CPLDebug("PDF", "Adobe ISO32000 style Geospatial PDF perhaps ?");
5307 281 : if (dfX1 != 0 || dfY1 != 0)
5308 : {
5309 0 : CPLDebug("PDF", "non null dfX1 or dfY1 values. untested case...");
5310 : }
5311 281 : poDS->ParseVP(poVP, dfX2 - dfX1, dfY2 - dfY1);
5312 : }
5313 : else
5314 : {
5315 : GDALPDFObject *poXObject =
5316 99 : poPageDict->LookupObject("Resources.XObject");
5317 :
5318 196 : if (poXObject != nullptr &&
5319 97 : poXObject->GetType() == PDFObjectType_Dictionary)
5320 : {
5321 97 : GDALPDFDictionary *poXObjectDict = poXObject->GetDictionary();
5322 97 : const auto &oMap = poXObjectDict->GetValues();
5323 97 : int nSubDataset = 0;
5324 398 : for (const auto &[osKey, poObj] : oMap)
5325 : {
5326 301 : if (poObj->GetType() == PDFObjectType_Dictionary)
5327 : {
5328 301 : GDALPDFDictionary *poDict = poObj->GetDictionary();
5329 301 : GDALPDFObject *poSubtype = nullptr;
5330 301 : GDALPDFObject *poMeasure = nullptr;
5331 301 : GDALPDFObject *poWidth = nullptr;
5332 301 : GDALPDFObject *poHeight = nullptr;
5333 301 : int nW = 0;
5334 301 : int nH = 0;
5335 301 : if ((poSubtype = poDict->Get("Subtype")) != nullptr &&
5336 602 : poSubtype->GetType() == PDFObjectType_Name &&
5337 301 : poSubtype->GetName() == "Image" &&
5338 256 : (poMeasure = poDict->Get("Measure")) != nullptr &&
5339 0 : poMeasure->GetType() == PDFObjectType_Dictionary &&
5340 0 : (poWidth = poDict->Get("Width")) != nullptr &&
5341 0 : poWidth->GetType() == PDFObjectType_Int &&
5342 0 : (nW = poWidth->GetInt()) > 0 &&
5343 0 : (poHeight = poDict->Get("Height")) != nullptr &&
5344 602 : poHeight->GetType() == PDFObjectType_Int &&
5345 0 : (nH = poHeight->GetInt()) > 0)
5346 : {
5347 0 : if (nImageNum < 0)
5348 0 : CPLDebug("PDF",
5349 : "Measure found on Image object (%d)",
5350 0 : poObj->GetRefNum().toInt());
5351 :
5352 0 : GDALPDFObject *poColorSpace = poDict->Get("ColorSpace");
5353 : GDALPDFObject *poBitsPerComponent =
5354 0 : poDict->Get("BitsPerComponent");
5355 0 : if (poObj->GetRefNum().toBool() &&
5356 0 : poObj->GetRefGen() == 0 &&
5357 0 : poColorSpace != nullptr &&
5358 0 : poColorSpace->GetType() == PDFObjectType_Name &&
5359 0 : (poColorSpace->GetName() == "DeviceGray" ||
5360 0 : poColorSpace->GetName() == "DeviceRGB") &&
5361 0 : (poBitsPerComponent == nullptr ||
5362 0 : (poBitsPerComponent->GetType() ==
5363 0 : PDFObjectType_Int &&
5364 0 : poBitsPerComponent->GetInt() == 8)))
5365 : {
5366 0 : if (nImageNum < 0)
5367 : {
5368 0 : nSubDataset++;
5369 0 : poDS->SetMetadataItem(
5370 : CPLSPrintf("SUBDATASET_%d_NAME",
5371 : nSubDataset),
5372 : CPLSPrintf("PDF_IMAGE:%d:%d:%s", iPage,
5373 0 : poObj->GetRefNum().toInt(),
5374 : pszFilename),
5375 : "SUBDATASETS");
5376 0 : poDS->SetMetadataItem(
5377 : CPLSPrintf("SUBDATASET_%d_DESC",
5378 : nSubDataset),
5379 : CPLSPrintf("Georeferenced image of size "
5380 : "%dx%d of page %d of %s",
5381 : nW, nH, iPage, pszFilename),
5382 : "SUBDATASETS");
5383 : }
5384 0 : else if (poObj->GetRefNum().toInt() == nImageNum)
5385 : {
5386 0 : poDS->nRasterXSize = nW;
5387 0 : poDS->nRasterYSize = nH;
5388 0 : poDS->ParseMeasure(poMeasure, nW, nH, 0, nH, nW,
5389 : 0);
5390 0 : poDS->m_poImageObj = poObj;
5391 0 : if (poColorSpace->GetName() == "DeviceGray")
5392 0 : nBandsGuessed = 1;
5393 0 : break;
5394 : }
5395 : }
5396 : }
5397 : }
5398 : }
5399 : }
5400 :
5401 99 : if (nImageNum >= 0 && poDS->m_poImageObj == nullptr)
5402 : {
5403 0 : CPLError(CE_Failure, CPLE_AppDefined, "Cannot find image %d",
5404 : nImageNum);
5405 0 : delete poDS;
5406 0 : return nullptr;
5407 : }
5408 :
5409 : /* Not a geospatial PDF doc */
5410 : }
5411 :
5412 : /* If pixel size or top left coordinates are very close to an int, round
5413 : * them to the int */
5414 380 : double dfEps = (fabs(poDS->m_adfGeoTransform[0]) > 1e5 &&
5415 207 : fabs(poDS->m_adfGeoTransform[3]) > 1e5)
5416 587 : ? 1e-5
5417 380 : : 1e-8;
5418 760 : poDS->m_adfGeoTransform[0] =
5419 380 : ROUND_IF_CLOSE(poDS->m_adfGeoTransform[0], dfEps);
5420 380 : poDS->m_adfGeoTransform[1] = ROUND_IF_CLOSE(poDS->m_adfGeoTransform[1]);
5421 760 : poDS->m_adfGeoTransform[3] =
5422 380 : ROUND_IF_CLOSE(poDS->m_adfGeoTransform[3], dfEps);
5423 380 : poDS->m_adfGeoTransform[5] = ROUND_IF_CLOSE(poDS->m_adfGeoTransform[5]);
5424 :
5425 380 : if (bUseLib.test(PDFLIB_PDFIUM))
5426 : {
5427 : // Attempt to "fix" the loss of precision due to the use of float32 for
5428 : // numbers by pdfium
5429 213 : if ((fabs(poDS->m_adfGeoTransform[0]) > 1e5 ||
5430 100 : fabs(poDS->m_adfGeoTransform[3]) > 1e5) &&
5431 113 : fabs(poDS->m_adfGeoTransform[0] -
5432 113 : std::round(poDS->m_adfGeoTransform[0])) <
5433 113 : 1e-6 * fabs(poDS->m_adfGeoTransform[0]) &&
5434 100 : fabs(poDS->m_adfGeoTransform[1] -
5435 100 : std::round(poDS->m_adfGeoTransform[1])) <
5436 100 : 1e-3 * fabs(poDS->m_adfGeoTransform[1]) &&
5437 89 : fabs(poDS->m_adfGeoTransform[3] -
5438 89 : std::round(poDS->m_adfGeoTransform[3])) <
5439 515 : 1e-6 * fabs(poDS->m_adfGeoTransform[3]) &&
5440 89 : fabs(poDS->m_adfGeoTransform[5] -
5441 89 : std::round(poDS->m_adfGeoTransform[5])) <
5442 89 : 1e-3 * fabs(poDS->m_adfGeoTransform[5]))
5443 : {
5444 623 : for (int i = 0; i < 6; i++)
5445 : {
5446 534 : poDS->m_adfGeoTransform[i] =
5447 534 : std::round(poDS->m_adfGeoTransform[i]);
5448 : }
5449 : }
5450 : }
5451 :
5452 380 : if (poDS->m_poNeatLine)
5453 : {
5454 280 : char *pszNeatLineWkt = nullptr;
5455 280 : OGRLinearRing *poRing = poDS->m_poNeatLine->getExteriorRing();
5456 : /* Adobe style is already in target SRS units */
5457 280 : if (bIsOGCBP)
5458 : {
5459 0 : int nPoints = poRing->getNumPoints();
5460 : int i;
5461 :
5462 0 : for (i = 0; i < nPoints; i++)
5463 : {
5464 : double x, y;
5465 0 : if (dfRotation == 90.0)
5466 : {
5467 0 : x = poRing->getY(i) * dfUserUnit;
5468 0 : y = poRing->getX(i) * dfUserUnit;
5469 : }
5470 0 : else if (dfRotation == -90.0 || dfRotation == 270.0)
5471 : {
5472 0 : x = poDS->nRasterXSize - poRing->getY(i) * dfUserUnit;
5473 0 : y = poDS->nRasterYSize - poRing->getX(i) * dfUserUnit;
5474 : }
5475 : else
5476 : {
5477 0 : x = (-dfX1 + poRing->getX(i)) * dfUserUnit;
5478 0 : y = (dfY2 - poRing->getY(i)) * dfUserUnit;
5479 : }
5480 0 : double X = poDS->m_adfGeoTransform[0] +
5481 0 : x * poDS->m_adfGeoTransform[1] +
5482 0 : y * poDS->m_adfGeoTransform[2];
5483 0 : double Y = poDS->m_adfGeoTransform[3] +
5484 0 : x * poDS->m_adfGeoTransform[4] +
5485 0 : y * poDS->m_adfGeoTransform[5];
5486 0 : poRing->setPoint(i, X, Y);
5487 : }
5488 : }
5489 280 : poRing->closeRings();
5490 :
5491 280 : poDS->m_poNeatLine->exportToWkt(&pszNeatLineWkt);
5492 280 : if (nImageNum < 0)
5493 280 : poDS->SetMetadataItem("NEATLINE", pszNeatLineWkt);
5494 280 : CPLFree(pszNeatLineWkt);
5495 : }
5496 :
5497 380 : poDS->MapOCGsToPages();
5498 :
5499 : #ifdef HAVE_POPPLER
5500 380 : if (bUseLib.test(PDFLIB_POPPLER))
5501 : {
5502 167 : auto poMetadata = poCatalogPoppler->readMetadata();
5503 167 : if (poMetadata)
5504 : {
5505 17 : const char *pszContent = poMetadata->c_str();
5506 17 : if (pszContent != nullptr &&
5507 17 : STARTS_WITH(pszContent, "<?xpacket begin="))
5508 : {
5509 17 : const char *const apszMDList[2] = {pszContent, nullptr};
5510 17 : poDS->SetMetadata(const_cast<char **>(apszMDList), "xml:XMP");
5511 : }
5512 : #if (POPPLER_MAJOR_VERSION < 21 || \
5513 : (POPPLER_MAJOR_VERSION == 21 && POPPLER_MINOR_VERSION < 10))
5514 17 : delete poMetadata;
5515 : #endif
5516 : }
5517 :
5518 : /* Read Info object */
5519 : /* The test is necessary since with some corrupted PDFs
5520 : * poDocPoppler->getDocInfo() */
5521 : /* might abort() */
5522 167 : if (poDocPoppler->getXRef()->isOk())
5523 : {
5524 334 : Object oInfo = poDocPoppler->getDocInfo();
5525 334 : GDALPDFObjectPoppler oInfoObjPoppler(&oInfo, FALSE);
5526 167 : poDS->ParseInfo(&oInfoObjPoppler);
5527 : }
5528 :
5529 : /* Find layers */
5530 322 : poDS->FindLayersPoppler(
5531 155 : (bOpenSubdataset || bOpenSubdatasetImage) ? iPage : 0);
5532 :
5533 : /* Turn user specified layers on or off */
5534 167 : poDS->TurnLayersOnOffPoppler();
5535 : }
5536 : #endif
5537 :
5538 : #ifdef HAVE_PODOFO
5539 : if (bUseLib.test(PDFLIB_PODOFO))
5540 : {
5541 : for (const auto &obj : poDS->m_poDocPodofo->GetObjects())
5542 : {
5543 : GDALPDFObjectPodofo oObjPodofo(obj,
5544 : poDS->m_poDocPodofo->GetObjects());
5545 : poDS->FindXMP(&oObjPodofo);
5546 : }
5547 :
5548 : /* Find layers */
5549 : poDS->FindLayersGeneric(poPageDict);
5550 :
5551 : /* Read Info object */
5552 : const PoDoFo::PdfInfo *poInfo = poDS->m_poDocPodofo->GetInfo();
5553 : if (poInfo != nullptr)
5554 : {
5555 : GDALPDFObjectPodofo oInfoObjPodofo(
5556 : #if PODOFO_VERSION_MAJOR > 0 || \
5557 : (PODOFO_VERSION_MAJOR == 0 && PODOFO_VERSION_MINOR >= 10)
5558 : &(poInfo->GetObject()),
5559 : #else
5560 : poInfo->GetObject(),
5561 : #endif
5562 : poDS->m_poDocPodofo->GetObjects());
5563 : poDS->ParseInfo(&oInfoObjPodofo);
5564 : }
5565 : }
5566 : #endif
5567 : #ifdef HAVE_PDFIUM
5568 380 : if (bUseLib.test(PDFLIB_PDFIUM))
5569 : {
5570 : // coverity is confused by WrapRetain(), believing that multiple
5571 : // smart pointers manage the same raw pointer. Which is actually
5572 : // true, but a RetainPtr holds a reference counted object. It is
5573 : // thus safe to have several RetainPtr holding it.
5574 : // coverity[multiple_init_smart_ptr]
5575 213 : GDALPDFObjectPdfium *poRoot = GDALPDFObjectPdfium::Build(
5576 426 : pdfium::WrapRetain(poDocPdfium->doc->GetRoot()));
5577 213 : if (poRoot->GetType() == PDFObjectType_Dictionary)
5578 : {
5579 213 : GDALPDFDictionary *poDict = poRoot->GetDictionary();
5580 213 : GDALPDFObject *poMetadata(poDict->Get("Metadata"));
5581 213 : if (poMetadata != nullptr)
5582 : {
5583 21 : GDALPDFStream *poStream = poMetadata->GetStream();
5584 21 : if (poStream != nullptr)
5585 : {
5586 19 : char *pszContent = poStream->GetBytes();
5587 19 : const auto nLength = poStream->GetLength();
5588 19 : if (pszContent != nullptr && nLength > 15 &&
5589 19 : STARTS_WITH(pszContent, "<?xpacket begin="))
5590 : {
5591 : char *apszMDList[2];
5592 19 : apszMDList[0] = pszContent;
5593 19 : apszMDList[1] = nullptr;
5594 19 : poDS->SetMetadata(apszMDList, "xml:XMP");
5595 : }
5596 19 : CPLFree(pszContent);
5597 : }
5598 : }
5599 : }
5600 213 : delete poRoot;
5601 :
5602 : /* Find layers */
5603 213 : poDS->FindLayersPdfium((bOpenSubdataset || bOpenSubdatasetImage) ? iPage
5604 : : 0);
5605 :
5606 : /* Turn user specified layers on or off */
5607 213 : poDS->TurnLayersOnOffPdfium();
5608 :
5609 : GDALPDFObjectPdfium *poInfo =
5610 213 : GDALPDFObjectPdfium::Build(poDocPdfium->doc->GetInfo());
5611 213 : if (poInfo)
5612 : {
5613 : /* Read Info object */
5614 39 : poDS->ParseInfo(poInfo);
5615 39 : delete poInfo;
5616 : }
5617 : }
5618 : #endif // ~ HAVE_PDFIUM
5619 :
5620 380 : int nBands = 3;
5621 : #ifdef HAVE_PDFIUM
5622 : // Use Alpha channel for PDFIUM as default format RGBA
5623 380 : if (bUseLib.test(PDFLIB_PDFIUM))
5624 213 : nBands = 4;
5625 : #endif
5626 380 : if (nBandsGuessed)
5627 16 : nBands = nBandsGuessed;
5628 : const char *pszPDFBands =
5629 380 : GetOption(poOpenInfo->papszOpenOptions, "BANDS", nullptr);
5630 380 : if (pszPDFBands)
5631 : {
5632 2 : nBands = atoi(pszPDFBands);
5633 2 : if (nBands != 3 && nBands != 4)
5634 : {
5635 0 : CPLError(CE_Warning, CPLE_NotSupported,
5636 : "Invalid value for GDAL_PDF_BANDS. Using 3 as a fallback");
5637 0 : nBands = 3;
5638 : }
5639 : }
5640 : #ifdef HAVE_PODOFO
5641 : if (bUseLib.test(PDFLIB_PODOFO) && nBands == 4 && poDS->m_aiTiles.empty())
5642 : {
5643 : CPLError(CE_Warning, CPLE_NotSupported,
5644 : "GDAL_PDF_BANDS=4 not supported when PDF driver is compiled "
5645 : "against Podofo. "
5646 : "Using 3 as a fallback");
5647 : nBands = 3;
5648 : }
5649 : #endif
5650 :
5651 : int iBand;
5652 1739 : for (iBand = 1; iBand <= nBands; iBand++)
5653 : {
5654 1359 : if (poDS->m_poImageObj != nullptr)
5655 0 : poDS->SetBand(iBand, new PDFImageRasterBand(poDS, iBand));
5656 : else
5657 1359 : poDS->SetBand(iBand, new PDFRasterBand(poDS, iBand, 0));
5658 : }
5659 :
5660 : /* Check if this is a raster-only PDF file and that we are */
5661 : /* opened in vector-only mode */
5662 870 : if ((poOpenInfo->nOpenFlags & GDAL_OF_RASTER) == 0 &&
5663 398 : (poOpenInfo->nOpenFlags & GDAL_OF_VECTOR) != 0 &&
5664 18 : !poDS->OpenVectorLayers(poPageDict))
5665 : {
5666 0 : CPLDebug("PDF", "This is a raster-only PDF dataset, "
5667 : "but it has been opened in vector-only mode");
5668 : /* Clear dirty flag */
5669 0 : poDS->m_bProjDirty = false;
5670 0 : poDS->m_bNeatLineDirty = false;
5671 0 : poDS->m_bInfoDirty = false;
5672 0 : poDS->m_bXMPDirty = false;
5673 0 : delete poDS;
5674 0 : return nullptr;
5675 : }
5676 :
5677 : /* -------------------------------------------------------------------- */
5678 : /* Initialize any PAM information. */
5679 : /* -------------------------------------------------------------------- */
5680 380 : if (bOpenSubdataset || bOpenSubdatasetImage)
5681 : {
5682 24 : poDS->SetPhysicalFilename(pszFilename);
5683 24 : poDS->SetSubdatasetName(osSubdatasetName.c_str());
5684 : }
5685 : else
5686 : {
5687 356 : poDS->SetDescription(poOpenInfo->pszFilename);
5688 : }
5689 :
5690 380 : poDS->TryLoadXML();
5691 :
5692 : /* -------------------------------------------------------------------- */
5693 : /* Support overviews. */
5694 : /* -------------------------------------------------------------------- */
5695 380 : if (!CSLFetchNameValue(poOpenInfo->papszOpenOptions, "@OPEN_FOR_OVERVIEW"))
5696 : {
5697 378 : poDS->oOvManager.Initialize(poDS, poOpenInfo->pszFilename);
5698 : }
5699 :
5700 : /* Clear dirty flag */
5701 380 : poDS->m_bProjDirty = false;
5702 380 : poDS->m_bNeatLineDirty = false;
5703 380 : poDS->m_bInfoDirty = false;
5704 380 : poDS->m_bXMPDirty = false;
5705 :
5706 380 : return (poDS);
5707 : }
5708 :
5709 : /************************************************************************/
5710 : /* ParseLGIDictObject() */
5711 : /************************************************************************/
5712 :
5713 0 : int PDFDataset::ParseLGIDictObject(GDALPDFObject *poLGIDict)
5714 : {
5715 0 : bool bOK = false;
5716 0 : if (poLGIDict->GetType() == PDFObjectType_Array)
5717 : {
5718 0 : GDALPDFArray *poArray = poLGIDict->GetArray();
5719 0 : int nArrayLength = poArray->GetLength();
5720 0 : int iMax = -1;
5721 0 : GDALPDFObject *poArrayElt = nullptr;
5722 0 : for (int i = 0; i < nArrayLength; i++)
5723 : {
5724 0 : if ((poArrayElt = poArray->Get(i)) == nullptr ||
5725 0 : poArrayElt->GetType() != PDFObjectType_Dictionary)
5726 : {
5727 0 : CPLError(CE_Failure, CPLE_AppDefined,
5728 : "LGIDict[%d] is not a dictionary", i);
5729 0 : return FALSE;
5730 : }
5731 :
5732 0 : int bIsBestCandidate = FALSE;
5733 0 : if (ParseLGIDictDictFirstPass(poArrayElt->GetDictionary(),
5734 0 : &bIsBestCandidate))
5735 : {
5736 0 : if (bIsBestCandidate || iMax < 0)
5737 0 : iMax = i;
5738 : }
5739 : }
5740 :
5741 0 : if (iMax < 0)
5742 0 : return FALSE;
5743 :
5744 0 : poArrayElt = poArray->Get(iMax);
5745 0 : bOK = CPL_TO_BOOL(
5746 0 : ParseLGIDictDictSecondPass(poArrayElt->GetDictionary()));
5747 : }
5748 0 : else if (poLGIDict->GetType() == PDFObjectType_Dictionary)
5749 : {
5750 0 : bOK = ParseLGIDictDictFirstPass(poLGIDict->GetDictionary()) &&
5751 0 : ParseLGIDictDictSecondPass(poLGIDict->GetDictionary());
5752 : }
5753 : else
5754 : {
5755 0 : CPLError(CE_Failure, CPLE_AppDefined, "LGIDict is of type %s",
5756 0 : poLGIDict->GetTypeName());
5757 : }
5758 :
5759 0 : return bOK;
5760 : }
5761 :
5762 : /************************************************************************/
5763 : /* Get() */
5764 : /************************************************************************/
5765 :
5766 20013 : static double Get(GDALPDFObject *poObj, int nIndice)
5767 : {
5768 20013 : if (poObj->GetType() == PDFObjectType_Array && nIndice >= 0)
5769 : {
5770 8892 : poObj = poObj->GetArray()->Get(nIndice);
5771 8892 : if (poObj == nullptr)
5772 0 : return 0;
5773 8892 : return Get(poObj);
5774 : }
5775 11121 : else if (poObj->GetType() == PDFObjectType_Int)
5776 8890 : return poObj->GetInt();
5777 2231 : else if (poObj->GetType() == PDFObjectType_Real)
5778 2231 : return poObj->GetReal();
5779 0 : else if (poObj->GetType() == PDFObjectType_String)
5780 : {
5781 0 : const char *pszStr = poObj->GetString().c_str();
5782 0 : size_t nLen = strlen(pszStr);
5783 0 : if (nLen == 0)
5784 0 : return 0;
5785 : /* cf Military_Installations_2008.pdf that has values like "96 0 0.0W"
5786 : */
5787 0 : char chLast = pszStr[nLen - 1];
5788 0 : if (chLast == 'W' || chLast == 'E' || chLast == 'N' || chLast == 'S')
5789 : {
5790 0 : double dfDeg = CPLAtof(pszStr);
5791 0 : double dfMin = 0.0;
5792 0 : double dfSec = 0.0;
5793 0 : const char *pszNext = strchr(pszStr, ' ');
5794 0 : if (pszNext)
5795 0 : pszNext++;
5796 0 : if (pszNext)
5797 0 : dfMin = CPLAtof(pszNext);
5798 0 : if (pszNext)
5799 0 : pszNext = strchr(pszNext, ' ');
5800 0 : if (pszNext)
5801 0 : pszNext++;
5802 0 : if (pszNext)
5803 0 : dfSec = CPLAtof(pszNext);
5804 0 : double dfVal = dfDeg + dfMin / 60 + dfSec / 3600;
5805 0 : if (chLast == 'W' || chLast == 'S')
5806 0 : return -dfVal;
5807 : else
5808 0 : return dfVal;
5809 : }
5810 0 : return CPLAtof(pszStr);
5811 : }
5812 : else
5813 : {
5814 0 : CPLError(CE_Warning, CPLE_AppDefined, "Unexpected type : %s",
5815 0 : poObj->GetTypeName());
5816 0 : return 0;
5817 : }
5818 : }
5819 :
5820 : /************************************************************************/
5821 : /* Get() */
5822 : /************************************************************************/
5823 :
5824 0 : static double Get(GDALPDFDictionary *poDict, const char *pszName)
5825 : {
5826 0 : GDALPDFObject *poObj = poDict->Get(pszName);
5827 0 : if (poObj != nullptr)
5828 0 : return Get(poObj);
5829 0 : CPLError(CE_Failure, CPLE_AppDefined, "Cannot find parameter %s", pszName);
5830 0 : return 0;
5831 : }
5832 :
5833 : /************************************************************************/
5834 : /* ParseLGIDictDictFirstPass() */
5835 : /************************************************************************/
5836 :
5837 0 : int PDFDataset::ParseLGIDictDictFirstPass(GDALPDFDictionary *poLGIDict,
5838 : int *pbIsBestCandidate)
5839 : {
5840 0 : if (pbIsBestCandidate)
5841 0 : *pbIsBestCandidate = FALSE;
5842 :
5843 0 : if (poLGIDict == nullptr)
5844 0 : return FALSE;
5845 :
5846 : /* -------------------------------------------------------------------- */
5847 : /* Extract Type attribute */
5848 : /* -------------------------------------------------------------------- */
5849 0 : GDALPDFObject *poType = poLGIDict->Get("Type");
5850 0 : if (poType == nullptr)
5851 : {
5852 0 : CPLError(CE_Failure, CPLE_AppDefined,
5853 : "Cannot find Type of LGIDict object");
5854 0 : return FALSE;
5855 : }
5856 :
5857 0 : if (poType->GetType() != PDFObjectType_Name)
5858 : {
5859 0 : CPLError(CE_Failure, CPLE_AppDefined,
5860 : "Invalid type for Type of LGIDict object");
5861 0 : return FALSE;
5862 : }
5863 :
5864 0 : if (strcmp(poType->GetName().c_str(), "LGIDict") != 0)
5865 : {
5866 0 : CPLError(CE_Failure, CPLE_AppDefined,
5867 : "Invalid value for Type of LGIDict object : %s",
5868 0 : poType->GetName().c_str());
5869 0 : return FALSE;
5870 : }
5871 :
5872 : /* -------------------------------------------------------------------- */
5873 : /* Extract Version attribute */
5874 : /* -------------------------------------------------------------------- */
5875 0 : GDALPDFObject *poVersion = poLGIDict->Get("Version");
5876 0 : if (poVersion == nullptr)
5877 : {
5878 0 : CPLError(CE_Failure, CPLE_AppDefined,
5879 : "Cannot find Version of LGIDict object");
5880 0 : return FALSE;
5881 : }
5882 :
5883 0 : if (poVersion->GetType() == PDFObjectType_String)
5884 : {
5885 : /* OGC best practice is 2.1 */
5886 0 : CPLDebug("PDF", "LGIDict Version : %s", poVersion->GetString().c_str());
5887 : }
5888 0 : else if (poVersion->GetType() == PDFObjectType_Int)
5889 : {
5890 : /* Old TerraGo is 2 */
5891 0 : CPLDebug("PDF", "LGIDict Version : %d", poVersion->GetInt());
5892 : }
5893 :
5894 : /* USGS PDF maps have several LGIDict. Keep the one whose description */
5895 : /* is "Map Layers" by default */
5896 : const char *pszNeatlineToSelect =
5897 0 : GetOption(papszOpenOptions, "NEATLINE", "Map Layers");
5898 :
5899 : /* -------------------------------------------------------------------- */
5900 : /* Extract Neatline attribute */
5901 : /* -------------------------------------------------------------------- */
5902 0 : GDALPDFObject *poNeatline = poLGIDict->Get("Neatline");
5903 0 : if (poNeatline != nullptr && poNeatline->GetType() == PDFObjectType_Array)
5904 : {
5905 0 : int nLength = poNeatline->GetArray()->GetLength();
5906 0 : if ((nLength % 2) != 0 || nLength < 4)
5907 : {
5908 0 : CPLError(CE_Failure, CPLE_AppDefined,
5909 : "Invalid length for Neatline");
5910 0 : return FALSE;
5911 : }
5912 :
5913 0 : GDALPDFObject *poDescription = poLGIDict->Get("Description");
5914 0 : bool bIsAskedNeatline = false;
5915 0 : if (poDescription != nullptr &&
5916 0 : poDescription->GetType() == PDFObjectType_String)
5917 : {
5918 0 : CPLDebug("PDF", "Description = %s",
5919 0 : poDescription->GetString().c_str());
5920 :
5921 0 : if (EQUAL(poDescription->GetString().c_str(), pszNeatlineToSelect))
5922 : {
5923 0 : m_dfMaxArea = 1e300;
5924 0 : bIsAskedNeatline = true;
5925 : }
5926 : }
5927 :
5928 0 : if (!bIsAskedNeatline)
5929 : {
5930 0 : double dfMinX = 0.0;
5931 0 : double dfMinY = 0.0;
5932 0 : double dfMaxX = 0.0;
5933 0 : double dfMaxY = 0.0;
5934 0 : for (int i = 0; i < nLength; i += 2)
5935 : {
5936 0 : double dfX = Get(poNeatline, i);
5937 0 : double dfY = Get(poNeatline, i + 1);
5938 0 : if (i == 0 || dfX < dfMinX)
5939 0 : dfMinX = dfX;
5940 0 : if (i == 0 || dfY < dfMinY)
5941 0 : dfMinY = dfY;
5942 0 : if (i == 0 || dfX > dfMaxX)
5943 0 : dfMaxX = dfX;
5944 0 : if (i == 0 || dfY > dfMaxY)
5945 0 : dfMaxY = dfY;
5946 : }
5947 0 : double dfArea = (dfMaxX - dfMinX) * (dfMaxY - dfMinY);
5948 0 : if (dfArea < m_dfMaxArea)
5949 : {
5950 0 : CPLDebug("PDF", "Not the largest neatline. Skipping it");
5951 0 : return TRUE;
5952 : }
5953 :
5954 0 : CPLDebug("PDF", "This is the largest neatline for now");
5955 0 : m_dfMaxArea = dfArea;
5956 : }
5957 : else
5958 0 : CPLDebug("PDF", "The \"%s\" registration will be selected",
5959 : pszNeatlineToSelect);
5960 :
5961 0 : if (pbIsBestCandidate)
5962 0 : *pbIsBestCandidate = TRUE;
5963 :
5964 0 : delete m_poNeatLine;
5965 0 : m_poNeatLine = new OGRPolygon();
5966 0 : OGRLinearRing *poRing = new OGRLinearRing();
5967 0 : if (nLength == 4)
5968 : {
5969 : /* 2 points only ? They are the bounding box */
5970 0 : double dfX1 = Get(poNeatline, 0);
5971 0 : double dfY1 = Get(poNeatline, 1);
5972 0 : double dfX2 = Get(poNeatline, 2);
5973 0 : double dfY2 = Get(poNeatline, 3);
5974 0 : poRing->addPoint(dfX1, dfY1);
5975 0 : poRing->addPoint(dfX2, dfY1);
5976 0 : poRing->addPoint(dfX2, dfY2);
5977 0 : poRing->addPoint(dfX1, dfY2);
5978 : }
5979 : else
5980 : {
5981 0 : for (int i = 0; i < nLength; i += 2)
5982 : {
5983 0 : double dfX = Get(poNeatline, i);
5984 0 : double dfY = Get(poNeatline, i + 1);
5985 0 : poRing->addPoint(dfX, dfY);
5986 : }
5987 : }
5988 0 : poRing->closeRings();
5989 0 : m_poNeatLine->addRingDirectly(poRing);
5990 : }
5991 :
5992 0 : return TRUE;
5993 : }
5994 :
5995 : /************************************************************************/
5996 : /* ParseLGIDictDictSecondPass() */
5997 : /************************************************************************/
5998 :
5999 0 : int PDFDataset::ParseLGIDictDictSecondPass(GDALPDFDictionary *poLGIDict)
6000 : {
6001 : int i;
6002 :
6003 : /* -------------------------------------------------------------------- */
6004 : /* Extract Description attribute */
6005 : /* -------------------------------------------------------------------- */
6006 0 : GDALPDFObject *poDescription = poLGIDict->Get("Description");
6007 0 : if (poDescription != nullptr &&
6008 0 : poDescription->GetType() == PDFObjectType_String)
6009 : {
6010 0 : CPLDebug("PDF", "Description = %s", poDescription->GetString().c_str());
6011 : }
6012 :
6013 : /* -------------------------------------------------------------------- */
6014 : /* Extract CTM attribute */
6015 : /* -------------------------------------------------------------------- */
6016 0 : GDALPDFObject *poCTM = poLGIDict->Get("CTM");
6017 0 : m_bHasCTM = false;
6018 0 : if (poCTM != nullptr && poCTM->GetType() == PDFObjectType_Array &&
6019 0 : CPLTestBool(CPLGetConfigOption("PDF_USE_CTM", "YES")))
6020 : {
6021 0 : int nLength = poCTM->GetArray()->GetLength();
6022 0 : if (nLength != 6)
6023 : {
6024 0 : CPLError(CE_Failure, CPLE_AppDefined, "Invalid length for CTM");
6025 0 : return FALSE;
6026 : }
6027 :
6028 0 : m_bHasCTM = true;
6029 0 : for (i = 0; i < nLength; i++)
6030 : {
6031 0 : m_adfCTM[i] = Get(poCTM, i);
6032 : /* Nullify rotation terms that are significantly smaller than */
6033 : /* scaling terms. */
6034 0 : if ((i == 1 || i == 2) &&
6035 0 : fabs(m_adfCTM[i]) < fabs(m_adfCTM[0]) * 1e-10)
6036 0 : m_adfCTM[i] = 0;
6037 0 : CPLDebug("PDF", "CTM[%d] = %.16g", i, m_adfCTM[i]);
6038 : }
6039 : }
6040 :
6041 : /* -------------------------------------------------------------------- */
6042 : /* Extract Registration attribute */
6043 : /* -------------------------------------------------------------------- */
6044 0 : GDALPDFObject *poRegistration = poLGIDict->Get("Registration");
6045 0 : if (poRegistration != nullptr &&
6046 0 : poRegistration->GetType() == PDFObjectType_Array)
6047 : {
6048 0 : GDALPDFArray *poRegistrationArray = poRegistration->GetArray();
6049 0 : int nLength = poRegistrationArray->GetLength();
6050 0 : if (nLength > 4 || (!m_bHasCTM && nLength >= 2) ||
6051 0 : CPLTestBool(CPLGetConfigOption("PDF_REPORT_GCPS", "NO")))
6052 : {
6053 0 : m_nGCPCount = 0;
6054 0 : m_pasGCPList =
6055 0 : static_cast<GDAL_GCP *>(CPLCalloc(sizeof(GDAL_GCP), nLength));
6056 :
6057 0 : for (i = 0; i < nLength; i++)
6058 : {
6059 0 : GDALPDFObject *poGCP = poRegistrationArray->Get(i);
6060 0 : if (poGCP != nullptr &&
6061 0 : poGCP->GetType() == PDFObjectType_Array &&
6062 0 : poGCP->GetArray()->GetLength() == 4)
6063 : {
6064 0 : double dfUserX = Get(poGCP, 0);
6065 0 : double dfUserY = Get(poGCP, 1);
6066 0 : double dfX = Get(poGCP, 2);
6067 0 : double dfY = Get(poGCP, 3);
6068 0 : CPLDebug("PDF", "GCP[%d].userX = %.16g", i, dfUserX);
6069 0 : CPLDebug("PDF", "GCP[%d].userY = %.16g", i, dfUserY);
6070 0 : CPLDebug("PDF", "GCP[%d].x = %.16g", i, dfX);
6071 0 : CPLDebug("PDF", "GCP[%d].y = %.16g", i, dfY);
6072 :
6073 : char szID[32];
6074 0 : snprintf(szID, sizeof(szID), "%d", m_nGCPCount + 1);
6075 0 : m_pasGCPList[m_nGCPCount].pszId = CPLStrdup(szID);
6076 0 : m_pasGCPList[m_nGCPCount].pszInfo = CPLStrdup("");
6077 0 : m_pasGCPList[m_nGCPCount].dfGCPPixel = dfUserX;
6078 0 : m_pasGCPList[m_nGCPCount].dfGCPLine = dfUserY;
6079 0 : m_pasGCPList[m_nGCPCount].dfGCPX = dfX;
6080 0 : m_pasGCPList[m_nGCPCount].dfGCPY = dfY;
6081 0 : m_nGCPCount++;
6082 : }
6083 : }
6084 :
6085 0 : if (m_nGCPCount == 0)
6086 : {
6087 0 : CPLFree(m_pasGCPList);
6088 0 : m_pasGCPList = nullptr;
6089 : }
6090 : }
6091 : }
6092 :
6093 0 : if (!m_bHasCTM && m_nGCPCount == 0)
6094 : {
6095 0 : CPLDebug("PDF", "Neither CTM nor Registration found");
6096 0 : return FALSE;
6097 : }
6098 :
6099 : /* -------------------------------------------------------------------- */
6100 : /* Extract Projection attribute */
6101 : /* -------------------------------------------------------------------- */
6102 0 : GDALPDFObject *poProjection = poLGIDict->Get("Projection");
6103 0 : if (poProjection == nullptr ||
6104 0 : poProjection->GetType() != PDFObjectType_Dictionary)
6105 : {
6106 0 : CPLError(CE_Failure, CPLE_AppDefined, "Could not find Projection");
6107 0 : return FALSE;
6108 : }
6109 :
6110 0 : return ParseProjDict(poProjection->GetDictionary());
6111 : }
6112 :
6113 : /************************************************************************/
6114 : /* ParseProjDict() */
6115 : /************************************************************************/
6116 :
6117 0 : int PDFDataset::ParseProjDict(GDALPDFDictionary *poProjDict)
6118 : {
6119 0 : if (poProjDict == nullptr)
6120 0 : return FALSE;
6121 0 : OGRSpatialReference oSRS;
6122 0 : oSRS.SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER);
6123 :
6124 : /* -------------------------------------------------------------------- */
6125 : /* Extract WKT attribute (GDAL extension) */
6126 : /* -------------------------------------------------------------------- */
6127 0 : GDALPDFObject *poWKT = poProjDict->Get("WKT");
6128 0 : if (poWKT != nullptr && poWKT->GetType() == PDFObjectType_String &&
6129 0 : CPLTestBool(CPLGetConfigOption("GDAL_PDF_OGC_BP_READ_WKT", "TRUE")))
6130 : {
6131 0 : CPLDebug("PDF", "Found WKT attribute (GDAL extension). Using it");
6132 0 : const char *pszWKTRead = poWKT->GetString().c_str();
6133 0 : if (pszWKTRead[0] != 0)
6134 0 : m_oSRS.importFromWkt(pszWKTRead);
6135 0 : return TRUE;
6136 : }
6137 :
6138 : /* -------------------------------------------------------------------- */
6139 : /* Extract Type attribute */
6140 : /* -------------------------------------------------------------------- */
6141 0 : GDALPDFObject *poType = poProjDict->Get("Type");
6142 0 : if (poType == nullptr)
6143 : {
6144 0 : CPLError(CE_Failure, CPLE_AppDefined,
6145 : "Cannot find Type of Projection object");
6146 0 : return FALSE;
6147 : }
6148 :
6149 0 : if (poType->GetType() != PDFObjectType_Name)
6150 : {
6151 0 : CPLError(CE_Failure, CPLE_AppDefined,
6152 : "Invalid type for Type of Projection object");
6153 0 : return FALSE;
6154 : }
6155 :
6156 0 : if (strcmp(poType->GetName().c_str(), "Projection") != 0)
6157 : {
6158 0 : CPLError(CE_Failure, CPLE_AppDefined,
6159 : "Invalid value for Type of Projection object : %s",
6160 0 : poType->GetName().c_str());
6161 0 : return FALSE;
6162 : }
6163 :
6164 : /* -------------------------------------------------------------------- */
6165 : /* Extract Datum attribute */
6166 : /* -------------------------------------------------------------------- */
6167 0 : int bIsWGS84 = FALSE;
6168 0 : int bIsNAD83 = FALSE;
6169 : /* int bIsNAD27 = FALSE; */
6170 :
6171 0 : GDALPDFObject *poDatum = poProjDict->Get("Datum");
6172 0 : if (poDatum != nullptr)
6173 : {
6174 0 : if (poDatum->GetType() == PDFObjectType_String)
6175 : {
6176 : /* Using Annex A of
6177 : * http://portal.opengeospatial.org/files/?artifact_id=40537 */
6178 0 : const char *pszDatum = poDatum->GetString().c_str();
6179 0 : CPLDebug("PDF", "Datum = %s", pszDatum);
6180 0 : if (EQUAL(pszDatum, "WE") || EQUAL(pszDatum, "WGE"))
6181 : {
6182 0 : bIsWGS84 = TRUE;
6183 0 : oSRS.SetWellKnownGeogCS("WGS84");
6184 : }
6185 0 : else if (EQUAL(pszDatum, "NAR") || STARTS_WITH_CI(pszDatum, "NAR-"))
6186 : {
6187 0 : bIsNAD83 = TRUE;
6188 0 : oSRS.SetWellKnownGeogCS("NAD83");
6189 : }
6190 0 : else if (EQUAL(pszDatum, "NAS") || STARTS_WITH_CI(pszDatum, "NAS-"))
6191 : {
6192 : /* bIsNAD27 = TRUE; */
6193 0 : oSRS.SetWellKnownGeogCS("NAD27");
6194 : }
6195 0 : else if (EQUAL(pszDatum, "HEN")) /* HERAT North, Afghanistan */
6196 : {
6197 0 : oSRS.SetGeogCS("unknown" /*const char * pszGeogName*/,
6198 : "unknown" /*const char * pszDatumName */,
6199 : "International 1924", 6378388, 297);
6200 0 : oSRS.SetTOWGS84(-333, -222, 114);
6201 : }
6202 0 : else if (EQUAL(pszDatum, "ING-A")) /* INDIAN 1960, Vietnam 16N */
6203 : {
6204 0 : oSRS.importFromEPSG(4131);
6205 : }
6206 0 : else if (EQUAL(pszDatum, "GDS")) /* Geocentric Datum of Australia */
6207 : {
6208 0 : oSRS.importFromEPSG(4283);
6209 : }
6210 0 : else if (STARTS_WITH_CI(pszDatum, "OHA-")) /* Old Hawaiian */
6211 : {
6212 0 : oSRS.importFromEPSG(4135); /* matches OHA-M (Mean) */
6213 0 : if (!EQUAL(pszDatum, "OHA-M"))
6214 : {
6215 0 : CPLError(CE_Warning, CPLE_AppDefined,
6216 : "Using OHA-M (Old Hawaiian Mean) definition for "
6217 : "%s. Potential issue with datum shift parameters",
6218 : pszDatum);
6219 0 : OGR_SRSNode *poNode = oSRS.GetRoot();
6220 0 : int iChild = poNode->FindChild("AUTHORITY");
6221 0 : if (iChild != -1)
6222 0 : poNode->DestroyChild(iChild);
6223 0 : iChild = poNode->FindChild("DATUM");
6224 0 : if (iChild != -1)
6225 : {
6226 0 : poNode = poNode->GetChild(iChild);
6227 0 : iChild = poNode->FindChild("AUTHORITY");
6228 0 : if (iChild != -1)
6229 0 : poNode->DestroyChild(iChild);
6230 : }
6231 : }
6232 : }
6233 : else
6234 : {
6235 0 : CPLError(CE_Warning, CPLE_AppDefined,
6236 : "Unhandled (yet) value for Datum : %s. Defaulting to "
6237 : "WGS84...",
6238 : pszDatum);
6239 0 : oSRS.SetGeogCS("unknown" /*const char * pszGeogName*/,
6240 : "unknown" /*const char * pszDatumName */,
6241 : "unknown", 6378137, 298.257223563);
6242 : }
6243 : }
6244 0 : else if (poDatum->GetType() == PDFObjectType_Dictionary)
6245 : {
6246 0 : GDALPDFDictionary *poDatumDict = poDatum->GetDictionary();
6247 :
6248 0 : GDALPDFObject *poDatumDescription = poDatumDict->Get("Description");
6249 0 : const char *pszDatumDescription = "unknown";
6250 0 : if (poDatumDescription != nullptr &&
6251 0 : poDatumDescription->GetType() == PDFObjectType_String)
6252 0 : pszDatumDescription = poDatumDescription->GetString().c_str();
6253 0 : CPLDebug("PDF", "Datum.Description = %s", pszDatumDescription);
6254 :
6255 0 : GDALPDFObject *poEllipsoid = poDatumDict->Get("Ellipsoid");
6256 0 : if (poEllipsoid == nullptr ||
6257 0 : !(poEllipsoid->GetType() == PDFObjectType_String ||
6258 0 : poEllipsoid->GetType() == PDFObjectType_Dictionary))
6259 : {
6260 0 : CPLError(
6261 : CE_Warning, CPLE_AppDefined,
6262 : "Cannot find Ellipsoid in Datum. Defaulting to WGS84...");
6263 0 : oSRS.SetGeogCS("unknown", pszDatumDescription, "unknown",
6264 : 6378137, 298.257223563);
6265 : }
6266 0 : else if (poEllipsoid->GetType() == PDFObjectType_String)
6267 : {
6268 0 : const char *pszEllipsoid = poEllipsoid->GetString().c_str();
6269 0 : CPLDebug("PDF", "Datum.Ellipsoid = %s", pszEllipsoid);
6270 0 : if (EQUAL(pszEllipsoid, "WE"))
6271 : {
6272 0 : oSRS.SetGeogCS("unknown", pszDatumDescription, "WGS 84",
6273 : 6378137, 298.257223563);
6274 : }
6275 : else
6276 : {
6277 0 : CPLError(CE_Warning, CPLE_AppDefined,
6278 : "Unhandled (yet) value for Ellipsoid : %s. "
6279 : "Defaulting to WGS84...",
6280 : pszEllipsoid);
6281 0 : oSRS.SetGeogCS("unknown", pszDatumDescription, pszEllipsoid,
6282 : 6378137, 298.257223563);
6283 : }
6284 : }
6285 : else // if (poEllipsoid->GetType() == PDFObjectType_Dictionary)
6286 : {
6287 : GDALPDFDictionary *poEllipsoidDict =
6288 0 : poEllipsoid->GetDictionary();
6289 :
6290 : GDALPDFObject *poEllipsoidDescription =
6291 0 : poEllipsoidDict->Get("Description");
6292 0 : const char *pszEllipsoidDescription = "unknown";
6293 0 : if (poEllipsoidDescription != nullptr &&
6294 0 : poEllipsoidDescription->GetType() == PDFObjectType_String)
6295 : pszEllipsoidDescription =
6296 0 : poEllipsoidDescription->GetString().c_str();
6297 0 : CPLDebug("PDF", "Datum.Ellipsoid.Description = %s",
6298 : pszEllipsoidDescription);
6299 :
6300 0 : double dfSemiMajor = Get(poEllipsoidDict, "SemiMajorAxis");
6301 0 : CPLDebug("PDF", "Datum.Ellipsoid.SemiMajorAxis = %.16g",
6302 : dfSemiMajor);
6303 0 : double dfInvFlattening = -1.0;
6304 :
6305 0 : if (poEllipsoidDict->Get("InvFlattening"))
6306 : {
6307 0 : dfInvFlattening = Get(poEllipsoidDict, "InvFlattening");
6308 0 : CPLDebug("PDF", "Datum.Ellipsoid.InvFlattening = %.16g",
6309 : dfInvFlattening);
6310 : }
6311 0 : else if (poEllipsoidDict->Get("SemiMinorAxis"))
6312 : {
6313 0 : double dfSemiMinor = Get(poEllipsoidDict, "SemiMinorAxis");
6314 0 : CPLDebug("PDF", "Datum.Ellipsoid.SemiMinorAxis = %.16g",
6315 : dfSemiMinor);
6316 : dfInvFlattening =
6317 0 : OSRCalcInvFlattening(dfSemiMajor, dfSemiMinor);
6318 : }
6319 :
6320 0 : if (dfSemiMajor != 0.0 && dfInvFlattening != -1.0)
6321 : {
6322 0 : oSRS.SetGeogCS("unknown", pszDatumDescription,
6323 : pszEllipsoidDescription, dfSemiMajor,
6324 : dfInvFlattening);
6325 : }
6326 : else
6327 : {
6328 0 : CPLError(
6329 : CE_Warning, CPLE_AppDefined,
6330 : "Invalid Ellipsoid object. Defaulting to WGS84...");
6331 0 : oSRS.SetGeogCS("unknown", pszDatumDescription,
6332 : pszEllipsoidDescription, 6378137,
6333 : 298.257223563);
6334 : }
6335 : }
6336 :
6337 0 : GDALPDFObject *poTOWGS84 = poDatumDict->Get("ToWGS84");
6338 0 : if (poTOWGS84 != nullptr &&
6339 0 : poTOWGS84->GetType() == PDFObjectType_Dictionary)
6340 : {
6341 0 : GDALPDFDictionary *poTOWGS84Dict = poTOWGS84->GetDictionary();
6342 0 : double dx = Get(poTOWGS84Dict, "dx");
6343 0 : double dy = Get(poTOWGS84Dict, "dy");
6344 0 : double dz = Get(poTOWGS84Dict, "dz");
6345 0 : if (poTOWGS84Dict->Get("rx") && poTOWGS84Dict->Get("ry") &&
6346 0 : poTOWGS84Dict->Get("rz") && poTOWGS84Dict->Get("sf"))
6347 : {
6348 0 : double rx = Get(poTOWGS84Dict, "rx");
6349 0 : double ry = Get(poTOWGS84Dict, "ry");
6350 0 : double rz = Get(poTOWGS84Dict, "rz");
6351 0 : double sf = Get(poTOWGS84Dict, "sf");
6352 0 : oSRS.SetTOWGS84(dx, dy, dz, rx, ry, rz, sf);
6353 : }
6354 : else
6355 : {
6356 0 : oSRS.SetTOWGS84(dx, dy, dz);
6357 : }
6358 : }
6359 : }
6360 : }
6361 :
6362 : /* -------------------------------------------------------------------- */
6363 : /* Extract Hemisphere attribute */
6364 : /* -------------------------------------------------------------------- */
6365 0 : CPLString osHemisphere;
6366 0 : GDALPDFObject *poHemisphere = poProjDict->Get("Hemisphere");
6367 0 : if (poHemisphere != nullptr &&
6368 0 : poHemisphere->GetType() == PDFObjectType_String)
6369 : {
6370 0 : osHemisphere = poHemisphere->GetString();
6371 : }
6372 :
6373 : /* -------------------------------------------------------------------- */
6374 : /* Extract ProjectionType attribute */
6375 : /* -------------------------------------------------------------------- */
6376 0 : GDALPDFObject *poProjectionType = poProjDict->Get("ProjectionType");
6377 0 : if (poProjectionType == nullptr ||
6378 0 : poProjectionType->GetType() != PDFObjectType_String)
6379 : {
6380 0 : CPLError(CE_Failure, CPLE_AppDefined,
6381 : "Cannot find ProjectionType of Projection object");
6382 0 : return FALSE;
6383 : }
6384 0 : CPLString osProjectionType(poProjectionType->GetString());
6385 0 : CPLDebug("PDF", "Projection.ProjectionType = %s", osProjectionType.c_str());
6386 :
6387 : /* Unhandled: NONE, GEODETIC */
6388 :
6389 0 : if (EQUAL(osProjectionType, "GEOGRAPHIC"))
6390 : {
6391 : /* Nothing to do */
6392 : }
6393 :
6394 : /* Unhandled: LOCAL CARTESIAN, MG (MGRS) */
6395 :
6396 0 : else if (EQUAL(osProjectionType, "UT")) /* UTM */
6397 : {
6398 0 : const double dfZone = Get(poProjDict, "Zone");
6399 0 : if (dfZone >= 1 && dfZone <= 60)
6400 : {
6401 0 : int nZone = static_cast<int>(dfZone);
6402 0 : int bNorth = EQUAL(osHemisphere, "N");
6403 0 : if (bIsWGS84)
6404 0 : oSRS.importFromEPSG(((bNorth) ? 32600 : 32700) + nZone);
6405 : else
6406 0 : oSRS.SetUTM(nZone, bNorth);
6407 : }
6408 : }
6409 :
6410 0 : else if (EQUAL(osProjectionType,
6411 : "UP")) /* Universal Polar Stereographic (UPS) */
6412 : {
6413 0 : int bNorth = EQUAL(osHemisphere, "N");
6414 0 : if (bIsWGS84)
6415 0 : oSRS.importFromEPSG((bNorth) ? 32661 : 32761);
6416 : else
6417 0 : oSRS.SetPS((bNorth) ? 90 : -90, 0, 0.994, 200000, 200000);
6418 : }
6419 :
6420 0 : else if (EQUAL(osProjectionType, "SPCS")) /* State Plane */
6421 : {
6422 0 : const double dfZone = Get(poProjDict, "Zone");
6423 0 : if (dfZone >= 0 && dfZone <= INT_MAX)
6424 : {
6425 0 : int nZone = static_cast<int>(dfZone);
6426 0 : oSRS.SetStatePlane(nZone, bIsNAD83);
6427 : }
6428 : }
6429 :
6430 0 : else if (EQUAL(osProjectionType, "AC")) /* Albers Equal Area Conic */
6431 : {
6432 0 : double dfStdP1 = Get(poProjDict, "StandardParallelOne");
6433 0 : double dfStdP2 = Get(poProjDict, "StandardParallelTwo");
6434 0 : double dfCenterLat = Get(poProjDict, "OriginLatitude");
6435 0 : double dfCenterLong = Get(poProjDict, "CentralMeridian");
6436 0 : double dfFalseEasting = Get(poProjDict, "FalseEasting");
6437 0 : double dfFalseNorthing = Get(poProjDict, "FalseNorthing");
6438 0 : oSRS.SetACEA(dfStdP1, dfStdP2, dfCenterLat, dfCenterLong,
6439 : dfFalseEasting, dfFalseNorthing);
6440 : }
6441 :
6442 0 : else if (EQUAL(osProjectionType, "AL")) /* Azimuthal Equidistant */
6443 : {
6444 0 : double dfCenterLat = Get(poProjDict, "OriginLatitude");
6445 0 : double dfCenterLong = Get(poProjDict, "CentralMeridian");
6446 0 : double dfFalseEasting = Get(poProjDict, "FalseEasting");
6447 0 : double dfFalseNorthing = Get(poProjDict, "FalseNorthing");
6448 0 : oSRS.SetAE(dfCenterLat, dfCenterLong, dfFalseEasting, dfFalseNorthing);
6449 : }
6450 :
6451 0 : else if (EQUAL(osProjectionType, "BF")) /* Bonne */
6452 : {
6453 0 : double dfStdP1 = Get(poProjDict, "OriginLatitude");
6454 0 : double dfCentralMeridian = Get(poProjDict, "CentralMeridian");
6455 0 : double dfFalseEasting = Get(poProjDict, "FalseEasting");
6456 0 : double dfFalseNorthing = Get(poProjDict, "FalseNorthing");
6457 0 : oSRS.SetBonne(dfStdP1, dfCentralMeridian, dfFalseEasting,
6458 : dfFalseNorthing);
6459 : }
6460 :
6461 0 : else if (EQUAL(osProjectionType, "CS")) /* Cassini */
6462 : {
6463 0 : double dfCenterLat = Get(poProjDict, "OriginLatitude");
6464 0 : double dfCenterLong = Get(poProjDict, "CentralMeridian");
6465 0 : double dfFalseEasting = Get(poProjDict, "FalseEasting");
6466 0 : double dfFalseNorthing = Get(poProjDict, "FalseNorthing");
6467 0 : oSRS.SetCS(dfCenterLat, dfCenterLong, dfFalseEasting, dfFalseNorthing);
6468 : }
6469 :
6470 0 : else if (EQUAL(osProjectionType, "LI")) /* Cylindrical Equal Area */
6471 : {
6472 0 : double dfStdP1 = Get(poProjDict, "OriginLatitude");
6473 0 : double dfCentralMeridian = Get(poProjDict, "CentralMeridian");
6474 0 : double dfFalseEasting = Get(poProjDict, "FalseEasting");
6475 0 : double dfFalseNorthing = Get(poProjDict, "FalseNorthing");
6476 0 : oSRS.SetCEA(dfStdP1, dfCentralMeridian, dfFalseEasting,
6477 : dfFalseNorthing);
6478 : }
6479 :
6480 0 : else if (EQUAL(osProjectionType, "EF")) /* Eckert IV */
6481 : {
6482 0 : double dfCentralMeridian = Get(poProjDict, "CentralMeridian");
6483 0 : double dfFalseEasting = Get(poProjDict, "FalseEasting");
6484 0 : double dfFalseNorthing = Get(poProjDict, "FalseNorthing");
6485 0 : oSRS.SetEckertIV(dfCentralMeridian, dfFalseEasting, dfFalseNorthing);
6486 : }
6487 :
6488 0 : else if (EQUAL(osProjectionType, "ED")) /* Eckert VI */
6489 : {
6490 0 : double dfCentralMeridian = Get(poProjDict, "CentralMeridian");
6491 0 : double dfFalseEasting = Get(poProjDict, "FalseEasting");
6492 0 : double dfFalseNorthing = Get(poProjDict, "FalseNorthing");
6493 0 : oSRS.SetEckertVI(dfCentralMeridian, dfFalseEasting, dfFalseNorthing);
6494 : }
6495 :
6496 0 : else if (EQUAL(osProjectionType, "CP")) /* Equidistant Cylindrical */
6497 : {
6498 0 : double dfCenterLat = Get(poProjDict, "StandardParallel");
6499 0 : double dfCenterLong = Get(poProjDict, "CentralMeridian");
6500 0 : double dfFalseEasting = Get(poProjDict, "FalseEasting");
6501 0 : double dfFalseNorthing = Get(poProjDict, "FalseNorthing");
6502 0 : oSRS.SetEquirectangular(dfCenterLat, dfCenterLong, dfFalseEasting,
6503 : dfFalseNorthing);
6504 : }
6505 :
6506 0 : else if (EQUAL(osProjectionType, "GN")) /* Gnomonic */
6507 : {
6508 0 : double dfCenterLat = Get(poProjDict, "OriginLatitude");
6509 0 : double dfCenterLong = Get(poProjDict, "CentralMeridian");
6510 0 : double dfFalseEasting = Get(poProjDict, "FalseEasting");
6511 0 : double dfFalseNorthing = Get(poProjDict, "FalseNorthing");
6512 0 : oSRS.SetGnomonic(dfCenterLat, dfCenterLong, dfFalseEasting,
6513 : dfFalseNorthing);
6514 : }
6515 :
6516 0 : else if (EQUAL(osProjectionType, "LE")) /* Lambert Conformal Conic */
6517 : {
6518 0 : double dfStdP1 = Get(poProjDict, "StandardParallelOne");
6519 0 : double dfStdP2 = Get(poProjDict, "StandardParallelTwo");
6520 0 : double dfCenterLat = Get(poProjDict, "OriginLatitude");
6521 0 : double dfCenterLong = Get(poProjDict, "CentralMeridian");
6522 0 : double dfFalseEasting = Get(poProjDict, "FalseEasting");
6523 0 : double dfFalseNorthing = Get(poProjDict, "FalseNorthing");
6524 0 : oSRS.SetLCC(dfStdP1, dfStdP2, dfCenterLat, dfCenterLong, dfFalseEasting,
6525 : dfFalseNorthing);
6526 : }
6527 :
6528 0 : else if (EQUAL(osProjectionType, "MC")) /* Mercator */
6529 : {
6530 : #ifdef not_supported
6531 : if (poProjDict->Get("StandardParallelOne") == nullptr)
6532 : #endif
6533 : {
6534 0 : double dfCenterLat = Get(poProjDict, "OriginLatitude");
6535 0 : double dfCenterLong = Get(poProjDict, "CentralMeridian");
6536 0 : double dfScale = Get(poProjDict, "ScaleFactor");
6537 0 : double dfFalseEasting = Get(poProjDict, "FalseEasting");
6538 0 : double dfFalseNorthing = Get(poProjDict, "FalseNorthing");
6539 0 : oSRS.SetMercator(dfCenterLat, dfCenterLong, dfScale, dfFalseEasting,
6540 : dfFalseNorthing);
6541 : }
6542 : #ifdef not_supported
6543 : else
6544 : {
6545 : double dfStdP1 = Get(poProjDict, "StandardParallelOne");
6546 : double dfCenterLat = poProjDict->Get("OriginLatitude")
6547 : ? Get(poProjDict, "OriginLatitude")
6548 : : 0;
6549 : double dfCenterLong = Get(poProjDict, "CentralMeridian");
6550 : double dfFalseEasting = Get(poProjDict, "FalseEasting");
6551 : double dfFalseNorthing = Get(poProjDict, "FalseNorthing");
6552 : oSRS.SetMercator2SP(dfStdP1, dfCenterLat, dfCenterLong,
6553 : dfFalseEasting, dfFalseNorthing);
6554 : }
6555 : #endif
6556 : }
6557 :
6558 0 : else if (EQUAL(osProjectionType, "MH")) /* Miller Cylindrical */
6559 : {
6560 0 : double dfCenterLat = 0 /* ? */;
6561 0 : double dfCenterLong = Get(poProjDict, "CentralMeridian");
6562 0 : double dfFalseEasting = Get(poProjDict, "FalseEasting");
6563 0 : double dfFalseNorthing = Get(poProjDict, "FalseNorthing");
6564 0 : oSRS.SetMC(dfCenterLat, dfCenterLong, dfFalseEasting, dfFalseNorthing);
6565 : }
6566 :
6567 0 : else if (EQUAL(osProjectionType, "MP")) /* Mollweide */
6568 : {
6569 0 : double dfCentralMeridian = Get(poProjDict, "CentralMeridian");
6570 0 : double dfFalseEasting = Get(poProjDict, "FalseEasting");
6571 0 : double dfFalseNorthing = Get(poProjDict, "FalseNorthing");
6572 0 : oSRS.SetMollweide(dfCentralMeridian, dfFalseEasting, dfFalseNorthing);
6573 : }
6574 :
6575 : /* Unhandled: "NY" : Ney's (Modified Lambert Conformal Conic) */
6576 :
6577 0 : else if (EQUAL(osProjectionType, "NT")) /* New Zealand Map Grid */
6578 : {
6579 : /* No parameter specified in the PDF, so let's take the ones of
6580 : * EPSG:27200 */
6581 0 : double dfCenterLat = -41;
6582 0 : double dfCenterLong = 173;
6583 0 : double dfFalseEasting = 2510000;
6584 0 : double dfFalseNorthing = 6023150;
6585 0 : oSRS.SetNZMG(dfCenterLat, dfCenterLong, dfFalseEasting,
6586 : dfFalseNorthing);
6587 : }
6588 :
6589 0 : else if (EQUAL(osProjectionType, "OC")) /* Oblique Mercator */
6590 : {
6591 0 : double dfCenterLat = Get(poProjDict, "OriginLatitude");
6592 0 : double dfLat1 = Get(poProjDict, "LatitudeOne");
6593 0 : double dfLong1 = Get(poProjDict, "LongitudeOne");
6594 0 : double dfLat2 = Get(poProjDict, "LatitudeTwo");
6595 0 : double dfLong2 = Get(poProjDict, "LongitudeTwo");
6596 0 : double dfScale = Get(poProjDict, "ScaleFactor");
6597 0 : double dfFalseEasting = Get(poProjDict, "FalseEasting");
6598 0 : double dfFalseNorthing = Get(poProjDict, "FalseNorthing");
6599 0 : oSRS.SetHOM2PNO(dfCenterLat, dfLat1, dfLong1, dfLat2, dfLong2, dfScale,
6600 : dfFalseEasting, dfFalseNorthing);
6601 : }
6602 :
6603 0 : else if (EQUAL(osProjectionType, "OD")) /* Orthographic */
6604 : {
6605 0 : double dfCenterLat = Get(poProjDict, "OriginLatitude");
6606 0 : double dfCenterLong = Get(poProjDict, "CentralMeridian");
6607 0 : double dfFalseEasting = Get(poProjDict, "FalseEasting");
6608 0 : double dfFalseNorthing = Get(poProjDict, "FalseNorthing");
6609 0 : oSRS.SetOrthographic(dfCenterLat, dfCenterLong, dfFalseEasting,
6610 : dfFalseNorthing);
6611 : }
6612 :
6613 0 : else if (EQUAL(osProjectionType, "PG")) /* Polar Stereographic */
6614 : {
6615 0 : double dfCenterLat = Get(poProjDict, "LatitudeTrueScale");
6616 0 : double dfCenterLong = Get(poProjDict, "LongitudeDownFromPole");
6617 0 : double dfScale = 1.0;
6618 0 : double dfFalseEasting = Get(poProjDict, "FalseEasting");
6619 0 : double dfFalseNorthing = Get(poProjDict, "FalseNorthing");
6620 0 : oSRS.SetPS(dfCenterLat, dfCenterLong, dfScale, dfFalseEasting,
6621 : dfFalseNorthing);
6622 : }
6623 :
6624 0 : else if (EQUAL(osProjectionType, "PH")) /* Polyconic */
6625 : {
6626 0 : double dfCenterLat = Get(poProjDict, "OriginLatitude");
6627 0 : double dfCenterLong = Get(poProjDict, "CentralMeridian");
6628 0 : double dfFalseEasting = Get(poProjDict, "FalseEasting");
6629 0 : double dfFalseNorthing = Get(poProjDict, "FalseNorthing");
6630 0 : oSRS.SetPolyconic(dfCenterLat, dfCenterLong, dfFalseEasting,
6631 : dfFalseNorthing);
6632 : }
6633 :
6634 0 : else if (EQUAL(osProjectionType, "SA")) /* Sinusoidal */
6635 : {
6636 0 : double dfCenterLong = Get(poProjDict, "CentralMeridian");
6637 0 : double dfFalseEasting = Get(poProjDict, "FalseEasting");
6638 0 : double dfFalseNorthing = Get(poProjDict, "FalseNorthing");
6639 0 : oSRS.SetSinusoidal(dfCenterLong, dfFalseEasting, dfFalseNorthing);
6640 : }
6641 :
6642 0 : else if (EQUAL(osProjectionType, "SD")) /* Stereographic */
6643 : {
6644 0 : double dfCenterLat = Get(poProjDict, "OriginLatitude");
6645 0 : double dfCenterLong = Get(poProjDict, "CentralMeridian");
6646 0 : double dfScale = 1.0;
6647 0 : double dfFalseEasting = Get(poProjDict, "FalseEasting");
6648 0 : double dfFalseNorthing = Get(poProjDict, "FalseNorthing");
6649 0 : oSRS.SetStereographic(dfCenterLat, dfCenterLong, dfScale,
6650 : dfFalseEasting, dfFalseNorthing);
6651 : }
6652 :
6653 0 : else if (EQUAL(osProjectionType, "TC")) /* Transverse Mercator */
6654 : {
6655 0 : double dfCenterLat = Get(poProjDict, "OriginLatitude");
6656 0 : double dfCenterLong = Get(poProjDict, "CentralMeridian");
6657 0 : double dfScale = Get(poProjDict, "ScaleFactor");
6658 0 : double dfFalseEasting = Get(poProjDict, "FalseEasting");
6659 0 : double dfFalseNorthing = Get(poProjDict, "FalseNorthing");
6660 0 : if (dfCenterLat == 0.0 && dfScale == 0.9996 && dfCenterLong >= -180 &&
6661 0 : dfCenterLong <= 180 && dfFalseEasting == 500000 &&
6662 0 : (dfFalseNorthing == 0.0 || dfFalseNorthing == 10000000.0))
6663 : {
6664 0 : const int nZone =
6665 0 : static_cast<int>(floor((dfCenterLong + 180.0) / 6.0) + 1);
6666 0 : int bNorth = dfFalseNorthing == 0;
6667 0 : if (bIsWGS84)
6668 0 : oSRS.importFromEPSG(((bNorth) ? 32600 : 32700) + nZone);
6669 0 : else if (bIsNAD83 && bNorth)
6670 0 : oSRS.importFromEPSG(26900 + nZone);
6671 : else
6672 0 : oSRS.SetUTM(nZone, bNorth);
6673 : }
6674 : else
6675 : {
6676 0 : oSRS.SetTM(dfCenterLat, dfCenterLong, dfScale, dfFalseEasting,
6677 : dfFalseNorthing);
6678 : }
6679 : }
6680 :
6681 : /* Unhandled TX : Transverse Cylindrical Equal Area */
6682 :
6683 0 : else if (EQUAL(osProjectionType, "VA")) /* Van der Grinten */
6684 : {
6685 0 : double dfCenterLong = Get(poProjDict, "CentralMeridian");
6686 0 : double dfFalseEasting = Get(poProjDict, "FalseEasting");
6687 0 : double dfFalseNorthing = Get(poProjDict, "FalseNorthing");
6688 0 : oSRS.SetVDG(dfCenterLong, dfFalseEasting, dfFalseNorthing);
6689 : }
6690 :
6691 : else
6692 : {
6693 0 : CPLError(CE_Failure, CPLE_AppDefined,
6694 : "Unhandled (yet) value for ProjectionType : %s",
6695 : osProjectionType.c_str());
6696 0 : return FALSE;
6697 : }
6698 :
6699 : /* -------------------------------------------------------------------- */
6700 : /* Extract Units attribute */
6701 : /* -------------------------------------------------------------------- */
6702 0 : CPLString osUnits;
6703 0 : GDALPDFObject *poUnits = poProjDict->Get("Units");
6704 0 : if (poUnits != nullptr && poUnits->GetType() == PDFObjectType_String &&
6705 0 : !EQUAL(osProjectionType, "GEOGRAPHIC"))
6706 : {
6707 0 : osUnits = poUnits->GetString();
6708 0 : CPLDebug("PDF", "Projection.Units = %s", osUnits.c_str());
6709 :
6710 : // This is super weird. The false easting/northing of the SRS
6711 : // are expressed in the unit, but the geotransform is expressed in
6712 : // meters. Hence this hack to have an equivalent SRS definition, but
6713 : // with linear units converted in meters.
6714 0 : if (EQUAL(osUnits, "M"))
6715 0 : oSRS.SetLinearUnits("Meter", 1.0);
6716 0 : else if (EQUAL(osUnits, "FT"))
6717 : {
6718 0 : oSRS.SetLinearUnits("foot", 0.3048);
6719 0 : oSRS.SetLinearUnitsAndUpdateParameters("Meter", 1.0);
6720 : }
6721 0 : else if (EQUAL(osUnits, "USSF"))
6722 : {
6723 0 : oSRS.SetLinearUnits(SRS_UL_US_FOOT, CPLAtof(SRS_UL_US_FOOT_CONV));
6724 0 : oSRS.SetLinearUnitsAndUpdateParameters("Meter", 1.0);
6725 : }
6726 : else
6727 0 : CPLError(CE_Warning, CPLE_AppDefined, "Unhandled unit: %s",
6728 : osUnits.c_str());
6729 : }
6730 :
6731 : /* -------------------------------------------------------------------- */
6732 : /* Export SpatialRef */
6733 : /* -------------------------------------------------------------------- */
6734 0 : m_oSRS = std::move(oSRS);
6735 :
6736 0 : return TRUE;
6737 : }
6738 :
6739 : /************************************************************************/
6740 : /* ParseVP() */
6741 : /************************************************************************/
6742 :
6743 281 : int PDFDataset::ParseVP(GDALPDFObject *poVP, double dfMediaBoxWidth,
6744 : double dfMediaBoxHeight)
6745 : {
6746 : int i;
6747 :
6748 281 : if (poVP->GetType() != PDFObjectType_Array)
6749 0 : return FALSE;
6750 :
6751 281 : GDALPDFArray *poVPArray = poVP->GetArray();
6752 :
6753 281 : int nLength = poVPArray->GetLength();
6754 281 : CPLDebug("PDF", "VP length = %d", nLength);
6755 281 : if (nLength < 1)
6756 0 : return FALSE;
6757 :
6758 : /* -------------------------------------------------------------------- */
6759 : /* Find the largest BBox */
6760 : /* -------------------------------------------------------------------- */
6761 : const char *pszNeatlineToSelect =
6762 281 : GetOption(papszOpenOptions, "NEATLINE", "Map Layers");
6763 :
6764 281 : int iLargest = 0;
6765 281 : int iRequestedVP = -1;
6766 281 : double dfLargestArea = 0;
6767 :
6768 579 : for (i = 0; i < nLength; i++)
6769 : {
6770 298 : GDALPDFObject *poVPElt = poVPArray->Get(i);
6771 596 : if (poVPElt == nullptr ||
6772 298 : poVPElt->GetType() != PDFObjectType_Dictionary)
6773 : {
6774 0 : return FALSE;
6775 : }
6776 :
6777 298 : GDALPDFDictionary *poVPEltDict = poVPElt->GetDictionary();
6778 :
6779 298 : GDALPDFObject *poMeasure = poVPEltDict->Get("Measure");
6780 596 : if (poMeasure == nullptr ||
6781 298 : poMeasure->GetType() != PDFObjectType_Dictionary)
6782 : {
6783 0 : continue;
6784 : }
6785 : /* --------------------------------------------------------------------
6786 : */
6787 : /* Extract Subtype attribute */
6788 : /* --------------------------------------------------------------------
6789 : */
6790 298 : GDALPDFDictionary *poMeasureDict = poMeasure->GetDictionary();
6791 298 : GDALPDFObject *poSubtype = poMeasureDict->Get("Subtype");
6792 298 : if (poSubtype == nullptr || poSubtype->GetType() != PDFObjectType_Name)
6793 : {
6794 0 : continue;
6795 : }
6796 :
6797 298 : CPLDebug("PDF", "Subtype = %s", poSubtype->GetName().c_str());
6798 298 : if (!EQUAL(poSubtype->GetName().c_str(), "GEO"))
6799 : {
6800 0 : continue;
6801 : }
6802 :
6803 298 : GDALPDFObject *poName = poVPEltDict->Get("Name");
6804 298 : if (poName != nullptr && poName->GetType() == PDFObjectType_String)
6805 : {
6806 295 : CPLDebug("PDF", "Name = %s", poName->GetString().c_str());
6807 295 : if (EQUAL(poName->GetString().c_str(), pszNeatlineToSelect))
6808 : {
6809 0 : iRequestedVP = i;
6810 : }
6811 : }
6812 :
6813 298 : GDALPDFObject *poBBox = poVPEltDict->Get("BBox");
6814 298 : if (poBBox == nullptr || poBBox->GetType() != PDFObjectType_Array)
6815 : {
6816 0 : CPLError(CE_Failure, CPLE_AppDefined, "Cannot find Bbox object");
6817 0 : return FALSE;
6818 : }
6819 :
6820 298 : int nBboxLength = poBBox->GetArray()->GetLength();
6821 298 : if (nBboxLength != 4)
6822 : {
6823 0 : CPLError(CE_Failure, CPLE_AppDefined,
6824 : "Invalid length for Bbox object");
6825 0 : return FALSE;
6826 : }
6827 :
6828 : double adfBBox[4];
6829 298 : adfBBox[0] = Get(poBBox, 0);
6830 298 : adfBBox[1] = Get(poBBox, 1);
6831 298 : adfBBox[2] = Get(poBBox, 2);
6832 298 : adfBBox[3] = Get(poBBox, 3);
6833 298 : double dfArea =
6834 298 : fabs(adfBBox[2] - adfBBox[0]) * fabs(adfBBox[3] - adfBBox[1]);
6835 298 : if (dfArea > dfLargestArea)
6836 : {
6837 281 : iLargest = i;
6838 281 : dfLargestArea = dfArea;
6839 : }
6840 : }
6841 :
6842 281 : if (nLength > 1)
6843 : {
6844 17 : CPLDebug("PDF", "Largest BBox in VP array is element %d", iLargest);
6845 : }
6846 :
6847 281 : GDALPDFObject *poVPElt = nullptr;
6848 :
6849 281 : if (iRequestedVP > -1)
6850 : {
6851 0 : CPLDebug("PDF", "Requested NEATLINE BBox in VP array is element %d",
6852 : iRequestedVP);
6853 0 : poVPElt = poVPArray->Get(iRequestedVP);
6854 : }
6855 : else
6856 : {
6857 281 : poVPElt = poVPArray->Get(iLargest);
6858 : }
6859 :
6860 281 : if (poVPElt == nullptr || poVPElt->GetType() != PDFObjectType_Dictionary)
6861 : {
6862 0 : return FALSE;
6863 : }
6864 :
6865 281 : GDALPDFDictionary *poVPEltDict = poVPElt->GetDictionary();
6866 :
6867 281 : GDALPDFObject *poBBox = poVPEltDict->Get("BBox");
6868 281 : if (poBBox == nullptr || poBBox->GetType() != PDFObjectType_Array)
6869 : {
6870 0 : CPLError(CE_Failure, CPLE_AppDefined, "Cannot find Bbox object");
6871 0 : return FALSE;
6872 : }
6873 :
6874 281 : int nBboxLength = poBBox->GetArray()->GetLength();
6875 281 : if (nBboxLength != 4)
6876 : {
6877 0 : CPLError(CE_Failure, CPLE_AppDefined, "Invalid length for Bbox object");
6878 0 : return FALSE;
6879 : }
6880 :
6881 281 : double dfULX = Get(poBBox, 0);
6882 281 : double dfULY = dfMediaBoxHeight - Get(poBBox, 1);
6883 281 : double dfLRX = Get(poBBox, 2);
6884 281 : double dfLRY = dfMediaBoxHeight - Get(poBBox, 3);
6885 :
6886 : /* -------------------------------------------------------------------- */
6887 : /* Extract Measure attribute */
6888 : /* -------------------------------------------------------------------- */
6889 281 : GDALPDFObject *poMeasure = poVPEltDict->Get("Measure");
6890 562 : if (poMeasure == nullptr ||
6891 281 : poMeasure->GetType() != PDFObjectType_Dictionary)
6892 : {
6893 0 : CPLError(CE_Failure, CPLE_AppDefined, "Cannot find Measure object");
6894 0 : return FALSE;
6895 : }
6896 :
6897 281 : int bRet = ParseMeasure(poMeasure, dfMediaBoxWidth, dfMediaBoxHeight, dfULX,
6898 : dfULY, dfLRX, dfLRY);
6899 :
6900 : /* -------------------------------------------------------------------- */
6901 : /* Extract PointData attribute */
6902 : /* -------------------------------------------------------------------- */
6903 281 : GDALPDFObject *poPointData = poVPEltDict->Get("PtData");
6904 281 : if (poPointData != nullptr &&
6905 0 : poPointData->GetType() == PDFObjectType_Dictionary)
6906 : {
6907 0 : CPLDebug("PDF", "Found PointData");
6908 : }
6909 :
6910 281 : return bRet;
6911 : }
6912 :
6913 : /************************************************************************/
6914 : /* ParseMeasure() */
6915 : /************************************************************************/
6916 :
6917 281 : int PDFDataset::ParseMeasure(GDALPDFObject *poMeasure, double dfMediaBoxWidth,
6918 : double dfMediaBoxHeight, double dfULX,
6919 : double dfULY, double dfLRX, double dfLRY)
6920 : {
6921 281 : GDALPDFDictionary *poMeasureDict = poMeasure->GetDictionary();
6922 :
6923 : /* -------------------------------------------------------------------- */
6924 : /* Extract Subtype attribute */
6925 : /* -------------------------------------------------------------------- */
6926 281 : GDALPDFObject *poSubtype = poMeasureDict->Get("Subtype");
6927 281 : if (poSubtype == nullptr || poSubtype->GetType() != PDFObjectType_Name)
6928 : {
6929 0 : CPLError(CE_Failure, CPLE_AppDefined, "Cannot find Subtype object");
6930 0 : return FALSE;
6931 : }
6932 :
6933 281 : CPLDebug("PDF", "Subtype = %s", poSubtype->GetName().c_str());
6934 281 : if (!EQUAL(poSubtype->GetName().c_str(), "GEO"))
6935 0 : return FALSE;
6936 :
6937 : /* -------------------------------------------------------------------- */
6938 : /* Extract Bounds attribute (optional) */
6939 : /* -------------------------------------------------------------------- */
6940 :
6941 : /* http://acrobatusers.com/sites/default/files/gallery_pictures/SEVERODVINSK.pdf
6942 : */
6943 : /* has lgit:LPTS, lgit:GPTS and lgit:Bounds that have more precision than */
6944 : /* LPTS, GPTS and Bounds. Use those ones */
6945 :
6946 281 : GDALPDFObject *poBounds = poMeasureDict->Get("lgit:Bounds");
6947 281 : if (poBounds != nullptr && poBounds->GetType() == PDFObjectType_Array)
6948 : {
6949 0 : CPLDebug("PDF", "Using lgit:Bounds");
6950 : }
6951 559 : else if ((poBounds = poMeasureDict->Get("Bounds")) == nullptr ||
6952 278 : poBounds->GetType() != PDFObjectType_Array)
6953 : {
6954 3 : poBounds = nullptr;
6955 : }
6956 :
6957 281 : if (poBounds != nullptr)
6958 : {
6959 278 : int nBoundsLength = poBounds->GetArray()->GetLength();
6960 278 : if (nBoundsLength == 8)
6961 : {
6962 : double adfBounds[8];
6963 2340 : for (int i = 0; i < 8; i++)
6964 : {
6965 2080 : adfBounds[i] = Get(poBounds, i);
6966 2080 : CPLDebug("PDF", "Bounds[%d] = %f", i, adfBounds[i]);
6967 : }
6968 :
6969 : // TODO we should use it to restrict the neatline but
6970 : // I have yet to set a sample where bounds are not the four
6971 : // corners of the unit square.
6972 : }
6973 : }
6974 :
6975 : /* -------------------------------------------------------------------- */
6976 : /* Extract GPTS attribute */
6977 : /* -------------------------------------------------------------------- */
6978 281 : GDALPDFObject *poGPTS = poMeasureDict->Get("lgit:GPTS");
6979 281 : if (poGPTS != nullptr && poGPTS->GetType() == PDFObjectType_Array)
6980 : {
6981 0 : CPLDebug("PDF", "Using lgit:GPTS");
6982 : }
6983 562 : else if ((poGPTS = poMeasureDict->Get("GPTS")) == nullptr ||
6984 281 : poGPTS->GetType() != PDFObjectType_Array)
6985 : {
6986 0 : CPLError(CE_Failure, CPLE_AppDefined, "Cannot find GPTS object");
6987 0 : return FALSE;
6988 : }
6989 :
6990 281 : int nGPTSLength = poGPTS->GetArray()->GetLength();
6991 281 : if ((nGPTSLength % 2) != 0 || nGPTSLength < 6)
6992 : {
6993 0 : CPLError(CE_Failure, CPLE_AppDefined, "Invalid length for GPTS object");
6994 0 : return FALSE;
6995 : }
6996 :
6997 562 : std::vector<double> adfGPTS(nGPTSLength);
6998 2529 : for (int i = 0; i < nGPTSLength; i++)
6999 : {
7000 2248 : adfGPTS[i] = Get(poGPTS, i);
7001 2248 : CPLDebug("PDF", "GPTS[%d] = %.18f", i, adfGPTS[i]);
7002 : }
7003 :
7004 : /* -------------------------------------------------------------------- */
7005 : /* Extract LPTS attribute */
7006 : /* -------------------------------------------------------------------- */
7007 281 : GDALPDFObject *poLPTS = poMeasureDict->Get("lgit:LPTS");
7008 281 : if (poLPTS != nullptr && poLPTS->GetType() == PDFObjectType_Array)
7009 : {
7010 0 : CPLDebug("PDF", "Using lgit:LPTS");
7011 : }
7012 562 : else if ((poLPTS = poMeasureDict->Get("LPTS")) == nullptr ||
7013 281 : poLPTS->GetType() != PDFObjectType_Array)
7014 : {
7015 0 : CPLError(CE_Failure, CPLE_AppDefined, "Cannot find LPTS object");
7016 0 : return FALSE;
7017 : }
7018 :
7019 281 : int nLPTSLength = poLPTS->GetArray()->GetLength();
7020 281 : if (nLPTSLength != nGPTSLength)
7021 : {
7022 0 : CPLError(CE_Failure, CPLE_AppDefined, "Invalid length for LPTS object");
7023 0 : return FALSE;
7024 : }
7025 :
7026 562 : std::vector<double> adfLPTS(nLPTSLength);
7027 2529 : for (int i = 0; i < nLPTSLength; i++)
7028 : {
7029 2248 : adfLPTS[i] = Get(poLPTS, i);
7030 2248 : CPLDebug("PDF", "LPTS[%d] = %f", i, adfLPTS[i]);
7031 : }
7032 :
7033 : /* -------------------------------------------------------------------- */
7034 : /* Extract GCS attribute */
7035 : /* -------------------------------------------------------------------- */
7036 281 : GDALPDFObject *poGCS = poMeasureDict->Get("GCS");
7037 281 : if (poGCS == nullptr || poGCS->GetType() != PDFObjectType_Dictionary)
7038 : {
7039 0 : CPLError(CE_Failure, CPLE_AppDefined, "Cannot find GCS object");
7040 0 : return FALSE;
7041 : }
7042 :
7043 281 : GDALPDFDictionary *poGCSDict = poGCS->GetDictionary();
7044 :
7045 : /* -------------------------------------------------------------------- */
7046 : /* Extract GCS.Type attribute */
7047 : /* -------------------------------------------------------------------- */
7048 281 : GDALPDFObject *poGCSType = poGCSDict->Get("Type");
7049 281 : if (poGCSType == nullptr || poGCSType->GetType() != PDFObjectType_Name)
7050 : {
7051 0 : CPLError(CE_Failure, CPLE_AppDefined, "Cannot find GCS.Type object");
7052 0 : return FALSE;
7053 : }
7054 :
7055 281 : CPLDebug("PDF", "GCS.Type = %s", poGCSType->GetName().c_str());
7056 :
7057 : /* -------------------------------------------------------------------- */
7058 : /* Extract EPSG attribute */
7059 : /* -------------------------------------------------------------------- */
7060 281 : GDALPDFObject *poEPSG = poGCSDict->Get("EPSG");
7061 281 : int nEPSGCode = 0;
7062 281 : if (poEPSG != nullptr && poEPSG->GetType() == PDFObjectType_Int)
7063 : {
7064 237 : nEPSGCode = poEPSG->GetInt();
7065 237 : CPLDebug("PDF", "GCS.EPSG = %d", nEPSGCode);
7066 : }
7067 :
7068 : /* -------------------------------------------------------------------- */
7069 : /* Extract GCS.WKT attribute */
7070 : /* -------------------------------------------------------------------- */
7071 281 : GDALPDFObject *poGCSWKT = poGCSDict->Get("WKT");
7072 281 : if (poGCSWKT != nullptr && poGCSWKT->GetType() != PDFObjectType_String)
7073 : {
7074 0 : poGCSWKT = nullptr;
7075 : }
7076 :
7077 281 : if (poGCSWKT != nullptr)
7078 278 : CPLDebug("PDF", "GCS.WKT = %s", poGCSWKT->GetString().c_str());
7079 :
7080 281 : if (nEPSGCode <= 0 && poGCSWKT == nullptr)
7081 : {
7082 0 : CPLError(CE_Failure, CPLE_AppDefined,
7083 : "Cannot find GCS.WKT or GCS.EPSG objects");
7084 0 : return FALSE;
7085 : }
7086 :
7087 281 : if (poGCSWKT != nullptr)
7088 : {
7089 278 : m_oSRS.importFromWkt(poGCSWKT->GetString().c_str());
7090 : }
7091 :
7092 281 : bool bSRSOK = false;
7093 281 : if (nEPSGCode != 0)
7094 : {
7095 : // At time of writing EPSG CRS codes are <= 32767.
7096 : // The usual practice is that codes >= 100000 are in the ESRI namespace
7097 : // instead
7098 237 : if (nEPSGCode >= 100000)
7099 : {
7100 4 : CPLErrorHandlerPusher oHandler(CPLQuietErrorHandler);
7101 4 : OGRSpatialReference oSRS_ESRI;
7102 2 : oSRS_ESRI.SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER);
7103 2 : if (oSRS_ESRI.SetFromUserInput(CPLSPrintf("ESRI:%d", nEPSGCode)) ==
7104 : OGRERR_NONE)
7105 : {
7106 2 : bSRSOK = true;
7107 :
7108 : // Check consistency of ESRI:xxxx and WKT definitions
7109 2 : if (poGCSWKT != nullptr)
7110 : {
7111 3 : if (!m_oSRS.GetName() ||
7112 1 : (!EQUAL(oSRS_ESRI.GetName(), m_oSRS.GetName()) &&
7113 0 : !oSRS_ESRI.IsSame(&m_oSRS)))
7114 : {
7115 1 : CPLDebug("PDF",
7116 : "Definition from ESRI:%d and WKT=%s do not "
7117 : "match. Using WKT string",
7118 1 : nEPSGCode, poGCSWKT->GetString().c_str());
7119 1 : bSRSOK = false;
7120 : }
7121 : }
7122 2 : if (bSRSOK)
7123 : {
7124 1 : m_oSRS = std::move(oSRS_ESRI);
7125 : }
7126 : }
7127 : }
7128 235 : else if (m_oSRS.importFromEPSG(nEPSGCode) == OGRERR_NONE)
7129 : {
7130 235 : bSRSOK = true;
7131 : }
7132 : }
7133 :
7134 281 : if (!bSRSOK)
7135 : {
7136 45 : if (poGCSWKT == nullptr)
7137 : {
7138 0 : CPLError(CE_Failure, CPLE_AppDefined,
7139 : "Cannot resolve EPSG object, and GCS.WKT not found");
7140 0 : return FALSE;
7141 : }
7142 :
7143 45 : if (m_oSRS.importFromWkt(poGCSWKT->GetString().c_str()) != OGRERR_NONE)
7144 : {
7145 1 : m_oSRS.Clear();
7146 1 : return FALSE;
7147 : }
7148 : }
7149 :
7150 : /* -------------------------------------------------------------------- */
7151 : /* Compute geotransform */
7152 : /* -------------------------------------------------------------------- */
7153 280 : OGRSpatialReference *poSRSGeog = m_oSRS.CloneGeogCS();
7154 :
7155 : /* Files found at
7156 : * http://carto.iict.ch/blog/publications-cartographiques-au-format-geospatial-pdf/
7157 : */
7158 : /* are in a PROJCS. However the coordinates in GPTS array are not in (lat,
7159 : * long) as required by the */
7160 : /* ISO 32000 supplement spec, but in (northing, easting). Adobe reader is
7161 : * able to understand that, */
7162 : /* so let's also try to do it with a heuristics. */
7163 :
7164 280 : bool bReproject = true;
7165 280 : if (m_oSRS.IsProjected())
7166 : {
7167 1035 : for (int i = 0; i < nGPTSLength / 2; i++)
7168 : {
7169 828 : if (fabs(adfGPTS[2 * i]) > 91 || fabs(adfGPTS[2 * i + 1]) > 361)
7170 : {
7171 0 : CPLDebug("PDF", "GPTS coordinates seems to be in (northing, "
7172 : "easting), which is non-standard");
7173 0 : bReproject = false;
7174 0 : break;
7175 : }
7176 : }
7177 : }
7178 :
7179 280 : OGRCoordinateTransformation *poCT = nullptr;
7180 280 : if (bReproject)
7181 : {
7182 280 : poCT = OGRCreateCoordinateTransformation(poSRSGeog, &m_oSRS);
7183 280 : if (poCT == nullptr)
7184 : {
7185 0 : delete poSRSGeog;
7186 0 : m_oSRS.Clear();
7187 0 : return FALSE;
7188 : }
7189 : }
7190 :
7191 560 : std::vector<GDAL_GCP> asGCPS(nGPTSLength / 2);
7192 :
7193 : /* Create NEATLINE */
7194 280 : OGRLinearRing *poRing = nullptr;
7195 280 : if (nGPTSLength == 8)
7196 : {
7197 280 : m_poNeatLine = new OGRPolygon();
7198 280 : poRing = new OGRLinearRing();
7199 280 : m_poNeatLine->addRingDirectly(poRing);
7200 : }
7201 :
7202 1400 : for (int i = 0; i < nGPTSLength / 2; i++)
7203 : {
7204 : /* We probably assume LPTS is 0 or 1 */
7205 2240 : asGCPS[i].dfGCPPixel =
7206 1120 : (dfULX * (1 - adfLPTS[2 * i + 0]) + dfLRX * adfLPTS[2 * i + 0]) /
7207 1120 : dfMediaBoxWidth * nRasterXSize;
7208 2240 : asGCPS[i].dfGCPLine =
7209 1120 : (dfULY * (1 - adfLPTS[2 * i + 1]) + dfLRY * adfLPTS[2 * i + 1]) /
7210 1120 : dfMediaBoxHeight * nRasterYSize;
7211 :
7212 1120 : double lat = adfGPTS[2 * i];
7213 1120 : double lon = adfGPTS[2 * i + 1];
7214 1120 : double x = lon;
7215 1120 : double y = lat;
7216 1120 : if (bReproject)
7217 : {
7218 1120 : if (!poCT->Transform(1, &x, &y, nullptr))
7219 : {
7220 0 : CPLError(CE_Failure, CPLE_AppDefined,
7221 : "Cannot reproject (%f, %f)", lon, lat);
7222 0 : delete poSRSGeog;
7223 0 : delete poCT;
7224 0 : m_oSRS.Clear();
7225 0 : return FALSE;
7226 : }
7227 : }
7228 :
7229 1120 : x = ROUND_IF_CLOSE(x);
7230 1120 : y = ROUND_IF_CLOSE(y);
7231 :
7232 1120 : asGCPS[i].dfGCPX = x;
7233 1120 : asGCPS[i].dfGCPY = y;
7234 :
7235 1120 : if (poRing)
7236 1120 : poRing->addPoint(x, y);
7237 : }
7238 :
7239 280 : delete poSRSGeog;
7240 280 : delete poCT;
7241 :
7242 280 : if (!GDALGCPsToGeoTransform(nGPTSLength / 2, asGCPS.data(),
7243 : m_adfGeoTransform.data(), FALSE))
7244 : {
7245 2 : CPLDebug("PDF",
7246 : "Could not compute GT with exact match. Try with approximate");
7247 2 : if (!GDALGCPsToGeoTransform(nGPTSLength / 2, asGCPS.data(),
7248 : m_adfGeoTransform.data(), TRUE))
7249 : {
7250 0 : CPLError(CE_Failure, CPLE_AppDefined,
7251 : "Could not compute GT with approximate match.");
7252 0 : return FALSE;
7253 : }
7254 : }
7255 280 : m_bGeoTransformValid = true;
7256 :
7257 : // If the non scaling terms of the geotransform are significantly smaller
7258 : // than the pixel size, then nullify them as being just artifacts of
7259 : // reprojection and GDALGCPsToGeoTransform() numerical imprecisions.
7260 : const double dfPixelSize =
7261 280 : std::min(fabs(m_adfGeoTransform[1]), fabs(m_adfGeoTransform[5]));
7262 : const double dfRotationShearTerm =
7263 280 : std::max(fabs(m_adfGeoTransform[2]), fabs(m_adfGeoTransform[4]));
7264 379 : if (dfRotationShearTerm < 1e-5 * dfPixelSize ||
7265 99 : (m_bUseLib.test(PDFLIB_PDFIUM) &&
7266 374 : std::min(fabs(m_adfGeoTransform[2]), fabs(m_adfGeoTransform[4])) <
7267 94 : 1e-5 * dfPixelSize))
7268 : {
7269 194 : dfLRX = m_adfGeoTransform[0] + nRasterXSize * m_adfGeoTransform[1] +
7270 194 : nRasterYSize * m_adfGeoTransform[2];
7271 194 : dfLRY = m_adfGeoTransform[3] + nRasterXSize * m_adfGeoTransform[4] +
7272 194 : nRasterYSize * m_adfGeoTransform[5];
7273 194 : m_adfGeoTransform[1] = (dfLRX - m_adfGeoTransform[0]) / nRasterXSize;
7274 194 : m_adfGeoTransform[5] = (dfLRY - m_adfGeoTransform[3]) / nRasterYSize;
7275 194 : m_adfGeoTransform[2] = m_adfGeoTransform[4] = 0;
7276 : }
7277 :
7278 280 : return TRUE;
7279 : }
7280 :
7281 : /************************************************************************/
7282 : /* GetSpatialRef() */
7283 : /************************************************************************/
7284 :
7285 255 : const OGRSpatialReference *PDFDataset::GetSpatialRef() const
7286 : {
7287 255 : const auto poSRS = GDALPamDataset::GetSpatialRef();
7288 255 : if (poSRS)
7289 6 : return poSRS;
7290 :
7291 249 : if (!m_oSRS.IsEmpty() && m_bGeoTransformValid)
7292 247 : return &m_oSRS;
7293 2 : return nullptr;
7294 : }
7295 :
7296 : /************************************************************************/
7297 : /* GetGeoTransform() */
7298 : /************************************************************************/
7299 :
7300 47 : CPLErr PDFDataset::GetGeoTransform(double *padfTransform)
7301 :
7302 : {
7303 47 : if (GDALPamDataset::GetGeoTransform(padfTransform) == CE_None)
7304 : {
7305 6 : return CE_None;
7306 : }
7307 :
7308 41 : std::copy(std::begin(m_adfGeoTransform), std::end(m_adfGeoTransform),
7309 : padfTransform);
7310 :
7311 41 : return ((m_bGeoTransformValid) ? CE_None : CE_Failure);
7312 : }
7313 :
7314 : /************************************************************************/
7315 : /* SetSpatialRef() */
7316 : /************************************************************************/
7317 :
7318 11 : CPLErr PDFDataset::SetSpatialRef(const OGRSpatialReference *poSRS)
7319 : {
7320 11 : if (eAccess == GA_ReadOnly)
7321 4 : GDALPamDataset::SetSpatialRef(poSRS);
7322 :
7323 11 : m_oSRS.Clear();
7324 11 : if (poSRS)
7325 9 : m_oSRS = *poSRS;
7326 11 : m_bProjDirty = true;
7327 11 : return CE_None;
7328 : }
7329 :
7330 : /************************************************************************/
7331 : /* SetGeoTransform() */
7332 : /************************************************************************/
7333 :
7334 9 : CPLErr PDFDataset::SetGeoTransform(double *padfGeoTransform)
7335 : {
7336 9 : if (eAccess == GA_ReadOnly)
7337 4 : GDALPamDataset::SetGeoTransform(padfGeoTransform);
7338 :
7339 9 : std::copy(padfGeoTransform, padfGeoTransform + 6,
7340 9 : std::begin(m_adfGeoTransform));
7341 9 : m_bGeoTransformValid = true;
7342 9 : m_bProjDirty = true;
7343 :
7344 : /* Reset NEATLINE if not explicitly set by the user */
7345 9 : if (!m_bNeatLineDirty)
7346 9 : SetMetadataItem("NEATLINE", nullptr);
7347 9 : return CE_None;
7348 : }
7349 :
7350 : /************************************************************************/
7351 : /* GetMetadataDomainList() */
7352 : /************************************************************************/
7353 :
7354 1 : char **PDFDataset::GetMetadataDomainList()
7355 : {
7356 1 : return BuildMetadataDomainList(GDALPamDataset::GetMetadataDomainList(),
7357 : TRUE, "xml:XMP", "LAYERS",
7358 1 : "EMBEDDED_METADATA", nullptr);
7359 : }
7360 :
7361 : /************************************************************************/
7362 : /* GetMetadata() */
7363 : /************************************************************************/
7364 :
7365 2089 : char **PDFDataset::GetMetadata(const char *pszDomain)
7366 : {
7367 2089 : if (pszDomain != nullptr && EQUAL(pszDomain, "EMBEDDED_METADATA"))
7368 : {
7369 1 : char **papszRet = m_oMDMD_PDF.GetMetadata(pszDomain);
7370 1 : if (papszRet)
7371 0 : return papszRet;
7372 :
7373 1 : GDALPDFObject *poCatalog = GetCatalog();
7374 1 : if (poCatalog == nullptr)
7375 0 : return nullptr;
7376 : GDALPDFObject *poFirstElt =
7377 1 : poCatalog->LookupObject("Names.EmbeddedFiles.Names[0]");
7378 : GDALPDFObject *poF =
7379 1 : poCatalog->LookupObject("Names.EmbeddedFiles.Names[1].EF.F");
7380 :
7381 1 : if (poFirstElt == nullptr ||
7382 1 : poFirstElt->GetType() != PDFObjectType_String ||
7383 0 : poFirstElt->GetString() != "Metadata")
7384 1 : return nullptr;
7385 0 : if (poF == nullptr || poF->GetType() != PDFObjectType_Dictionary)
7386 0 : return nullptr;
7387 0 : GDALPDFStream *poStream = poF->GetStream();
7388 0 : if (poStream == nullptr)
7389 0 : return nullptr;
7390 :
7391 0 : char *apszMetadata[2] = {nullptr, nullptr};
7392 0 : apszMetadata[0] = poStream->GetBytes();
7393 0 : m_oMDMD_PDF.SetMetadata(apszMetadata, pszDomain);
7394 0 : VSIFree(apszMetadata[0]);
7395 0 : return m_oMDMD_PDF.GetMetadata(pszDomain);
7396 : }
7397 2088 : if (pszDomain == nullptr || EQUAL(pszDomain, ""))
7398 : {
7399 217 : char **papszPAMMD = GDALPamDataset::GetMetadata(pszDomain);
7400 222 : for (char **papszIter = papszPAMMD; papszIter && *papszIter;
7401 : ++papszIter)
7402 : {
7403 5 : char *pszKey = nullptr;
7404 5 : const char *pszValue = CPLParseNameValue(*papszIter, &pszKey);
7405 5 : if (pszKey && pszValue)
7406 : {
7407 5 : if (m_oMDMD_PDF.GetMetadataItem(pszKey, pszDomain) == nullptr)
7408 4 : m_oMDMD_PDF.SetMetadataItem(pszKey, pszValue, pszDomain);
7409 : }
7410 5 : CPLFree(pszKey);
7411 : }
7412 217 : return m_oMDMD_PDF.GetMetadata(pszDomain);
7413 : }
7414 1871 : if (EQUAL(pszDomain, "LAYERS") || EQUAL(pszDomain, "xml:XMP") ||
7415 1821 : EQUAL(pszDomain, "SUBDATASETS"))
7416 : {
7417 52 : return m_oMDMD_PDF.GetMetadata(pszDomain);
7418 : }
7419 1819 : return GDALPamDataset::GetMetadata(pszDomain);
7420 : }
7421 :
7422 : /************************************************************************/
7423 : /* SetMetadata() */
7424 : /************************************************************************/
7425 :
7426 129 : CPLErr PDFDataset::SetMetadata(char **papszMetadata, const char *pszDomain)
7427 : {
7428 129 : if (pszDomain == nullptr || EQUAL(pszDomain, ""))
7429 : {
7430 83 : char **papszMetadataDup = CSLDuplicate(papszMetadata);
7431 83 : m_oMDMD_PDF.SetMetadata(nullptr, pszDomain);
7432 :
7433 259 : for (char **papszIter = papszMetadataDup; papszIter && *papszIter;
7434 : ++papszIter)
7435 : {
7436 176 : char *pszKey = nullptr;
7437 176 : const char *pszValue = CPLParseNameValue(*papszIter, &pszKey);
7438 176 : if (pszKey && pszValue)
7439 : {
7440 173 : SetMetadataItem(pszKey, pszValue, pszDomain);
7441 : }
7442 176 : CPLFree(pszKey);
7443 : }
7444 83 : CSLDestroy(papszMetadataDup);
7445 83 : return CE_None;
7446 : }
7447 46 : else if (EQUAL(pszDomain, "xml:XMP"))
7448 : {
7449 42 : m_bXMPDirty = true;
7450 42 : return m_oMDMD_PDF.SetMetadata(papszMetadata, pszDomain);
7451 : }
7452 4 : else if (EQUAL(pszDomain, "SUBDATASETS"))
7453 : {
7454 4 : return m_oMDMD_PDF.SetMetadata(papszMetadata, pszDomain);
7455 : }
7456 : else
7457 : {
7458 0 : return GDALPamDataset::SetMetadata(papszMetadata, pszDomain);
7459 : }
7460 : }
7461 :
7462 : /************************************************************************/
7463 : /* GetMetadataItem() */
7464 : /************************************************************************/
7465 :
7466 1921 : const char *PDFDataset::GetMetadataItem(const char *pszName,
7467 : const char *pszDomain)
7468 : {
7469 1921 : if (pszDomain != nullptr && EQUAL(pszDomain, "_INTERNAL_") &&
7470 0 : pszName != nullptr && EQUAL(pszName, "PDF_LIB"))
7471 : {
7472 0 : if (m_bUseLib.test(PDFLIB_POPPLER))
7473 0 : return "POPPLER";
7474 0 : if (m_bUseLib.test(PDFLIB_PODOFO))
7475 0 : return "PODOFO";
7476 0 : if (m_bUseLib.test(PDFLIB_PDFIUM))
7477 0 : return "PDFIUM";
7478 : }
7479 1921 : return CSLFetchNameValue(GetMetadata(pszDomain), pszName);
7480 : }
7481 :
7482 : /************************************************************************/
7483 : /* SetMetadataItem() */
7484 : /************************************************************************/
7485 :
7486 1329 : CPLErr PDFDataset::SetMetadataItem(const char *pszName, const char *pszValue,
7487 : const char *pszDomain)
7488 : {
7489 1329 : if (pszDomain == nullptr || EQUAL(pszDomain, ""))
7490 : {
7491 1227 : if (EQUAL(pszName, "NEATLINE"))
7492 : {
7493 : const char *pszOldValue =
7494 351 : m_oMDMD_PDF.GetMetadataItem(pszName, pszDomain);
7495 351 : if ((pszValue == nullptr && pszOldValue != nullptr) ||
7496 348 : (pszValue != nullptr && pszOldValue == nullptr) ||
7497 2 : (pszValue != nullptr && pszOldValue != nullptr &&
7498 2 : strcmp(pszValue, pszOldValue) != 0))
7499 : {
7500 343 : m_bProjDirty = true;
7501 343 : m_bNeatLineDirty = true;
7502 : }
7503 351 : return m_oMDMD_PDF.SetMetadataItem(pszName, pszValue, pszDomain);
7504 : }
7505 : else
7506 : {
7507 876 : if (EQUAL(pszName, "AUTHOR") || EQUAL(pszName, "PRODUCER") ||
7508 833 : EQUAL(pszName, "CREATOR") || EQUAL(pszName, "CREATION_DATE") ||
7509 739 : EQUAL(pszName, "SUBJECT") || EQUAL(pszName, "TITLE") ||
7510 704 : EQUAL(pszName, "KEYWORDS"))
7511 : {
7512 184 : if (pszValue == nullptr)
7513 2 : pszValue = "";
7514 : const char *pszOldValue =
7515 184 : m_oMDMD_PDF.GetMetadataItem(pszName, pszDomain);
7516 184 : if (pszOldValue == nullptr ||
7517 4 : strcmp(pszValue, pszOldValue) != 0)
7518 : {
7519 184 : m_bInfoDirty = true;
7520 : }
7521 184 : return m_oMDMD_PDF.SetMetadataItem(pszName, pszValue,
7522 184 : pszDomain);
7523 : }
7524 692 : else if (EQUAL(pszName, "DPI"))
7525 : {
7526 689 : return m_oMDMD_PDF.SetMetadataItem(pszName, pszValue,
7527 689 : pszDomain);
7528 : }
7529 : else
7530 : {
7531 3 : m_oMDMD_PDF.SetMetadataItem(pszName, pszValue, pszDomain);
7532 3 : return GDALPamDataset::SetMetadataItem(pszName, pszValue,
7533 3 : pszDomain);
7534 : }
7535 : }
7536 : }
7537 102 : else if (EQUAL(pszDomain, "xml:XMP"))
7538 : {
7539 0 : m_bXMPDirty = true;
7540 0 : return m_oMDMD_PDF.SetMetadataItem(pszName, pszValue, pszDomain);
7541 : }
7542 102 : else if (EQUAL(pszDomain, "SUBDATASETS"))
7543 : {
7544 0 : return m_oMDMD_PDF.SetMetadataItem(pszName, pszValue, pszDomain);
7545 : }
7546 : else
7547 : {
7548 102 : return GDALPamDataset::SetMetadataItem(pszName, pszValue, pszDomain);
7549 : }
7550 : }
7551 :
7552 : /************************************************************************/
7553 : /* GetGCPCount() */
7554 : /************************************************************************/
7555 :
7556 21 : int PDFDataset::GetGCPCount()
7557 : {
7558 21 : return m_nGCPCount;
7559 : }
7560 :
7561 : /************************************************************************/
7562 : /* GetGCPSpatialRef() */
7563 : /************************************************************************/
7564 :
7565 4 : const OGRSpatialReference *PDFDataset::GetGCPSpatialRef() const
7566 : {
7567 4 : if (!m_oSRS.IsEmpty() && m_nGCPCount != 0)
7568 2 : return &m_oSRS;
7569 2 : return nullptr;
7570 : }
7571 :
7572 : /************************************************************************/
7573 : /* GetGCPs() */
7574 : /************************************************************************/
7575 :
7576 4 : const GDAL_GCP *PDFDataset::GetGCPs()
7577 : {
7578 4 : return m_pasGCPList;
7579 : }
7580 :
7581 : /************************************************************************/
7582 : /* SetGCPs() */
7583 : /************************************************************************/
7584 :
7585 2 : CPLErr PDFDataset::SetGCPs(int nGCPCountIn, const GDAL_GCP *pasGCPListIn,
7586 : const OGRSpatialReference *poSRS)
7587 : {
7588 : const char *pszGEO_ENCODING =
7589 2 : CPLGetConfigOption("GDAL_PDF_GEO_ENCODING", "ISO32000");
7590 2 : if (nGCPCountIn != 4 && EQUAL(pszGEO_ENCODING, "ISO32000"))
7591 : {
7592 0 : CPLError(CE_Failure, CPLE_NotSupported,
7593 : "PDF driver only supports writing 4 GCPs when "
7594 : "GDAL_PDF_GEO_ENCODING=ISO32000.");
7595 0 : return CE_Failure;
7596 : }
7597 :
7598 : /* Free previous GCPs */
7599 2 : GDALDeinitGCPs(m_nGCPCount, m_pasGCPList);
7600 2 : CPLFree(m_pasGCPList);
7601 :
7602 : /* Duplicate in GCPs */
7603 2 : m_nGCPCount = nGCPCountIn;
7604 2 : m_pasGCPList = GDALDuplicateGCPs(m_nGCPCount, pasGCPListIn);
7605 :
7606 2 : m_oSRS.Clear();
7607 2 : if (poSRS)
7608 2 : m_oSRS = *poSRS;
7609 :
7610 2 : m_bProjDirty = true;
7611 :
7612 : /* Reset NEATLINE if not explicitly set by the user */
7613 2 : if (!m_bNeatLineDirty)
7614 2 : SetMetadataItem("NEATLINE", nullptr);
7615 :
7616 2 : return CE_None;
7617 : }
7618 :
7619 : #endif // #ifdef HAVE_PDF_READ_SUPPORT
7620 :
7621 : /************************************************************************/
7622 : /* GDALPDFOpen() */
7623 : /************************************************************************/
7624 :
7625 90 : GDALDataset *GDALPDFOpen(
7626 : #ifdef HAVE_PDF_READ_SUPPORT
7627 : const char *pszFilename, GDALAccess eAccess
7628 : #else
7629 : CPL_UNUSED const char *pszFilename, CPL_UNUSED GDALAccess eAccess
7630 : #endif
7631 : )
7632 : {
7633 : #ifdef HAVE_PDF_READ_SUPPORT
7634 180 : GDALOpenInfo oOpenInfo(pszFilename, eAccess);
7635 180 : return PDFDataset::Open(&oOpenInfo);
7636 : #else
7637 : return nullptr;
7638 : #endif
7639 : }
7640 :
7641 : /************************************************************************/
7642 : /* GDALPDFUnloadDriver() */
7643 : /************************************************************************/
7644 :
7645 10 : static void GDALPDFUnloadDriver(CPL_UNUSED GDALDriver *poDriver)
7646 : {
7647 : #ifdef HAVE_POPPLER
7648 10 : if (hGlobalParamsMutex != nullptr)
7649 0 : CPLDestroyMutex(hGlobalParamsMutex);
7650 : #endif
7651 : #ifdef HAVE_PDFIUM
7652 10 : if (PDFDataset::g_bPdfiumInit)
7653 : {
7654 2 : CPLCreateOrAcquireMutex(&g_oPdfiumLoadDocMutex, PDFIUM_MUTEX_TIMEOUT);
7655 : // Destroy every loaded document or page
7656 2 : TMapPdfiumDatasets::iterator itDoc;
7657 2 : TMapPdfiumPages::iterator itPage;
7658 2 : for (itDoc = g_mPdfiumDatasets.begin();
7659 2 : itDoc != g_mPdfiumDatasets.end(); ++itDoc)
7660 : {
7661 0 : TPdfiumDocumentStruct *pDoc = itDoc->second;
7662 0 : for (itPage = pDoc->pages.begin(); itPage != pDoc->pages.end();
7663 0 : ++itPage)
7664 : {
7665 0 : TPdfiumPageStruct *pPage = itPage->second;
7666 :
7667 0 : CPLCreateOrAcquireMutex(&g_oPdfiumReadMutex,
7668 : PDFIUM_MUTEX_TIMEOUT);
7669 0 : CPLCreateOrAcquireMutex(&(pPage->readMutex),
7670 : PDFIUM_MUTEX_TIMEOUT);
7671 0 : CPLReleaseMutex(pPage->readMutex);
7672 0 : CPLDestroyMutex(pPage->readMutex);
7673 0 : FPDF_ClosePage(FPDFPageFromIPDFPage(pPage->page));
7674 0 : delete pPage;
7675 0 : CPLReleaseMutex(g_oPdfiumReadMutex);
7676 : } // ~ foreach page
7677 :
7678 0 : FPDF_CloseDocument(FPDFDocumentFromCPDFDocument(pDoc->doc));
7679 0 : CPLFree(pDoc->filename);
7680 0 : VSIFCloseL(static_cast<VSILFILE *>(pDoc->psFileAccess->m_Param));
7681 0 : delete pDoc->psFileAccess;
7682 0 : pDoc->pages.clear();
7683 :
7684 0 : delete pDoc;
7685 : } // ~ foreach document
7686 2 : g_mPdfiumDatasets.clear();
7687 2 : FPDF_DestroyLibrary();
7688 2 : PDFDataset::g_bPdfiumInit = FALSE;
7689 :
7690 2 : CPLReleaseMutex(g_oPdfiumLoadDocMutex);
7691 :
7692 2 : if (g_oPdfiumReadMutex)
7693 0 : CPLDestroyMutex(g_oPdfiumReadMutex);
7694 2 : CPLDestroyMutex(g_oPdfiumLoadDocMutex);
7695 : }
7696 : #endif
7697 10 : }
7698 :
7699 : /************************************************************************/
7700 : /* PDFSanitizeLayerName() */
7701 : /************************************************************************/
7702 :
7703 837 : CPLString PDFSanitizeLayerName(const char *pszName)
7704 : {
7705 837 : if (!CPLTestBool(CPLGetConfigOption("GDAL_PDF_LAUNDER_LAYER_NAMES", "YES")))
7706 0 : return pszName;
7707 :
7708 1674 : CPLString osName;
7709 18551 : for (int i = 0; pszName[i] != '\0'; i++)
7710 : {
7711 17714 : if (pszName[i] == ' ' || pszName[i] == '.' || pszName[i] == ',')
7712 1027 : osName += "_";
7713 16687 : else if (pszName[i] != '"')
7714 16687 : osName += pszName[i];
7715 : }
7716 837 : if (osName.empty())
7717 3 : osName = "unnamed";
7718 837 : return osName;
7719 : }
7720 :
7721 : /************************************************************************/
7722 : /* GDALPDFListLayersAlgorithm */
7723 : /************************************************************************/
7724 :
7725 : #ifdef HAVE_PDF_READ_SUPPORT
7726 :
7727 : class GDALPDFListLayersAlgorithm final : public GDALAlgorithm
7728 : {
7729 : public:
7730 13 : GDALPDFListLayersAlgorithm()
7731 13 : : GDALAlgorithm("list-layers",
7732 26 : std::string("List layers of a PDF dataset"),
7733 39 : "/drivers/raster/pdf.html")
7734 : {
7735 13 : AddInputDatasetArg(&m_dataset, GDAL_OF_RASTER | GDAL_OF_VECTOR);
7736 13 : AddOutputFormatArg(&m_format).SetDefault(m_format).SetChoices("json",
7737 13 : "text");
7738 13 : AddOutputStringArg(&m_output);
7739 13 : }
7740 :
7741 : protected:
7742 : bool RunImpl(GDALProgressFunc, void *) override;
7743 :
7744 : private:
7745 : GDALArgDatasetValue m_dataset{};
7746 : std::string m_format = "json";
7747 : std::string m_output{};
7748 : };
7749 :
7750 3 : bool GDALPDFListLayersAlgorithm::RunImpl(GDALProgressFunc, void *)
7751 : {
7752 3 : auto poDS = dynamic_cast<PDFDataset *>(m_dataset.GetDatasetRef());
7753 3 : if (!poDS)
7754 : {
7755 1 : ReportError(CE_Failure, CPLE_AppDefined, "%s is not a PDF",
7756 1 : m_dataset.GetName().c_str());
7757 1 : return false;
7758 : }
7759 2 : if (m_format == "json")
7760 : {
7761 2 : CPLJSonStreamingWriter oWriter(nullptr, nullptr);
7762 1 : oWriter.StartArray();
7763 10 : for (const auto &[key, value] : cpl::IterateNameValue(
7764 11 : const_cast<CSLConstList>(poDS->GetMetadata("LAYERS"))))
7765 : {
7766 5 : CPL_IGNORE_RET_VAL(key);
7767 5 : oWriter.Add(value);
7768 : }
7769 1 : oWriter.EndArray();
7770 1 : m_output = oWriter.GetString();
7771 1 : m_output += '\n';
7772 : }
7773 : else
7774 : {
7775 10 : for (const auto &[key, value] : cpl::IterateNameValue(
7776 11 : const_cast<CSLConstList>(poDS->GetMetadata("LAYERS"))))
7777 : {
7778 5 : CPL_IGNORE_RET_VAL(key);
7779 5 : m_output += value;
7780 5 : m_output += '\n';
7781 : }
7782 : }
7783 2 : return true;
7784 : }
7785 :
7786 : /************************************************************************/
7787 : /* GDALPDFInstantiateAlgorithm() */
7788 : /************************************************************************/
7789 :
7790 : static GDALAlgorithm *
7791 13 : GDALPDFInstantiateAlgorithm(const std::vector<std::string> &aosPath)
7792 : {
7793 13 : if (aosPath.size() == 1 && aosPath[0] == "list-layers")
7794 : {
7795 13 : return std::make_unique<GDALPDFListLayersAlgorithm>().release();
7796 : }
7797 : else
7798 : {
7799 0 : return nullptr;
7800 : }
7801 : }
7802 :
7803 : #endif // HAVE_PDF_READ_SUPPORT
7804 :
7805 : /************************************************************************/
7806 : /* GDALRegister_PDF() */
7807 : /************************************************************************/
7808 :
7809 18 : void GDALRegister_PDF()
7810 :
7811 : {
7812 18 : if (!GDAL_CHECK_VERSION("PDF driver"))
7813 0 : return;
7814 :
7815 18 : if (GDALGetDriverByName(DRIVER_NAME) != nullptr)
7816 0 : return;
7817 :
7818 18 : GDALDriver *poDriver = new GDALDriver();
7819 18 : PDFDriverSetCommonMetadata(poDriver);
7820 :
7821 : #ifdef HAVE_PDF_READ_SUPPORT
7822 18 : poDriver->pfnOpen = PDFDataset::OpenWrapper;
7823 18 : poDriver->pfnInstantiateAlgorithm = GDALPDFInstantiateAlgorithm;
7824 : #endif // HAVE_PDF_READ_SUPPORT
7825 :
7826 18 : poDriver->pfnCreateCopy = GDALPDFCreateCopy;
7827 18 : poDriver->pfnCreate = PDFWritableVectorDataset::Create;
7828 18 : poDriver->pfnUnloadDriver = GDALPDFUnloadDriver;
7829 :
7830 18 : GetGDALDriverManager()->RegisterDriver(poDriver);
7831 : }
|