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