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