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 1363 : PDFRasterBand::PDFRasterBand(PDFDataset *poDSIn, int nBandIn,
489 1363 : int nResolutionLevelIn)
490 1363 : : nResolutionLevel(nResolutionLevelIn)
491 : {
492 1363 : poDS = poDSIn;
493 1363 : nBand = nBandIn;
494 :
495 1363 : eDataType = GDT_Byte;
496 :
497 1363 : if (nResolutionLevel > 0)
498 : {
499 8 : nBlockXSize = 256;
500 8 : nBlockYSize = 256;
501 8 : poDSIn->SetMetadataItem("INTERLEAVE", "PIXEL", "IMAGE_STRUCTURE");
502 : }
503 1355 : 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 1283 : else if (poDSIn->GetRasterXSize() <
510 1283 : 64 * 1024 * 1024 / poDSIn->GetRasterYSize())
511 : {
512 1279 : nBlockXSize = poDSIn->GetRasterXSize();
513 1279 : 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 1363 : }
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 2726 : PDFRasterBand::~PDFRasterBand()
641 : {
642 2726 : }
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 443 : bool operator()(char const *a, char const *b) const
1028 : {
1029 443 : return strcmp(a, b) < 0;
1030 : }
1031 : };
1032 :
1033 5149 : static int GDALPdfiumGetBlock(void *param, unsigned long position,
1034 : unsigned char *pBuf, unsigned long size)
1035 : {
1036 5149 : VSILFILE *fp = static_cast<VSILFILE *>(param);
1037 5149 : VSIFSeekL(fp, position, SEEK_SET);
1038 5149 : 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 226 : 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 226 : if (doc)
1060 226 : *doc = nullptr;
1061 226 : if (page)
1062 226 : *page = nullptr;
1063 226 : if (pnPageCount)
1064 226 : *pnPageCount = 0;
1065 :
1066 : // Loading document and page must be only in one thread!
1067 226 : CPLCreateOrAcquireMutex(&g_oPdfiumLoadDocMutex, PDFIUM_MUTEX_TIMEOUT);
1068 :
1069 : // Library can be destroyed if every PDF dataset was closed!
1070 226 : if (!PDFDataset::g_bPdfiumInit)
1071 : {
1072 202 : FPDF_InitLibrary();
1073 202 : PDFDataset::g_bPdfiumInit = TRUE;
1074 : }
1075 :
1076 226 : TMapPdfiumDatasets::iterator it;
1077 226 : it = g_mPdfiumDatasets.find(pszFilename);
1078 226 : TPdfiumDocumentStruct *poDoc = nullptr;
1079 : // Load new document if missing
1080 226 : if (it == g_mPdfiumDatasets.end())
1081 : {
1082 : // Try without password (if PDF not requires password it can fail)
1083 :
1084 216 : VSILFILE *fp = VSIFOpenL(pszFilename, "rb");
1085 216 : if (fp == nullptr)
1086 : {
1087 1 : CPLReleaseMutex(g_oPdfiumLoadDocMutex);
1088 1 : return FALSE;
1089 : }
1090 215 : VSIFSeekL(fp, 0, SEEK_END);
1091 215 : const auto nFileLen64 = VSIFTellL(fp);
1092 : if constexpr (LONG_MAX < std::numeric_limits<vsi_l_offset>::max())
1093 : {
1094 215 : if (nFileLen64 > LONG_MAX)
1095 : {
1096 0 : VSIFCloseL(fp);
1097 0 : CPLReleaseMutex(g_oPdfiumLoadDocMutex);
1098 0 : return FALSE;
1099 : }
1100 : }
1101 :
1102 215 : FPDF_FILEACCESS *psFileAccess = new FPDF_FILEACCESS;
1103 215 : psFileAccess->m_Param = fp;
1104 215 : psFileAccess->m_FileLen = static_cast<unsigned long>(nFileLen64);
1105 215 : psFileAccess->m_GetBlock = GDALPdfiumGetBlock;
1106 215 : CPDF_Document *docPdfium = CPDFDocumentFromFPDFDocument(
1107 : FPDF_LoadCustomDocument(psFileAccess, nullptr));
1108 215 : 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 203 : poDoc = new TPdfiumDocumentStruct;
1165 203 : 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 203 : poDoc->filename = CPLStrdup(pszFilename);
1176 203 : poDoc->doc = docPdfium;
1177 203 : poDoc->psFileAccess = psFileAccess;
1178 :
1179 203 : 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 213 : int nPages = poDoc->doc->GetPageCount();
1189 213 : 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 212 : 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 212 : TMapPdfiumPages::iterator itPage;
1212 212 : itPage = poDoc->pages.find(pageNum);
1213 212 : TPdfiumPageStruct *poPage = nullptr;
1214 : // Page not loaded
1215 212 : if (itPage == poDoc->pages.end())
1216 : {
1217 207 : auto pDict = poDoc->doc->GetMutablePageDictionary(pageNum - 1);
1218 207 : 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 207 : auto pPage = pdfium::MakeRetain<CPDF_Page>(poDoc->doc, pDict);
1227 :
1228 207 : poPage = new TPdfiumPageStruct;
1229 207 : 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 207 : poPage->pageNum = pageNum;
1238 207 : poPage->page = pPage.Leak();
1239 207 : poPage->readMutex = nullptr;
1240 207 : poPage->sharedNum = 0;
1241 :
1242 207 : 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 212 : ++poPage->sharedNum;
1252 :
1253 212 : if (doc)
1254 212 : *doc = poDoc;
1255 212 : if (page)
1256 212 : *page = poPage;
1257 212 : if (pnPageCount)
1258 212 : *pnPageCount = nPages;
1259 :
1260 212 : CPLReleaseMutex(g_oPdfiumLoadDocMutex);
1261 :
1262 212 : return TRUE;
1263 : }
1264 :
1265 : // ~ static int LoadPdfiumDocumentPage()
1266 :
1267 212 : static int UnloadPdfiumDocumentPage(TPdfiumDocumentStruct **doc,
1268 : TPdfiumPageStruct **page)
1269 : {
1270 212 : if (!doc || !page)
1271 0 : return FALSE;
1272 :
1273 212 : TPdfiumPageStruct *pPage = *page;
1274 212 : TPdfiumDocumentStruct *pDoc = *doc;
1275 :
1276 : // Get mutex for loading pdfium
1277 212 : CPLCreateOrAcquireMutex(&g_oPdfiumLoadDocMutex, PDFIUM_MUTEX_TIMEOUT);
1278 :
1279 : // Decrease page use
1280 212 : --pPage->sharedNum;
1281 :
1282 : #ifdef DEBUG
1283 212 : CPLDebug("PDF", "PDFDataset::UnloadPdfiumDocumentPage: page shared num %d",
1284 : pPage->sharedNum);
1285 : #endif
1286 : // Page is used (also document)
1287 212 : if (pPage->sharedNum != 0)
1288 : {
1289 5 : CPLReleaseMutex(g_oPdfiumLoadDocMutex);
1290 5 : return TRUE;
1291 : }
1292 :
1293 : // Get mutex, release and destroy it
1294 207 : CPLCreateOrAcquireMutex(&(pPage->readMutex), PDFIUM_MUTEX_TIMEOUT);
1295 207 : CPLReleaseMutex(pPage->readMutex);
1296 207 : CPLDestroyMutex(pPage->readMutex);
1297 : // Close page and remove from map
1298 207 : FPDF_ClosePage(FPDFPageFromIPDFPage(pPage->page));
1299 :
1300 207 : pDoc->pages.erase(pPage->pageNum);
1301 207 : delete pPage;
1302 207 : pPage = nullptr;
1303 :
1304 : #ifdef DEBUG
1305 207 : CPLDebug("PDF", "PDFDataset::UnloadPdfiumDocumentPage: pages %lu",
1306 : pDoc->pages.size());
1307 : #endif
1308 : // Another page is used
1309 207 : if (!pDoc->pages.empty())
1310 : {
1311 4 : CPLReleaseMutex(g_oPdfiumLoadDocMutex);
1312 4 : return TRUE;
1313 : }
1314 :
1315 : // Close document and remove from map
1316 203 : FPDF_CloseDocument(FPDFDocumentFromCPDFDocument(pDoc->doc));
1317 203 : g_mPdfiumDatasets.erase(pDoc->filename);
1318 203 : CPLFree(pDoc->filename);
1319 203 : VSIFCloseL(static_cast<VSILFILE *>(pDoc->psFileAccess->m_Param));
1320 203 : delete pDoc->psFileAccess;
1321 203 : delete pDoc;
1322 203 : pDoc = nullptr;
1323 :
1324 : #ifdef DEBUG
1325 203 : CPLDebug("PDF", "PDFDataset::UnloadPdfiumDocumentPage: documents %lu",
1326 : g_mPdfiumDatasets.size());
1327 : #endif
1328 : // Another document is used
1329 203 : if (!g_mPdfiumDatasets.empty())
1330 : {
1331 3 : CPLReleaseMutex(g_oPdfiumLoadDocMutex);
1332 3 : return TRUE;
1333 : }
1334 :
1335 : #ifdef DEBUG
1336 200 : CPLDebug("PDF", "PDFDataset::UnloadPdfiumDocumentPage: Nothing loaded, "
1337 : "destroy Library");
1338 : #endif
1339 : // No document loaded, destroy pdfium
1340 200 : FPDF_DestroyLibrary();
1341 200 : PDFDataset::g_bPdfiumInit = FALSE;
1342 :
1343 200 : CPLReleaseMutex(g_oPdfiumLoadDocMutex);
1344 :
1345 200 : return TRUE;
1346 : }
1347 :
1348 : // ~ static int UnloadPdfiumDocumentPage()
1349 :
1350 : #endif // ~ HAVE_PDFIUM
1351 :
1352 : /************************************************************************/
1353 : /* GetOption() */
1354 : /************************************************************************/
1355 :
1356 2438 : const char *PDFDataset::GetOption(char **papszOpenOptionsIn,
1357 : const char *pszOptionName,
1358 : const char *pszDefaultVal)
1359 : {
1360 2438 : CPLErr eLastErrType = CPLGetLastErrorType();
1361 2438 : CPLErrorNum nLastErrno = CPLGetLastErrorNo();
1362 4876 : CPLString osLastErrorMsg(CPLGetLastErrorMsg());
1363 2438 : CPLXMLNode *psNode = CPLParseXMLString(PDFGetOpenOptionList());
1364 2438 : CPLErrorSetState(eLastErrType, nLastErrno, osLastErrorMsg);
1365 2438 : if (psNode == nullptr)
1366 0 : return pszDefaultVal;
1367 2438 : CPLXMLNode *psIter = psNode->psChild;
1368 11128 : while (psIter != nullptr)
1369 : {
1370 11128 : if (EQUAL(CPLGetXMLValue(psIter, "name", ""), pszOptionName))
1371 : {
1372 : const char *pszVal =
1373 2438 : CSLFetchNameValue(papszOpenOptionsIn, pszOptionName);
1374 2438 : if (pszVal != nullptr)
1375 : {
1376 36 : CPLDestroyXMLNode(psNode);
1377 36 : return pszVal;
1378 : }
1379 : const char *pszAltConfigOption =
1380 2402 : CPLGetXMLValue(psIter, "alt_config_option", nullptr);
1381 2402 : if (pszAltConfigOption != nullptr)
1382 : {
1383 2402 : pszVal = CPLGetConfigOption(pszAltConfigOption, pszDefaultVal);
1384 2402 : CPLDestroyXMLNode(psNode);
1385 2402 : return pszVal;
1386 : }
1387 0 : CPLDestroyXMLNode(psNode);
1388 0 : return pszDefaultVal;
1389 : }
1390 8690 : 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 381 : PDFDataset::PDFDataset(PDFDataset *poParentDSIn, int nXSize, int nYSize)
2404 381 : : m_bIsOvrDS(poParentDSIn != nullptr),
2405 : #ifdef HAVE_PDFIUM
2406 381 : m_poDocPdfium(poParentDSIn ? poParentDSIn->m_poDocPdfium : nullptr),
2407 381 : m_poPagePdfium(poParentDSIn ? poParentDSIn->m_poPagePdfium : nullptr),
2408 : #endif
2409 1143 : m_bSetStyle(CPLTestBool(CPLGetConfigOption("OGR_PDF_SET_STYLE", "YES")))
2410 : {
2411 381 : m_oSRS.SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER);
2412 381 : nRasterXSize = nXSize;
2413 381 : nRasterYSize = nYSize;
2414 381 : if (poParentDSIn)
2415 2 : m_bUseLib = poParentDSIn->m_bUseLib;
2416 :
2417 381 : InitMapOperators();
2418 381 : }
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 1222 : GDALPDFObject *PDFDataset::GetCatalog()
2479 : {
2480 1222 : if (m_poCatalogObject)
2481 843 : return m_poCatalogObject;
2482 :
2483 : #ifdef HAVE_POPPLER
2484 379 : 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 379 : if (m_bUseLib.test(PDFLIB_PDFIUM) && m_poDocPdfium)
2522 : {
2523 : RetainPtr<CPDF_Dictionary> catalog =
2524 424 : m_poDocPdfium->doc->GetMutableRoot();
2525 212 : if (catalog)
2526 212 : m_poCatalogObject = GDALPDFObjectPdfium::Build(catalog);
2527 : }
2528 : #endif // ~ HAVE_PDFIUM
2529 :
2530 379 : return m_poCatalogObject;
2531 : }
2532 :
2533 : /************************************************************************/
2534 : /* ~PDFDataset() */
2535 : /************************************************************************/
2536 :
2537 762 : PDFDataset::~PDFDataset()
2538 : {
2539 : #ifdef HAVE_PDFIUM
2540 381 : m_apoOvrDS.clear();
2541 381 : m_apoOvrDSBackup.clear();
2542 : #endif
2543 :
2544 381 : CPLFree(m_pabyCachedData);
2545 381 : m_pabyCachedData = nullptr;
2546 :
2547 381 : delete m_poNeatLine;
2548 381 : m_poNeatLine = nullptr;
2549 :
2550 : /* Collect data necessary to update */
2551 381 : int nNum = 0;
2552 381 : int nGen = 0;
2553 381 : GDALPDFDictionaryRW *poPageDictCopy = nullptr;
2554 381 : GDALPDFDictionaryRW *poCatalogDictCopy = nullptr;
2555 381 : if (m_poPageObj)
2556 : {
2557 379 : nNum = m_poPageObj->GetRefNum().toInt();
2558 379 : nGen = m_poPageObj->GetRefGen();
2559 781 : if (eAccess == GA_Update &&
2560 23 : (m_bProjDirty || m_bNeatLineDirty || m_bInfoDirty || m_bXMPDirty) &&
2561 425 : 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 381 : delete m_poPageObj;
2582 381 : m_poPageObj = nullptr;
2583 381 : delete m_poCatalogObject;
2584 381 : m_poCatalogObject = nullptr;
2585 : #ifdef HAVE_POPPLER
2586 381 : if (m_bUseLib.test(PDFLIB_POPPLER))
2587 : {
2588 167 : m_poCatalogObjectPoppler.reset();
2589 167 : PDFFreeDoc(m_poDocPoppler);
2590 : }
2591 381 : 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 381 : if (!m_bIsOvrDS)
2602 : {
2603 377 : if (m_bUseLib.test(PDFLIB_PDFIUM))
2604 : {
2605 212 : UnloadPdfiumDocumentPage(&m_poDocPdfium, &m_poPagePdfium);
2606 : }
2607 : }
2608 381 : m_poDocPdfium = nullptr;
2609 381 : m_poPagePdfium = nullptr;
2610 : #endif // ~ HAVE_PDFIUM
2611 :
2612 381 : m_bHasLoadedLayers = true;
2613 381 : m_apoLayers.clear();
2614 :
2615 : /* Now do the update */
2616 381 : if (poPageDictCopy)
2617 : {
2618 23 : VSILFILE *fp = VSIFOpenL(m_osFilename, "rb+");
2619 23 : if (fp != nullptr)
2620 : {
2621 46 : GDALPDFUpdateWriter oWriter(fp);
2622 23 : if (oWriter.ParseTrailerAndXRef())
2623 : {
2624 23 : if ((m_bProjDirty || m_bNeatLineDirty) &&
2625 : poPageDictCopy != nullptr)
2626 11 : oWriter.UpdateProj(this, m_dfDPI, poPageDictCopy,
2627 22 : GDALPDFObjectNum(nNum), nGen);
2628 :
2629 23 : if (m_bInfoDirty)
2630 6 : oWriter.UpdateInfo(this);
2631 :
2632 23 : if (m_bXMPDirty && poCatalogDictCopy != nullptr)
2633 6 : oWriter.UpdateXMP(this, poCatalogDictCopy);
2634 : }
2635 23 : oWriter.Close();
2636 : }
2637 : else
2638 : {
2639 0 : CPLError(CE_Failure, CPLE_AppDefined,
2640 : "Cannot open %s in update mode", m_osFilename.c_str());
2641 : }
2642 : }
2643 381 : delete poPageDictCopy;
2644 381 : poPageDictCopy = nullptr;
2645 381 : delete poCatalogDictCopy;
2646 381 : poCatalogDictCopy = nullptr;
2647 :
2648 381 : if (m_nGCPCount > 0)
2649 : {
2650 2 : GDALDeinitGCPs(m_nGCPCount, m_pasGCPList);
2651 2 : CPLFree(m_pasGCPList);
2652 2 : m_pasGCPList = nullptr;
2653 2 : m_nGCPCount = 0;
2654 : }
2655 :
2656 381 : CleanupIntermediateResources();
2657 :
2658 : // Do that only after having destroyed Poppler objects
2659 381 : m_fp.reset();
2660 762 : }
2661 :
2662 : /************************************************************************/
2663 : /* IRasterIO() */
2664 : /************************************************************************/
2665 :
2666 1674 : CPLErr PDFDataset::IRasterIO(GDALRWFlag eRWFlag, int nXOff, int nYOff,
2667 : int nXSize, int nYSize, void *pData, int nBufXSize,
2668 : int nBufYSize, GDALDataType eBufType,
2669 : int nBandCount, BANDMAP_TYPE panBandMap,
2670 : GSpacing nPixelSpace, GSpacing nLineSpace,
2671 : GSpacing nBandSpace,
2672 : GDALRasterIOExtraArg *psExtraArg)
2673 : {
2674 : // Try to pass the request to the most appropriate overview dataset.
2675 1674 : if (nBufXSize < nXSize && nBufYSize < nYSize)
2676 : {
2677 0 : int bTried = FALSE;
2678 0 : const CPLErr eErr = TryOverviewRasterIO(
2679 : eRWFlag, nXOff, nYOff, nXSize, nYSize, pData, nBufXSize, nBufYSize,
2680 : eBufType, nBandCount, panBandMap, nPixelSpace, nLineSpace,
2681 : nBandSpace, psExtraArg, &bTried);
2682 0 : if (bTried)
2683 0 : return eErr;
2684 : }
2685 :
2686 : int nBandBlockXSize, nBandBlockYSize;
2687 1674 : int bReadPixels = FALSE;
2688 1674 : GetRasterBand(1)->GetBlockSize(&nBandBlockXSize, &nBandBlockYSize);
2689 3348 : if (m_aiTiles.empty() && eRWFlag == GF_Read && nXSize == nBufXSize &&
2690 1674 : nYSize == nBufYSize &&
2691 1674 : (nBufXSize > nBandBlockXSize || nBufYSize > nBandBlockYSize) &&
2692 3350 : eBufType == GDT_Byte && nBandCount == nBands &&
2693 2 : IsAllBands(nBandCount, panBandMap))
2694 : {
2695 2 : bReadPixels = TRUE;
2696 : #ifdef HAVE_PODOFO
2697 : if (m_bUseLib.test(PDFLIB_PODOFO) && nBands == 4)
2698 : {
2699 : bReadPixels = FALSE;
2700 : }
2701 : #endif
2702 : }
2703 :
2704 1674 : if (bReadPixels)
2705 2 : return ReadPixels(nXOff, nYOff, nXSize, nYSize, nPixelSpace, nLineSpace,
2706 2 : nBandSpace, static_cast<GByte *>(pData));
2707 :
2708 1672 : if (nBufXSize != nXSize || nBufYSize != nYSize || eBufType != GDT_Byte)
2709 : {
2710 0 : m_bCacheBlocksForOtherBands = true;
2711 : }
2712 1672 : CPLErr eErr = GDALPamDataset::IRasterIO(
2713 : eRWFlag, nXOff, nYOff, nXSize, nYSize, pData, nBufXSize, nBufYSize,
2714 : eBufType, nBandCount, panBandMap, nPixelSpace, nLineSpace, nBandSpace,
2715 : psExtraArg);
2716 1672 : m_bCacheBlocksForOtherBands = false;
2717 1672 : return eErr;
2718 : }
2719 :
2720 : /************************************************************************/
2721 : /* IRasterIO() */
2722 : /************************************************************************/
2723 :
2724 43215 : CPLErr PDFRasterBand::IRasterIO(GDALRWFlag eRWFlag, int nXOff, int nYOff,
2725 : int nXSize, int nYSize, void *pData,
2726 : int nBufXSize, int nBufYSize,
2727 : GDALDataType eBufType, GSpacing nPixelSpace,
2728 : GSpacing nLineSpace,
2729 : GDALRasterIOExtraArg *psExtraArg)
2730 : {
2731 43215 : PDFDataset *poGDS = cpl::down_cast<PDFDataset *>(poDS);
2732 :
2733 : // Try to pass the request to the most appropriate overview dataset.
2734 43215 : if (nBufXSize < nXSize && nBufYSize < nYSize)
2735 : {
2736 0 : int bTried = FALSE;
2737 0 : const CPLErr eErr = TryOverviewRasterIO(
2738 : eRWFlag, nXOff, nYOff, nXSize, nYSize, pData, nBufXSize, nBufYSize,
2739 : eBufType, nPixelSpace, nLineSpace, psExtraArg, &bTried);
2740 0 : if (bTried)
2741 0 : return eErr;
2742 : }
2743 :
2744 43215 : if (nBufXSize != nXSize || nBufYSize != nYSize || eBufType != GDT_Byte)
2745 : {
2746 38177 : poGDS->m_bCacheBlocksForOtherBands = true;
2747 : }
2748 43215 : CPLErr eErr = GDALPamRasterBand::IRasterIO(
2749 : eRWFlag, nXOff, nYOff, nXSize, nYSize, pData, nBufXSize, nBufYSize,
2750 : eBufType, nPixelSpace, nLineSpace, psExtraArg);
2751 43215 : poGDS->m_bCacheBlocksForOtherBands = false;
2752 43215 : return eErr;
2753 : }
2754 :
2755 : /************************************************************************/
2756 : /* PDFDatasetErrorFunction() */
2757 : /************************************************************************/
2758 :
2759 : #ifdef HAVE_POPPLER
2760 :
2761 2 : static void PDFDatasetErrorFunctionCommon(const CPLString &osError)
2762 : {
2763 2 : if (strcmp(osError.c_str(), "Incorrect password") == 0)
2764 2 : return;
2765 : /* Reported on newer USGS GeoPDF */
2766 0 : if (strcmp(osError.c_str(),
2767 0 : "Couldn't find group for reference to set OFF") == 0)
2768 : {
2769 0 : CPLDebug("PDF", "%s", osError.c_str());
2770 0 : return;
2771 : }
2772 :
2773 0 : CPLError(CE_Failure, CPLE_AppDefined, "%s", osError.c_str());
2774 : }
2775 :
2776 : static int g_nPopplerErrors = 0;
2777 : constexpr int MAX_POPPLER_ERRORS = 1000;
2778 :
2779 2 : static void PDFDatasetErrorFunction(ErrorCategory /* eErrCategory */,
2780 : Goffset nPos, const char *pszMsg)
2781 : {
2782 2 : if (g_nPopplerErrors >= MAX_POPPLER_ERRORS)
2783 : {
2784 : // If there are too many errors, then unregister ourselves and turn
2785 : // quiet error mode, as the error() function in poppler can spend
2786 : // significant time formatting an error message we won't emit...
2787 0 : setErrorCallback(nullptr);
2788 0 : globalParams->setErrQuiet(true);
2789 0 : return;
2790 : }
2791 :
2792 2 : g_nPopplerErrors++;
2793 4 : CPLString osError;
2794 :
2795 2 : if (nPos >= 0)
2796 : osError.Printf("Pos = " CPL_FRMT_GUIB ", ",
2797 0 : static_cast<GUIntBig>(nPos));
2798 2 : osError += pszMsg;
2799 2 : PDFDatasetErrorFunctionCommon(osError);
2800 : }
2801 : #endif
2802 :
2803 : /************************************************************************/
2804 : /* GDALPDFParseStreamContentOnlyDrawForm() */
2805 : /************************************************************************/
2806 :
2807 353 : static CPLString GDALPDFParseStreamContentOnlyDrawForm(const char *pszContent)
2808 : {
2809 706 : CPLString osToken;
2810 : char ch;
2811 353 : int nCurIdx = 0;
2812 706 : CPLString osCurrentForm;
2813 :
2814 : // CPLDebug("PDF", "content = %s", pszContent);
2815 :
2816 1186 : while ((ch = *pszContent) != '\0')
2817 : {
2818 1186 : if (ch == '%')
2819 : {
2820 : /* Skip comments until end-of-line */
2821 0 : while ((ch = *pszContent) != '\0')
2822 : {
2823 0 : if (ch == '\r' || ch == '\n')
2824 : break;
2825 0 : pszContent++;
2826 : }
2827 0 : if (ch == 0)
2828 0 : break;
2829 : }
2830 1186 : else if (ch == ' ' || ch == '\r' || ch == '\n')
2831 : {
2832 406 : if (!osToken.empty())
2833 : {
2834 406 : if (nCurIdx == 0 && osToken[0] == '/')
2835 : {
2836 53 : osCurrentForm = osToken.substr(1);
2837 53 : nCurIdx++;
2838 : }
2839 353 : else if (nCurIdx == 1 && osToken == "Do")
2840 : {
2841 0 : nCurIdx++;
2842 : }
2843 : else
2844 : {
2845 353 : return "";
2846 : }
2847 : }
2848 53 : osToken = "";
2849 : }
2850 : else
2851 780 : osToken += ch;
2852 833 : pszContent++;
2853 : }
2854 :
2855 0 : return osCurrentForm;
2856 : }
2857 :
2858 : /************************************************************************/
2859 : /* GDALPDFParseStreamContent() */
2860 : /************************************************************************/
2861 :
2862 : typedef enum
2863 : {
2864 : STATE_INIT,
2865 : STATE_AFTER_q,
2866 : STATE_AFTER_cm,
2867 : STATE_AFTER_Do
2868 : } PDFStreamState;
2869 :
2870 : /* This parser is reduced to understanding sequences that draw rasters, such as
2871 : :
2872 : q
2873 : scaleX 0 0 scaleY translateX translateY cm
2874 : /ImXXX Do
2875 : Q
2876 :
2877 : All other sequences will abort the parsing.
2878 :
2879 : Returns TRUE if the stream only contains images.
2880 : */
2881 :
2882 353 : static int GDALPDFParseStreamContent(const char *pszContent,
2883 : GDALPDFDictionary *poXObjectDict,
2884 : double *pdfDPI, int *pbDPISet,
2885 : int *pnBands,
2886 : std::vector<GDALPDFTileDesc> &asTiles,
2887 : int bAcceptRotationTerms)
2888 : {
2889 706 : CPLString osToken;
2890 : char ch;
2891 353 : PDFStreamState nState = STATE_INIT;
2892 353 : int nCurIdx = 0;
2893 : double adfVals[6];
2894 706 : CPLString osCurrentImage;
2895 :
2896 353 : double dfDPI = DEFAULT_DPI;
2897 353 : *pbDPISet = FALSE;
2898 :
2899 21686 : while ((ch = *pszContent) != '\0')
2900 : {
2901 21417 : if (ch == '%')
2902 : {
2903 : /* Skip comments until end-of-line */
2904 0 : while ((ch = *pszContent) != '\0')
2905 : {
2906 0 : if (ch == '\r' || ch == '\n')
2907 : break;
2908 0 : pszContent++;
2909 : }
2910 0 : if (ch == 0)
2911 0 : break;
2912 : }
2913 21417 : else if (ch == ' ' || ch == '\t' || ch == '\r' || ch == '\n')
2914 : {
2915 6453 : if (!osToken.empty())
2916 : {
2917 6453 : if (nState == STATE_INIT)
2918 : {
2919 663 : if (osToken == "q")
2920 : {
2921 579 : nState = STATE_AFTER_q;
2922 579 : nCurIdx = 0;
2923 : }
2924 84 : else if (osToken != "Q")
2925 84 : return FALSE;
2926 : }
2927 5790 : else if (nState == STATE_AFTER_q)
2928 : {
2929 4053 : if (osToken == "q")
2930 : {
2931 : // ignore
2932 : }
2933 4053 : else if (nCurIdx < 6)
2934 : {
2935 3474 : adfVals[nCurIdx++] = CPLAtof(osToken);
2936 : }
2937 579 : else if (nCurIdx == 6 && osToken == "cm")
2938 : {
2939 579 : nState = STATE_AFTER_cm;
2940 579 : nCurIdx = 0;
2941 : }
2942 : else
2943 0 : return FALSE;
2944 : }
2945 1737 : else if (nState == STATE_AFTER_cm)
2946 : {
2947 1158 : if (nCurIdx == 0 && osToken[0] == '/')
2948 : {
2949 579 : osCurrentImage = osToken.substr(1);
2950 : }
2951 579 : else if (osToken == "Do")
2952 : {
2953 579 : nState = STATE_AFTER_Do;
2954 : }
2955 : else
2956 0 : return FALSE;
2957 : }
2958 579 : else if (nState == STATE_AFTER_Do)
2959 : {
2960 579 : if (osToken == "Q")
2961 : {
2962 : GDALPDFObject *poImage =
2963 579 : poXObjectDict->Get(osCurrentImage);
2964 1158 : if (poImage != nullptr &&
2965 579 : poImage->GetType() == PDFObjectType_Dictionary)
2966 : {
2967 : GDALPDFTileDesc sTile;
2968 : GDALPDFDictionary *poImageDict =
2969 579 : poImage->GetDictionary();
2970 579 : GDALPDFObject *poWidth = poImageDict->Get("Width");
2971 : GDALPDFObject *poHeight =
2972 579 : poImageDict->Get("Height");
2973 : GDALPDFObject *poColorSpace =
2974 579 : poImageDict->Get("ColorSpace");
2975 579 : GDALPDFObject *poSMask = poImageDict->Get("SMask");
2976 1158 : if (poColorSpace &&
2977 579 : poColorSpace->GetType() == PDFObjectType_Name)
2978 : {
2979 573 : if (poColorSpace->GetName() == "DeviceRGB")
2980 : {
2981 221 : sTile.nBands = 3;
2982 221 : if (*pnBands < 3)
2983 47 : *pnBands = 3;
2984 : }
2985 352 : else if (poColorSpace->GetName() ==
2986 : "DeviceGray")
2987 : {
2988 352 : sTile.nBands = 1;
2989 352 : if (*pnBands < 1)
2990 244 : *pnBands = 1;
2991 : }
2992 : else
2993 0 : sTile.nBands = 0;
2994 : }
2995 579 : if (poSMask != nullptr)
2996 190 : *pnBands = 4;
2997 :
2998 579 : if (poWidth && poHeight &&
2999 0 : ((bAcceptRotationTerms &&
3000 579 : adfVals[1] == -adfVals[2]) ||
3001 579 : (!bAcceptRotationTerms && adfVals[1] == 0.0 &&
3002 579 : adfVals[2] == 0.0)))
3003 : {
3004 579 : double dfWidth = Get(poWidth);
3005 579 : double dfHeight = Get(poHeight);
3006 579 : double dfScaleX = adfVals[0];
3007 579 : double dfScaleY = adfVals[3];
3008 579 : if (dfWidth > 0 && dfHeight > 0 &&
3009 579 : dfScaleX > 0 && dfScaleY > 0 &&
3010 579 : dfWidth / dfScaleX * DEFAULT_DPI <
3011 579 : INT_MAX &&
3012 579 : dfHeight / dfScaleY * DEFAULT_DPI < INT_MAX)
3013 : {
3014 1158 : double dfDPI_X = ROUND_IF_CLOSE(
3015 579 : dfWidth / dfScaleX * DEFAULT_DPI, 1e-3);
3016 1158 : double dfDPI_Y = ROUND_IF_CLOSE(
3017 579 : dfHeight / dfScaleY * DEFAULT_DPI,
3018 : 1e-3);
3019 : // CPLDebug("PDF", "Image %s, width = %.16g,
3020 : // height = %.16g, scaleX = %.16g, scaleY =
3021 : // %.16g --> DPI_X = %.16g, DPI_Y = %.16g",
3022 : // osCurrentImage.c_str(),
3023 : // dfWidth, dfHeight,
3024 : // dfScaleX, dfScaleY,
3025 : // dfDPI_X, dfDPI_Y);
3026 579 : if (dfDPI_X > dfDPI)
3027 40 : dfDPI = dfDPI_X;
3028 579 : if (dfDPI_Y > dfDPI)
3029 0 : dfDPI = dfDPI_Y;
3030 :
3031 579 : memcpy(&(sTile.adfCM), adfVals,
3032 : 6 * sizeof(double));
3033 579 : sTile.poImage = poImage;
3034 579 : sTile.dfWidth = dfWidth;
3035 579 : sTile.dfHeight = dfHeight;
3036 579 : asTiles.push_back(sTile);
3037 :
3038 579 : *pbDPISet = TRUE;
3039 579 : *pdfDPI = dfDPI;
3040 : }
3041 : }
3042 : }
3043 579 : nState = STATE_INIT;
3044 : }
3045 : else
3046 0 : return FALSE;
3047 : }
3048 : }
3049 6369 : osToken = "";
3050 : }
3051 : else
3052 14964 : osToken += ch;
3053 21333 : pszContent++;
3054 : }
3055 :
3056 269 : return TRUE;
3057 : }
3058 :
3059 : /************************************************************************/
3060 : /* CheckTiledRaster() */
3061 : /************************************************************************/
3062 :
3063 297 : int PDFDataset::CheckTiledRaster()
3064 : {
3065 : size_t i;
3066 297 : int l_nBlockXSize = 0;
3067 297 : int l_nBlockYSize = 0;
3068 297 : const double dfUserUnit = m_dfDPI * USER_UNIT_IN_INCH;
3069 :
3070 : /* First pass : check that all tiles have same DPI, */
3071 : /* are contained entirely in the raster size, */
3072 : /* and determine the block size */
3073 870 : for (i = 0; i < m_asTiles.size(); i++)
3074 : {
3075 579 : double dfDrawWidth = m_asTiles[i].adfCM[0] * dfUserUnit;
3076 579 : double dfDrawHeight = m_asTiles[i].adfCM[3] * dfUserUnit;
3077 579 : double dfX = m_asTiles[i].adfCM[4] * dfUserUnit;
3078 579 : double dfY = m_asTiles[i].adfCM[5] * dfUserUnit;
3079 579 : int nX = static_cast<int>(dfX + 0.1);
3080 579 : int nY = static_cast<int>(dfY + 0.1);
3081 579 : int nWidth = static_cast<int>(m_asTiles[i].dfWidth + 1e-8);
3082 579 : int nHeight = static_cast<int>(m_asTiles[i].dfHeight + 1e-8);
3083 :
3084 579 : GDALPDFDictionary *poImageDict = m_asTiles[i].poImage->GetDictionary();
3085 : GDALPDFObject *poBitsPerComponent =
3086 579 : poImageDict->Get("BitsPerComponent");
3087 579 : GDALPDFObject *poColorSpace = poImageDict->Get("ColorSpace");
3088 579 : GDALPDFObject *poFilter = poImageDict->Get("Filter");
3089 :
3090 : /* Podofo cannot uncompress JPEG2000 streams */
3091 579 : if (m_bUseLib.test(PDFLIB_PODOFO) && poFilter != nullptr &&
3092 579 : poFilter->GetType() == PDFObjectType_Name &&
3093 0 : poFilter->GetName() == "JPXDecode")
3094 : {
3095 0 : CPLDebug("PDF", "Tile %d : Incompatible image for tiled reading",
3096 : static_cast<int>(i));
3097 0 : return FALSE;
3098 : }
3099 :
3100 579 : if (poBitsPerComponent == nullptr || Get(poBitsPerComponent) != 8 ||
3101 579 : poColorSpace == nullptr ||
3102 2083 : poColorSpace->GetType() != PDFObjectType_Name ||
3103 925 : (poColorSpace->GetName() != "DeviceRGB" &&
3104 352 : poColorSpace->GetName() != "DeviceGray"))
3105 : {
3106 6 : CPLDebug("PDF", "Tile %d : Incompatible image for tiled reading",
3107 : static_cast<int>(i));
3108 6 : return FALSE;
3109 : }
3110 :
3111 573 : if (fabs(dfDrawWidth - m_asTiles[i].dfWidth) > 1e-2 ||
3112 573 : fabs(dfDrawHeight - m_asTiles[i].dfHeight) > 1e-2 ||
3113 573 : fabs(nWidth - m_asTiles[i].dfWidth) > 1e-8 ||
3114 573 : fabs(nHeight - m_asTiles[i].dfHeight) > 1e-8 ||
3115 573 : fabs(nX - dfX) > 1e-1 || fabs(nY - dfY) > 1e-1 || nX < 0 ||
3116 1146 : nY < 0 || nX + nWidth > nRasterXSize || nY >= nRasterYSize)
3117 : {
3118 0 : CPLDebug("PDF", "Tile %d : %f %f %f %f %f %f", static_cast<int>(i),
3119 0 : dfX, dfY, dfDrawWidth, dfDrawHeight, m_asTiles[i].dfWidth,
3120 0 : m_asTiles[i].dfHeight);
3121 0 : return FALSE;
3122 : }
3123 573 : if (l_nBlockXSize == 0 && l_nBlockYSize == 0 && nX == 0 && nY != 0)
3124 : {
3125 18 : l_nBlockXSize = nWidth;
3126 18 : l_nBlockYSize = nHeight;
3127 : }
3128 : }
3129 291 : if (l_nBlockXSize <= 0 || l_nBlockYSize <= 0 || l_nBlockXSize > 2048 ||
3130 : l_nBlockYSize > 2048)
3131 273 : return FALSE;
3132 :
3133 18 : int nXBlocks = DIV_ROUND_UP(nRasterXSize, l_nBlockXSize);
3134 18 : int nYBlocks = DIV_ROUND_UP(nRasterYSize, l_nBlockYSize);
3135 :
3136 : /* Second pass to determine that all tiles are properly aligned on block
3137 : * size */
3138 318 : for (i = 0; i < m_asTiles.size(); i++)
3139 : {
3140 300 : double dfX = m_asTiles[i].adfCM[4] * dfUserUnit;
3141 300 : double dfY = m_asTiles[i].adfCM[5] * dfUserUnit;
3142 300 : int nX = static_cast<int>(dfX + 0.1);
3143 300 : int nY = static_cast<int>(dfY + 0.1);
3144 300 : int nWidth = static_cast<int>(m_asTiles[i].dfWidth + 1e-8);
3145 300 : int nHeight = static_cast<int>(m_asTiles[i].dfHeight + 1e-8);
3146 300 : int bOK = TRUE;
3147 300 : int nBlockXOff = nX / l_nBlockXSize;
3148 300 : if ((nX % l_nBlockXSize) != 0)
3149 0 : bOK = FALSE;
3150 300 : if (nBlockXOff < nXBlocks - 1 && nWidth != l_nBlockXSize)
3151 0 : bOK = FALSE;
3152 300 : if (nBlockXOff == nXBlocks - 1 && nX + nWidth != nRasterXSize)
3153 0 : bOK = FALSE;
3154 :
3155 300 : if (nY > 0 && nHeight != l_nBlockYSize)
3156 0 : bOK = FALSE;
3157 300 : if (nY == 0 && nHeight != nRasterYSize - (nYBlocks - 1) * l_nBlockYSize)
3158 0 : bOK = FALSE;
3159 :
3160 300 : if (!bOK)
3161 : {
3162 0 : CPLDebug("PDF", "Tile %d : %d %d %d %d", static_cast<int>(i), nX,
3163 : nY, nWidth, nHeight);
3164 0 : return FALSE;
3165 : }
3166 : }
3167 :
3168 : /* Third pass to set the aiTiles array */
3169 18 : m_aiTiles.resize(static_cast<size_t>(nXBlocks) * nYBlocks, -1);
3170 318 : for (i = 0; i < m_asTiles.size(); i++)
3171 : {
3172 300 : double dfX = m_asTiles[i].adfCM[4] * dfUserUnit;
3173 300 : double dfY = m_asTiles[i].adfCM[5] * dfUserUnit;
3174 300 : int nHeight = static_cast<int>(m_asTiles[i].dfHeight + 1e-8);
3175 300 : int nX = static_cast<int>(dfX + 0.1);
3176 300 : int nY = nRasterYSize - (static_cast<int>(dfY + 0.1) + nHeight);
3177 300 : int nBlockXOff = nX / l_nBlockXSize;
3178 300 : int nBlockYOff = nY / l_nBlockYSize;
3179 300 : m_aiTiles[nBlockYOff * nXBlocks + nBlockXOff] = static_cast<int>(i);
3180 : }
3181 :
3182 18 : this->m_nBlockXSize = l_nBlockXSize;
3183 18 : this->m_nBlockYSize = l_nBlockYSize;
3184 :
3185 18 : return TRUE;
3186 : }
3187 :
3188 : /************************************************************************/
3189 : /* GuessDPI() */
3190 : /************************************************************************/
3191 :
3192 379 : void PDFDataset::GuessDPI(GDALPDFDictionary *poPageDict, int *pnBands)
3193 : {
3194 379 : const char *pszDPI = GetOption(papszOpenOptions, "DPI", nullptr);
3195 379 : if (pszDPI != nullptr)
3196 : {
3197 : // coverity[tainted_data]
3198 4 : m_dfDPI = CPLAtof(pszDPI);
3199 : }
3200 : else
3201 : {
3202 : /* Try to get a better value from the images that are drawn */
3203 : /* Very simplistic logic. Will only work for raster only PDF */
3204 :
3205 375 : GDALPDFObject *poContents = poPageDict->Get("Contents");
3206 748 : if (poContents != nullptr &&
3207 373 : poContents->GetType() == PDFObjectType_Array)
3208 : {
3209 1 : GDALPDFArray *poContentsArray = poContents->GetArray();
3210 1 : if (poContentsArray->GetLength() == 1)
3211 : {
3212 1 : poContents = poContentsArray->Get(0);
3213 : }
3214 : }
3215 :
3216 : GDALPDFObject *poXObject =
3217 375 : poPageDict->LookupObject("Resources.XObject");
3218 748 : if (poContents != nullptr &&
3219 373 : poContents->GetType() == PDFObjectType_Dictionary &&
3220 748 : poXObject != nullptr &&
3221 355 : poXObject->GetType() == PDFObjectType_Dictionary)
3222 : {
3223 355 : GDALPDFDictionary *poXObjectDict = poXObject->GetDictionary();
3224 355 : GDALPDFDictionary *poContentDict = poXObjectDict;
3225 355 : GDALPDFStream *poPageStream = poContents->GetStream();
3226 355 : if (poPageStream != nullptr)
3227 : {
3228 353 : char *pszContent = nullptr;
3229 353 : const int64_t MAX_LENGTH = 10 * 1000 * 1000;
3230 353 : int64_t nLength = poPageStream->GetLength(MAX_LENGTH);
3231 353 : int bResetTiles = FALSE;
3232 353 : double dfScaleDPI = 1.0;
3233 :
3234 353 : if (nLength < MAX_LENGTH)
3235 : {
3236 706 : CPLString osForm;
3237 353 : pszContent = poPageStream->GetBytes();
3238 353 : if (pszContent != nullptr)
3239 : {
3240 : #ifdef DEBUG
3241 : const char *pszDumpStream =
3242 353 : CPLGetConfigOption("PDF_DUMP_STREAM", nullptr);
3243 353 : if (pszDumpStream != nullptr)
3244 : {
3245 0 : VSILFILE *fpDump = VSIFOpenL(pszDumpStream, "wb");
3246 0 : if (fpDump)
3247 : {
3248 0 : VSIFWriteL(pszContent, 1,
3249 : static_cast<int>(nLength), fpDump);
3250 0 : VSIFCloseL(fpDump);
3251 : }
3252 : }
3253 : #endif // DEBUG
3254 : osForm =
3255 353 : GDALPDFParseStreamContentOnlyDrawForm(pszContent);
3256 353 : if (osForm.empty())
3257 : {
3258 : /* Special case for USGS Topo PDF, like
3259 : * CA_Hollywood_20090811_OM_geo.pdf */
3260 : const char *pszOGCDo =
3261 353 : strstr(pszContent, " /XO1 Do");
3262 353 : if (pszOGCDo)
3263 : {
3264 0 : const char *pszcm = strstr(pszContent, " cm ");
3265 0 : if (pszcm != nullptr && pszcm < pszOGCDo)
3266 : {
3267 : const char *pszNextcm =
3268 0 : strstr(pszcm + 2, "cm");
3269 0 : if (pszNextcm == nullptr ||
3270 : pszNextcm > pszOGCDo)
3271 : {
3272 0 : const char *pszIter = pszcm;
3273 0 : while (pszIter > pszContent)
3274 : {
3275 0 : if ((*pszIter >= '0' &&
3276 0 : *pszIter <= '9') ||
3277 0 : *pszIter == '-' ||
3278 0 : *pszIter == '.' ||
3279 0 : *pszIter == ' ')
3280 0 : pszIter--;
3281 : else
3282 : {
3283 0 : pszIter++;
3284 0 : break;
3285 : }
3286 : }
3287 0 : CPLString oscm(pszIter);
3288 0 : oscm.resize(pszcm - pszIter);
3289 : char **papszTokens =
3290 0 : CSLTokenizeString(oscm);
3291 0 : double dfScaleX = -1.0;
3292 0 : double dfScaleY = -2.0;
3293 0 : if (CSLCount(papszTokens) == 6)
3294 : {
3295 0 : dfScaleX = CPLAtof(papszTokens[0]);
3296 0 : dfScaleY = CPLAtof(papszTokens[3]);
3297 : }
3298 0 : CSLDestroy(papszTokens);
3299 0 : if (dfScaleX == dfScaleY &&
3300 : dfScaleX > 0.0)
3301 : {
3302 0 : osForm = "XO1";
3303 0 : bResetTiles = TRUE;
3304 0 : dfScaleDPI = 1.0 / dfScaleX;
3305 : }
3306 0 : }
3307 : }
3308 : else
3309 : {
3310 0 : osForm = "XO1";
3311 0 : bResetTiles = TRUE;
3312 : }
3313 : }
3314 : /* Special case for USGS Topo PDF, like
3315 : * CA_Sacramento_East_20120308_TM_geo.pdf */
3316 : else
3317 : {
3318 : CPLString osOCG =
3319 706 : FindLayerOCG(poPageDict, "Orthoimage");
3320 353 : if (!osOCG.empty())
3321 : {
3322 0 : const char *pszBDCLookup = CPLSPrintf(
3323 : "/OC /%s BDC", osOCG.c_str());
3324 : const char *pszBDC =
3325 0 : strstr(pszContent, pszBDCLookup);
3326 0 : if (pszBDC != nullptr)
3327 : {
3328 0 : const char *pszIter =
3329 0 : pszBDC + strlen(pszBDCLookup);
3330 0 : while (*pszIter != '\0')
3331 : {
3332 0 : if (*pszIter == 13 ||
3333 0 : *pszIter == 10 ||
3334 0 : *pszIter == ' ' ||
3335 0 : *pszIter == 'q')
3336 0 : pszIter++;
3337 : else
3338 : break;
3339 : }
3340 0 : if (STARTS_WITH(pszIter,
3341 : "1 0 0 1 0 0 cm\n"))
3342 0 : pszIter +=
3343 : strlen("1 0 0 1 0 0 cm\n");
3344 0 : if (*pszIter == '/')
3345 : {
3346 0 : pszIter++;
3347 : const char *pszDo =
3348 0 : strstr(pszIter, " Do");
3349 0 : if (pszDo != nullptr)
3350 : {
3351 0 : osForm = pszIter;
3352 0 : osForm.resize(pszDo - pszIter);
3353 0 : bResetTiles = TRUE;
3354 : }
3355 : }
3356 : }
3357 : }
3358 : }
3359 : }
3360 : }
3361 :
3362 353 : if (!osForm.empty())
3363 : {
3364 0 : CPLFree(pszContent);
3365 0 : pszContent = nullptr;
3366 :
3367 0 : GDALPDFObject *poObjForm = poXObjectDict->Get(osForm);
3368 0 : if (poObjForm != nullptr &&
3369 0 : poObjForm->GetType() == PDFObjectType_Dictionary &&
3370 0 : (poPageStream = poObjForm->GetStream()) != nullptr)
3371 : {
3372 : GDALPDFDictionary *poObjFormDict =
3373 0 : poObjForm->GetDictionary();
3374 : GDALPDFObject *poSubtype =
3375 0 : poObjFormDict->Get("Subtype");
3376 0 : if (poSubtype != nullptr &&
3377 0 : poSubtype->GetType() == PDFObjectType_Name &&
3378 0 : poSubtype->GetName() == "Form")
3379 : {
3380 0 : nLength = poPageStream->GetLength(MAX_LENGTH);
3381 0 : if (nLength < MAX_LENGTH)
3382 : {
3383 0 : pszContent = poPageStream->GetBytes();
3384 :
3385 : GDALPDFObject *poXObject2 =
3386 0 : poObjFormDict->LookupObject(
3387 : "Resources.XObject");
3388 0 : if (poXObject2 != nullptr &&
3389 0 : poXObject2->GetType() ==
3390 : PDFObjectType_Dictionary)
3391 : poContentDict =
3392 0 : poXObject2->GetDictionary();
3393 : }
3394 : }
3395 : }
3396 : }
3397 : }
3398 :
3399 353 : if (pszContent != nullptr)
3400 : {
3401 353 : int bDPISet = FALSE;
3402 :
3403 353 : const char *pszContentToParse = pszContent;
3404 353 : if (bResetTiles)
3405 : {
3406 0 : while (*pszContentToParse != '\0')
3407 : {
3408 0 : if (*pszContentToParse == 13 ||
3409 0 : *pszContentToParse == 10 ||
3410 0 : *pszContentToParse == ' ' ||
3411 0 : (*pszContentToParse >= '0' &&
3412 0 : *pszContentToParse <= '9') ||
3413 0 : *pszContentToParse == '.' ||
3414 0 : *pszContentToParse == '-' ||
3415 0 : *pszContentToParse == 'l' ||
3416 0 : *pszContentToParse == 'm' ||
3417 0 : *pszContentToParse == 'n' ||
3418 0 : *pszContentToParse == 'W')
3419 0 : pszContentToParse++;
3420 : else
3421 : break;
3422 : }
3423 : }
3424 :
3425 353 : GDALPDFParseStreamContent(pszContentToParse, poContentDict,
3426 : &(m_dfDPI), &bDPISet, pnBands,
3427 353 : m_asTiles, bResetTiles);
3428 353 : CPLFree(pszContent);
3429 353 : if (bDPISet)
3430 : {
3431 297 : m_dfDPI *= dfScaleDPI;
3432 :
3433 297 : CPLDebug("PDF",
3434 : "DPI guessed from contents stream = %.16g",
3435 : m_dfDPI);
3436 297 : SetMetadataItem("DPI", CPLSPrintf("%.16g", m_dfDPI));
3437 297 : if (bResetTiles)
3438 0 : m_asTiles.resize(0);
3439 : }
3440 : else
3441 56 : m_asTiles.resize(0);
3442 : }
3443 : }
3444 : }
3445 :
3446 375 : GDALPDFObject *poUserUnit = nullptr;
3447 686 : if ((poUserUnit = poPageDict->Get("UserUnit")) != nullptr &&
3448 311 : (poUserUnit->GetType() == PDFObjectType_Int ||
3449 23 : poUserUnit->GetType() == PDFObjectType_Real))
3450 : {
3451 311 : m_dfDPI = ROUND_IF_CLOSE(Get(poUserUnit) * DEFAULT_DPI, 1e-5);
3452 311 : CPLDebug("PDF", "Found UserUnit in Page --> DPI = %.16g", m_dfDPI);
3453 311 : SetMetadataItem("DPI", CPLSPrintf("%.16g", m_dfDPI));
3454 : }
3455 : }
3456 :
3457 379 : if (m_dfDPI < 1e-2 || m_dfDPI > 7200)
3458 : {
3459 0 : CPLError(CE_Warning, CPLE_AppDefined,
3460 : "Invalid value for GDAL_PDF_DPI. Using default value instead");
3461 0 : m_dfDPI = GDAL_DEFAULT_DPI;
3462 : }
3463 379 : }
3464 :
3465 : /************************************************************************/
3466 : /* FindXMP() */
3467 : /************************************************************************/
3468 :
3469 0 : void PDFDataset::FindXMP(GDALPDFObject *poObj)
3470 : {
3471 0 : if (poObj->GetType() != PDFObjectType_Dictionary)
3472 0 : return;
3473 :
3474 0 : GDALPDFDictionary *poDict = poObj->GetDictionary();
3475 0 : GDALPDFObject *poType = poDict->Get("Type");
3476 0 : GDALPDFObject *poSubtype = poDict->Get("Subtype");
3477 0 : if (poType == nullptr || poType->GetType() != PDFObjectType_Name ||
3478 0 : poType->GetName() != "Metadata" || poSubtype == nullptr ||
3479 0 : poSubtype->GetType() != PDFObjectType_Name ||
3480 0 : poSubtype->GetName() != "XML")
3481 : {
3482 0 : return;
3483 : }
3484 :
3485 0 : GDALPDFStream *poStream = poObj->GetStream();
3486 0 : if (poStream == nullptr)
3487 0 : return;
3488 :
3489 0 : char *pszContent = poStream->GetBytes();
3490 0 : const auto nLength = poStream->GetLength();
3491 0 : if (pszContent != nullptr && nLength > 15 &&
3492 0 : STARTS_WITH(pszContent, "<?xpacket begin="))
3493 : {
3494 : char *apszMDList[2];
3495 0 : apszMDList[0] = pszContent;
3496 0 : apszMDList[1] = nullptr;
3497 0 : SetMetadata(apszMDList, "xml:XMP");
3498 : }
3499 0 : CPLFree(pszContent);
3500 : }
3501 :
3502 : /************************************************************************/
3503 : /* ParseInfo() */
3504 : /************************************************************************/
3505 :
3506 205 : void PDFDataset::ParseInfo(GDALPDFObject *poInfoObj)
3507 : {
3508 205 : if (poInfoObj->GetType() != PDFObjectType_Dictionary)
3509 136 : return;
3510 :
3511 69 : GDALPDFDictionary *poInfoObjDict = poInfoObj->GetDictionary();
3512 69 : GDALPDFObject *poItem = nullptr;
3513 69 : int bOneMDISet = FALSE;
3514 86 : if ((poItem = poInfoObjDict->Get("Author")) != nullptr &&
3515 17 : poItem->GetType() == PDFObjectType_String)
3516 : {
3517 17 : SetMetadataItem("AUTHOR", poItem->GetString().c_str());
3518 17 : bOneMDISet = TRUE;
3519 : }
3520 115 : if ((poItem = poInfoObjDict->Get("Creator")) != nullptr &&
3521 46 : poItem->GetType() == PDFObjectType_String)
3522 : {
3523 46 : SetMetadataItem("CREATOR", poItem->GetString().c_str());
3524 46 : bOneMDISet = TRUE;
3525 : }
3526 77 : if ((poItem = poInfoObjDict->Get("Keywords")) != nullptr &&
3527 8 : poItem->GetType() == PDFObjectType_String)
3528 : {
3529 8 : SetMetadataItem("KEYWORDS", poItem->GetString().c_str());
3530 8 : bOneMDISet = TRUE;
3531 : }
3532 80 : if ((poItem = poInfoObjDict->Get("Subject")) != nullptr &&
3533 11 : poItem->GetType() == PDFObjectType_String)
3534 : {
3535 11 : SetMetadataItem("SUBJECT", poItem->GetString().c_str());
3536 11 : bOneMDISet = TRUE;
3537 : }
3538 80 : if ((poItem = poInfoObjDict->Get("Title")) != nullptr &&
3539 11 : poItem->GetType() == PDFObjectType_String)
3540 : {
3541 11 : SetMetadataItem("TITLE", poItem->GetString().c_str());
3542 11 : bOneMDISet = TRUE;
3543 : }
3544 92 : if ((poItem = poInfoObjDict->Get("Producer")) != nullptr &&
3545 23 : poItem->GetType() == PDFObjectType_String)
3546 : {
3547 34 : if (bOneMDISet ||
3548 11 : poItem->GetString() != "PoDoFo - http://podofo.sf.net")
3549 : {
3550 12 : SetMetadataItem("PRODUCER", poItem->GetString().c_str());
3551 12 : bOneMDISet = TRUE;
3552 : }
3553 : }
3554 118 : if ((poItem = poInfoObjDict->Get("CreationDate")) != nullptr &&
3555 49 : poItem->GetType() == PDFObjectType_String)
3556 : {
3557 49 : if (bOneMDISet)
3558 38 : SetMetadataItem("CREATION_DATE", poItem->GetString().c_str());
3559 : }
3560 : }
3561 :
3562 : #if defined(HAVE_POPPLER) || defined(HAVE_PDFIUM)
3563 :
3564 : /************************************************************************/
3565 : /* AddLayer() */
3566 : /************************************************************************/
3567 :
3568 280 : void PDFDataset::AddLayer(const std::string &osName, int iPage)
3569 : {
3570 560 : LayerStruct layerStruct;
3571 280 : layerStruct.osName = osName;
3572 280 : layerStruct.nInsertIdx = static_cast<int>(m_oLayerNameSet.size());
3573 280 : layerStruct.iPage = iPage;
3574 280 : m_oLayerNameSet.emplace_back(std::move(layerStruct));
3575 280 : }
3576 :
3577 : /************************************************************************/
3578 : /* CreateLayerList() */
3579 : /************************************************************************/
3580 :
3581 250 : void PDFDataset::CreateLayerList()
3582 : {
3583 : // Sort layers by prioritizing page number and then insertion index
3584 250 : std::sort(m_oLayerNameSet.begin(), m_oLayerNameSet.end(),
3585 426 : [](const LayerStruct &a, const LayerStruct &b)
3586 : {
3587 426 : if (a.iPage < b.iPage)
3588 78 : return true;
3589 348 : if (a.iPage > b.iPage)
3590 0 : return false;
3591 348 : return a.nInsertIdx < b.nInsertIdx;
3592 : });
3593 :
3594 250 : if (m_oLayerNameSet.size() >= 100)
3595 : {
3596 0 : for (const auto &oLayerStruct : m_oLayerNameSet)
3597 : {
3598 : m_aosLayerNames.AddNameValue(
3599 : CPLSPrintf("LAYER_%03d_NAME", m_aosLayerNames.size()),
3600 0 : oLayerStruct.osName.c_str());
3601 : }
3602 : }
3603 : else
3604 : {
3605 530 : for (const auto &oLayerStruct : m_oLayerNameSet)
3606 : {
3607 : m_aosLayerNames.AddNameValue(
3608 : CPLSPrintf("LAYER_%02d_NAME", m_aosLayerNames.size()),
3609 280 : oLayerStruct.osName.c_str());
3610 : }
3611 : }
3612 250 : }
3613 :
3614 : /************************************************************************/
3615 : /* BuildPostfixedLayerNameAndAddLayer() */
3616 : /************************************************************************/
3617 :
3618 : /** Append a suffix with the page number(s) to the provided layer name, if
3619 : * it makes sense (that is if it is a multiple page PDF and we haven't selected
3620 : * a specific name). And also call AddLayer() on it if successful.
3621 : * If may return an empty string if the layer isn't used by the page of interest
3622 : */
3623 424 : std::string PDFDataset::BuildPostfixedLayerNameAndAddLayer(
3624 : const std::string &osName, const std::pair<int, int> &oOCGRef,
3625 : int iPageOfInterest, int nPageCount)
3626 : {
3627 848 : std::string osPostfixedName = osName;
3628 424 : int iLayerPage = 0;
3629 424 : if (nPageCount > 1 && !m_oMapOCGNumGenToPages.empty())
3630 : {
3631 216 : const auto oIterToPages = m_oMapOCGNumGenToPages.find(oOCGRef);
3632 216 : if (oIterToPages != m_oMapOCGNumGenToPages.end())
3633 : {
3634 216 : const auto &anPages = oIterToPages->second;
3635 216 : if (iPageOfInterest > 0)
3636 : {
3637 192 : if (std::find(anPages.begin(), anPages.end(),
3638 192 : iPageOfInterest) == anPages.end())
3639 : {
3640 144 : return std::string();
3641 : }
3642 : }
3643 24 : else if (anPages.size() == 1)
3644 : {
3645 24 : iLayerPage = anPages.front();
3646 24 : osPostfixedName += CPLSPrintf(" (page %d)", anPages.front());
3647 : }
3648 : else
3649 : {
3650 0 : osPostfixedName += " (pages ";
3651 0 : for (size_t j = 0; j < anPages.size(); ++j)
3652 : {
3653 0 : if (j > 0)
3654 0 : osPostfixedName += ", ";
3655 0 : osPostfixedName += CPLSPrintf("%d", anPages[j]);
3656 : }
3657 0 : osPostfixedName += ')';
3658 : }
3659 : }
3660 : }
3661 :
3662 280 : AddLayer(osPostfixedName, iLayerPage);
3663 :
3664 280 : return osPostfixedName;
3665 : }
3666 :
3667 : #endif // defined(HAVE_POPPLER) || defined(HAVE_PDFIUM)
3668 :
3669 : #ifdef HAVE_POPPLER
3670 :
3671 : /************************************************************************/
3672 : /* ExploreLayersPoppler() */
3673 : /************************************************************************/
3674 :
3675 135 : void PDFDataset::ExploreLayersPoppler(GDALPDFArray *poArray,
3676 : int iPageOfInterest, int nPageCount,
3677 : CPLString osTopLayer, int nRecLevel,
3678 : int &nVisited, bool &bStop)
3679 : {
3680 135 : if (nRecLevel == 16 || nVisited == 1000)
3681 : {
3682 0 : CPLError(
3683 : CE_Failure, CPLE_AppDefined,
3684 : "ExploreLayersPoppler(): too deep exploration or too many items");
3685 0 : bStop = true;
3686 0 : return;
3687 : }
3688 135 : if (bStop)
3689 0 : return;
3690 :
3691 135 : int nLength = poArray->GetLength();
3692 135 : CPLString osCurLayer;
3693 414 : for (int i = 0; i < nLength; i++)
3694 : {
3695 279 : nVisited++;
3696 279 : GDALPDFObject *poObj = poArray->Get(i);
3697 279 : if (poObj == nullptr)
3698 0 : continue;
3699 279 : if (i == 0 && poObj->GetType() == PDFObjectType_String)
3700 : {
3701 : std::string osName =
3702 0 : PDFSanitizeLayerName(poObj->GetString().c_str());
3703 0 : if (!osTopLayer.empty())
3704 : {
3705 0 : osTopLayer += '.';
3706 0 : osTopLayer += osName;
3707 : }
3708 : else
3709 0 : osTopLayer = std::move(osName);
3710 0 : AddLayer(osTopLayer, 0);
3711 0 : m_oLayerOCGListPoppler.push_back(std::pair(osTopLayer, nullptr));
3712 : }
3713 279 : else if (poObj->GetType() == PDFObjectType_Array)
3714 : {
3715 97 : ExploreLayersPoppler(poObj->GetArray(), iPageOfInterest, nPageCount,
3716 : osCurLayer, nRecLevel + 1, nVisited, bStop);
3717 97 : if (bStop)
3718 0 : return;
3719 97 : osCurLayer = "";
3720 : }
3721 182 : else if (poObj->GetType() == PDFObjectType_Dictionary)
3722 : {
3723 182 : GDALPDFDictionary *poDict = poObj->GetDictionary();
3724 182 : GDALPDFObject *poName = poDict->Get("Name");
3725 182 : if (poName != nullptr && poName->GetType() == PDFObjectType_String)
3726 : {
3727 : std::string osName =
3728 182 : PDFSanitizeLayerName(poName->GetString().c_str());
3729 : /* coverity[copy_paste_error] */
3730 182 : if (!osTopLayer.empty())
3731 : {
3732 103 : osCurLayer = osTopLayer;
3733 103 : osCurLayer += '.';
3734 103 : osCurLayer += osName;
3735 : }
3736 : else
3737 79 : osCurLayer = std::move(osName);
3738 : // CPLDebug("PDF", "Layer %s", osCurLayer.c_str());
3739 :
3740 : #if POPPLER_MAJOR_VERSION > 25 || \
3741 : (POPPLER_MAJOR_VERSION == 25 && POPPLER_MINOR_VERSION >= 2)
3742 : const
3743 : #endif
3744 : OCGs *optContentConfig =
3745 182 : m_poDocPoppler->getOptContentConfig();
3746 : struct Ref r;
3747 182 : r.num = poObj->GetRefNum().toInt();
3748 182 : r.gen = poObj->GetRefGen();
3749 182 : OptionalContentGroup *ocg = optContentConfig->findOcgByRef(r);
3750 182 : if (ocg)
3751 : {
3752 182 : const auto oRefPair = std::pair(poObj->GetRefNum().toInt(),
3753 364 : poObj->GetRefGen());
3754 : const std::string osPostfixedName =
3755 : BuildPostfixedLayerNameAndAddLayer(
3756 182 : osCurLayer, oRefPair, iPageOfInterest, nPageCount);
3757 182 : if (osPostfixedName.empty())
3758 72 : continue;
3759 :
3760 110 : m_oLayerOCGListPoppler.push_back(
3761 220 : std::make_pair(osPostfixedName, ocg));
3762 110 : m_aoLayerWithRef.emplace_back(osPostfixedName.c_str(),
3763 220 : poObj->GetRefNum(), r.gen);
3764 : }
3765 : }
3766 : }
3767 : }
3768 : }
3769 :
3770 : /************************************************************************/
3771 : /* FindLayersPoppler() */
3772 : /************************************************************************/
3773 :
3774 167 : void PDFDataset::FindLayersPoppler(int iPageOfInterest)
3775 : {
3776 167 : int nPageCount = 0;
3777 167 : const auto poPages = GetPagesKids();
3778 167 : if (poPages)
3779 167 : nPageCount = poPages->GetLength();
3780 :
3781 : #if POPPLER_MAJOR_VERSION > 25 || \
3782 : (POPPLER_MAJOR_VERSION == 25 && POPPLER_MINOR_VERSION >= 2)
3783 : const
3784 : #endif
3785 167 : OCGs *optContentConfig = m_poDocPoppler->getOptContentConfig();
3786 167 : if (optContentConfig == nullptr || !optContentConfig->isOk())
3787 129 : return;
3788 :
3789 : #if POPPLER_MAJOR_VERSION > 25 || \
3790 : (POPPLER_MAJOR_VERSION == 25 && POPPLER_MINOR_VERSION >= 2)
3791 : const
3792 : #endif
3793 38 : Array *array = optContentConfig->getOrderArray();
3794 38 : if (array)
3795 : {
3796 38 : GDALPDFArray *poArray = GDALPDFCreateArray(array);
3797 38 : int nVisited = 0;
3798 38 : bool bStop = false;
3799 38 : ExploreLayersPoppler(poArray, iPageOfInterest, nPageCount, CPLString(),
3800 : 0, nVisited, bStop);
3801 38 : delete poArray;
3802 : }
3803 : else
3804 : {
3805 0 : for (const auto &refOCGPair : optContentConfig->getOCGs())
3806 : {
3807 0 : auto ocg = refOCGPair.second.get();
3808 0 : if (ocg != nullptr && ocg->getName() != nullptr)
3809 : {
3810 : const char *pszLayerName =
3811 0 : reinterpret_cast<const char *>(ocg->getName()->c_str());
3812 0 : AddLayer(pszLayerName, 0);
3813 0 : m_oLayerOCGListPoppler.push_back(
3814 0 : std::make_pair(CPLString(pszLayerName), ocg));
3815 : }
3816 : }
3817 : }
3818 :
3819 38 : CreateLayerList();
3820 38 : m_oMDMD_PDF.SetMetadata(m_aosLayerNames.List(), "LAYERS");
3821 : }
3822 :
3823 : /************************************************************************/
3824 : /* TurnLayersOnOffPoppler() */
3825 : /************************************************************************/
3826 :
3827 167 : void PDFDataset::TurnLayersOnOffPoppler()
3828 : {
3829 : #if POPPLER_MAJOR_VERSION > 25 || \
3830 : (POPPLER_MAJOR_VERSION == 25 && POPPLER_MINOR_VERSION >= 2)
3831 : const
3832 : #endif
3833 167 : OCGs *optContentConfig = m_poDocPoppler->getOptContentConfig();
3834 167 : if (optContentConfig == nullptr || !optContentConfig->isOk())
3835 129 : return;
3836 :
3837 : // Which layers to turn ON ?
3838 38 : const char *pszLayers = GetOption(papszOpenOptions, "LAYERS", nullptr);
3839 38 : if (pszLayers)
3840 : {
3841 : int i;
3842 2 : int bAll = EQUAL(pszLayers, "ALL");
3843 12 : for (const auto &refOCGPair : optContentConfig->getOCGs())
3844 : {
3845 10 : auto ocg = refOCGPair.second.get();
3846 10 : ocg->setState((bAll) ? OptionalContentGroup::On
3847 : : OptionalContentGroup::Off);
3848 : }
3849 :
3850 2 : char **papszLayers = CSLTokenizeString2(pszLayers, ",", 0);
3851 4 : for (i = 0; !bAll && papszLayers[i] != nullptr; i++)
3852 : {
3853 2 : bool isFound = false;
3854 12 : for (auto oIter2 = m_oLayerOCGListPoppler.begin();
3855 22 : oIter2 != m_oLayerOCGListPoppler.end(); ++oIter2)
3856 : {
3857 10 : if (oIter2->first != papszLayers[i])
3858 8 : continue;
3859 :
3860 2 : isFound = true;
3861 2 : auto oIter = oIter2;
3862 2 : if (oIter->second)
3863 : {
3864 : // CPLDebug("PDF", "Turn '%s' on", papszLayers[i]);
3865 2 : oIter->second->setState(OptionalContentGroup::On);
3866 : }
3867 :
3868 : // Turn child layers on, unless there's one of them explicitly
3869 : // listed in the list.
3870 2 : size_t nLen = strlen(papszLayers[i]);
3871 2 : int bFoundChildLayer = FALSE;
3872 2 : oIter = m_oLayerOCGListPoppler.begin();
3873 10 : for (;
3874 12 : oIter != m_oLayerOCGListPoppler.end() && !bFoundChildLayer;
3875 10 : ++oIter)
3876 : {
3877 10 : if (oIter->first.size() > nLen &&
3878 5 : strncmp(oIter->first.c_str(), papszLayers[i], nLen) ==
3879 15 : 0 &&
3880 2 : oIter->first[nLen] == '.')
3881 : {
3882 4 : for (int j = 0; papszLayers[j] != nullptr; j++)
3883 : {
3884 2 : if (strcmp(papszLayers[j], oIter->first.c_str()) ==
3885 : 0)
3886 : {
3887 0 : bFoundChildLayer = TRUE;
3888 0 : break;
3889 : }
3890 : }
3891 : }
3892 : }
3893 :
3894 2 : if (!bFoundChildLayer)
3895 : {
3896 2 : oIter = m_oLayerOCGListPoppler.begin();
3897 12 : for (; oIter != m_oLayerOCGListPoppler.end() &&
3898 : !bFoundChildLayer;
3899 10 : ++oIter)
3900 : {
3901 10 : if (oIter->first.size() > nLen &&
3902 5 : strncmp(oIter->first.c_str(), papszLayers[i],
3903 15 : nLen) == 0 &&
3904 2 : oIter->first[nLen] == '.')
3905 : {
3906 2 : if (oIter->second)
3907 : {
3908 : // CPLDebug("PDF", "Turn '%s' on too",
3909 : // oIter->first.c_str());
3910 2 : oIter->second->setState(
3911 : OptionalContentGroup::On);
3912 : }
3913 : }
3914 : }
3915 : }
3916 :
3917 : // Turn parent layers on too
3918 6 : std::string layer(papszLayers[i]);
3919 : std::string::size_type j;
3920 3 : while ((j = layer.find_last_of('.')) != std::string::npos)
3921 : {
3922 1 : layer.resize(j);
3923 1 : oIter = m_oLayerOCGListPoppler.begin();
3924 6 : for (; oIter != m_oLayerOCGListPoppler.end(); ++oIter)
3925 : {
3926 5 : if (oIter->first == layer && oIter->second)
3927 : {
3928 : // CPLDebug("PDF", "Turn '%s' on too",
3929 : // layer.c_str());
3930 1 : oIter->second->setState(OptionalContentGroup::On);
3931 : }
3932 : }
3933 : }
3934 : }
3935 2 : if (!isFound)
3936 : {
3937 0 : CPLError(CE_Warning, CPLE_AppDefined, "Unknown layer '%s'",
3938 0 : papszLayers[i]);
3939 : }
3940 : }
3941 2 : CSLDestroy(papszLayers);
3942 :
3943 2 : m_bUseOCG = true;
3944 : }
3945 :
3946 : // Which layers to turn OFF ?
3947 : const char *pszLayersOFF =
3948 38 : GetOption(papszOpenOptions, "LAYERS_OFF", nullptr);
3949 38 : if (pszLayersOFF)
3950 : {
3951 5 : char **papszLayersOFF = CSLTokenizeString2(pszLayersOFF, ",", 0);
3952 10 : for (int i = 0; papszLayersOFF[i] != nullptr; i++)
3953 : {
3954 5 : bool isFound = false;
3955 22 : for (auto oIter2 = m_oLayerOCGListPoppler.begin();
3956 39 : oIter2 != m_oLayerOCGListPoppler.end(); ++oIter2)
3957 : {
3958 17 : if (oIter2->first != papszLayersOFF[i])
3959 12 : continue;
3960 :
3961 5 : isFound = true;
3962 5 : auto oIter = oIter2;
3963 5 : if (oIter->second)
3964 : {
3965 : // CPLDebug("PDF", "Turn '%s' off", papszLayersOFF[i]);
3966 5 : oIter->second->setState(OptionalContentGroup::Off);
3967 : }
3968 :
3969 : // Turn child layers off too
3970 5 : size_t nLen = strlen(papszLayersOFF[i]);
3971 5 : oIter = m_oLayerOCGListPoppler.begin();
3972 22 : for (; oIter != m_oLayerOCGListPoppler.end(); ++oIter)
3973 : {
3974 17 : if (oIter->first.size() > nLen &&
3975 3 : strncmp(oIter->first.c_str(), papszLayersOFF[i],
3976 20 : nLen) == 0 &&
3977 1 : oIter->first[nLen] == '.')
3978 : {
3979 1 : if (oIter->second)
3980 : {
3981 : // CPLDebug("PDF", "Turn '%s' off too",
3982 : // oIter->first.c_str());
3983 1 : oIter->second->setState(OptionalContentGroup::Off);
3984 : }
3985 : }
3986 : }
3987 : }
3988 5 : if (!isFound)
3989 : {
3990 0 : CPLError(CE_Warning, CPLE_AppDefined, "Unknown layer '%s'",
3991 0 : papszLayersOFF[i]);
3992 : }
3993 : }
3994 5 : CSLDestroy(papszLayersOFF);
3995 :
3996 5 : m_bUseOCG = true;
3997 : }
3998 : }
3999 :
4000 : #endif
4001 :
4002 : #ifdef HAVE_PDFIUM
4003 :
4004 : /************************************************************************/
4005 : /* ExploreLayersPdfium() */
4006 : /************************************************************************/
4007 :
4008 170 : void PDFDataset::ExploreLayersPdfium(GDALPDFArray *poArray, int iPageOfInterest,
4009 : int nPageCount, int nRecLevel,
4010 : CPLString osTopLayer)
4011 : {
4012 170 : if (nRecLevel == 16)
4013 0 : return;
4014 :
4015 170 : const int nLength = poArray->GetLength();
4016 340 : std::string osCurLayer;
4017 520 : for (int i = 0; i < nLength; i++)
4018 : {
4019 350 : GDALPDFObject *poObj = poArray->Get(i);
4020 350 : if (poObj == nullptr)
4021 0 : continue;
4022 350 : if (i == 0 && poObj->GetType() == PDFObjectType_String)
4023 : {
4024 : const std::string osName =
4025 0 : PDFSanitizeLayerName(poObj->GetString().c_str());
4026 0 : if (!osTopLayer.empty())
4027 0 : osTopLayer = std::string(osTopLayer).append(".").append(osName);
4028 : else
4029 0 : osTopLayer = osName;
4030 0 : AddLayer(osTopLayer, 0);
4031 0 : m_oMapLayerNameToOCGNumGenPdfium[osTopLayer] = std::pair(-1, -1);
4032 : }
4033 350 : else if (poObj->GetType() == PDFObjectType_Array)
4034 : {
4035 108 : ExploreLayersPdfium(poObj->GetArray(), iPageOfInterest, nPageCount,
4036 : nRecLevel + 1, osCurLayer);
4037 108 : osCurLayer.clear();
4038 : }
4039 242 : else if (poObj->GetType() == PDFObjectType_Dictionary)
4040 : {
4041 242 : GDALPDFDictionary *poDict = poObj->GetDictionary();
4042 242 : GDALPDFObject *poName = poDict->Get("Name");
4043 242 : if (poName != nullptr && poName->GetType() == PDFObjectType_String)
4044 : {
4045 : std::string osName =
4046 242 : PDFSanitizeLayerName(poName->GetString().c_str());
4047 : // coverity[copy_paste_error]
4048 242 : if (!osTopLayer.empty())
4049 : {
4050 : osCurLayer =
4051 118 : std::string(osTopLayer).append(".").append(osName);
4052 : }
4053 : else
4054 124 : osCurLayer = std::move(osName);
4055 : // CPLDebug("PDF", "Layer %s", osCurLayer.c_str());
4056 :
4057 : const auto oRefPair =
4058 242 : std::pair(poObj->GetRefNum().toInt(), poObj->GetRefGen());
4059 : const std::string osPostfixedName =
4060 : BuildPostfixedLayerNameAndAddLayer(
4061 242 : osCurLayer, oRefPair, iPageOfInterest, nPageCount);
4062 242 : if (osPostfixedName.empty())
4063 72 : continue;
4064 :
4065 : m_aoLayerWithRef.emplace_back(
4066 170 : osPostfixedName, poObj->GetRefNum(), poObj->GetRefGen());
4067 170 : m_oMapLayerNameToOCGNumGenPdfium[osPostfixedName] = oRefPair;
4068 : }
4069 : }
4070 : }
4071 : }
4072 :
4073 : /************************************************************************/
4074 : /* FindLayersPdfium() */
4075 : /************************************************************************/
4076 :
4077 212 : void PDFDataset::FindLayersPdfium(int iPageOfInterest)
4078 : {
4079 212 : int nPageCount = 0;
4080 212 : const auto poPages = GetPagesKids();
4081 212 : if (poPages)
4082 212 : nPageCount = poPages->GetLength();
4083 :
4084 212 : GDALPDFObject *poCatalog = GetCatalog();
4085 424 : if (poCatalog == nullptr ||
4086 212 : poCatalog->GetType() != PDFObjectType_Dictionary)
4087 0 : return;
4088 212 : GDALPDFObject *poOrder = poCatalog->LookupObject("OCProperties.D.Order");
4089 212 : if (poOrder != nullptr && poOrder->GetType() == PDFObjectType_Array)
4090 : {
4091 62 : ExploreLayersPdfium(poOrder->GetArray(), iPageOfInterest, nPageCount,
4092 : 0);
4093 : }
4094 : #if 0
4095 : else
4096 : {
4097 : GDALPDFObject* poOCGs = poD->GetDictionary()->Get("OCGs");
4098 : if( poOCGs != nullptr && poOCGs->GetType() == PDFObjectType_Array )
4099 : {
4100 : GDALPDFArray* poArray = poOCGs->GetArray();
4101 : int nLength = poArray->GetLength();
4102 : for(int i=0;i<nLength;i++)
4103 : {
4104 : GDALPDFObject* poObj = poArray->Get(i);
4105 : if( poObj != nullptr )
4106 : {
4107 : // TODO ?
4108 : }
4109 : }
4110 : }
4111 : }
4112 : #endif
4113 :
4114 212 : CreateLayerList();
4115 212 : m_oMDMD_PDF.SetMetadata(m_aosLayerNames.List(), "LAYERS");
4116 : }
4117 :
4118 : /************************************************************************/
4119 : /* TurnLayersOnOffPdfium() */
4120 : /************************************************************************/
4121 :
4122 212 : void PDFDataset::TurnLayersOnOffPdfium()
4123 : {
4124 212 : GDALPDFObject *poCatalog = GetCatalog();
4125 424 : if (poCatalog == nullptr ||
4126 212 : poCatalog->GetType() != PDFObjectType_Dictionary)
4127 0 : return;
4128 212 : GDALPDFObject *poOCGs = poCatalog->LookupObject("OCProperties.OCGs");
4129 212 : if (poOCGs == nullptr || poOCGs->GetType() != PDFObjectType_Array)
4130 150 : return;
4131 :
4132 : // Which layers to turn ON ?
4133 62 : const char *pszLayers = GetOption(papszOpenOptions, "LAYERS", nullptr);
4134 62 : if (pszLayers)
4135 : {
4136 : int i;
4137 2 : int bAll = EQUAL(pszLayers, "ALL");
4138 :
4139 2 : GDALPDFArray *poOCGsArray = poOCGs->GetArray();
4140 2 : int nLength = poOCGsArray->GetLength();
4141 12 : for (i = 0; i < nLength; i++)
4142 : {
4143 10 : GDALPDFObject *poOCG = poOCGsArray->Get(i);
4144 0 : m_oMapOCGNumGenToVisibilityStatePdfium[std::pair(
4145 10 : poOCG->GetRefNum().toInt(), poOCG->GetRefGen())] =
4146 10 : (bAll) ? VISIBILITY_ON : VISIBILITY_OFF;
4147 : }
4148 :
4149 2 : char **papszLayers = CSLTokenizeString2(pszLayers, ",", 0);
4150 4 : for (i = 0; !bAll && papszLayers[i] != nullptr; i++)
4151 : {
4152 2 : auto oIter = m_oMapLayerNameToOCGNumGenPdfium.find(papszLayers[i]);
4153 2 : if (oIter != m_oMapLayerNameToOCGNumGenPdfium.end())
4154 : {
4155 2 : if (oIter->second.first >= 0)
4156 : {
4157 : // CPLDebug("PDF", "Turn '%s' on", papszLayers[i]);
4158 2 : m_oMapOCGNumGenToVisibilityStatePdfium[oIter->second] =
4159 : VISIBILITY_ON;
4160 : }
4161 :
4162 : // Turn child layers on, unless there's one of them explicitly
4163 : // listed in the list.
4164 2 : size_t nLen = strlen(papszLayers[i]);
4165 2 : int bFoundChildLayer = FALSE;
4166 2 : oIter = m_oMapLayerNameToOCGNumGenPdfium.begin();
4167 12 : for (; oIter != m_oMapLayerNameToOCGNumGenPdfium.end() &&
4168 : !bFoundChildLayer;
4169 10 : oIter++)
4170 : {
4171 10 : if (oIter->first.size() > nLen &&
4172 5 : strncmp(oIter->first.c_str(), papszLayers[i], nLen) ==
4173 15 : 0 &&
4174 2 : oIter->first[nLen] == '.')
4175 : {
4176 4 : for (int j = 0; papszLayers[j] != nullptr; j++)
4177 : {
4178 2 : if (strcmp(papszLayers[j], oIter->first.c_str()) ==
4179 : 0)
4180 0 : bFoundChildLayer = TRUE;
4181 : }
4182 : }
4183 : }
4184 :
4185 2 : if (!bFoundChildLayer)
4186 : {
4187 2 : oIter = m_oMapLayerNameToOCGNumGenPdfium.begin();
4188 12 : for (; oIter != m_oMapLayerNameToOCGNumGenPdfium.end() &&
4189 : !bFoundChildLayer;
4190 10 : oIter++)
4191 : {
4192 10 : if (oIter->first.size() > nLen &&
4193 5 : strncmp(oIter->first.c_str(), papszLayers[i],
4194 15 : nLen) == 0 &&
4195 2 : oIter->first[nLen] == '.')
4196 : {
4197 2 : if (oIter->second.first >= 0)
4198 : {
4199 : // CPLDebug("PDF", "Turn '%s' on too",
4200 : // oIter->first.c_str());
4201 : m_oMapOCGNumGenToVisibilityStatePdfium
4202 2 : [oIter->second] = VISIBILITY_ON;
4203 : }
4204 : }
4205 : }
4206 : }
4207 :
4208 : // Turn parent layers on too
4209 2 : char *pszLastDot = nullptr;
4210 3 : while ((pszLastDot = strrchr(papszLayers[i], '.')) != nullptr)
4211 : {
4212 1 : *pszLastDot = '\0';
4213 : oIter =
4214 1 : m_oMapLayerNameToOCGNumGenPdfium.find(papszLayers[i]);
4215 1 : if (oIter != m_oMapLayerNameToOCGNumGenPdfium.end())
4216 : {
4217 1 : if (oIter->second.first >= 0)
4218 : {
4219 : // CPLDebug("PDF", "Turn '%s' on too",
4220 : // papszLayers[i]);
4221 : m_oMapOCGNumGenToVisibilityStatePdfium
4222 1 : [oIter->second] = VISIBILITY_ON;
4223 : }
4224 : }
4225 : }
4226 : }
4227 : else
4228 : {
4229 0 : CPLError(CE_Warning, CPLE_AppDefined, "Unknown layer '%s'",
4230 0 : papszLayers[i]);
4231 : }
4232 : }
4233 2 : CSLDestroy(papszLayers);
4234 :
4235 2 : m_bUseOCG = true;
4236 : }
4237 :
4238 : // Which layers to turn OFF ?
4239 : const char *pszLayersOFF =
4240 62 : GetOption(papszOpenOptions, "LAYERS_OFF", nullptr);
4241 62 : if (pszLayersOFF)
4242 : {
4243 5 : char **papszLayersOFF = CSLTokenizeString2(pszLayersOFF, ",", 0);
4244 10 : for (int i = 0; papszLayersOFF[i] != nullptr; i++)
4245 : {
4246 : auto oIter =
4247 5 : m_oMapLayerNameToOCGNumGenPdfium.find(papszLayersOFF[i]);
4248 5 : if (oIter != m_oMapLayerNameToOCGNumGenPdfium.end())
4249 : {
4250 5 : if (oIter->second.first >= 0)
4251 : {
4252 : // CPLDebug("PDF", "Turn '%s' (%d,%d) off",
4253 : // papszLayersOFF[i], oIter->second.first,
4254 : // oIter->second.second);
4255 5 : m_oMapOCGNumGenToVisibilityStatePdfium[oIter->second] =
4256 : VISIBILITY_OFF;
4257 : }
4258 :
4259 : // Turn child layers off too
4260 5 : size_t nLen = strlen(papszLayersOFF[i]);
4261 5 : oIter = m_oMapLayerNameToOCGNumGenPdfium.begin();
4262 22 : for (; oIter != m_oMapLayerNameToOCGNumGenPdfium.end(); oIter++)
4263 : {
4264 17 : if (oIter->first.size() > nLen &&
4265 3 : strncmp(oIter->first.c_str(), papszLayersOFF[i],
4266 20 : nLen) == 0 &&
4267 1 : oIter->first[nLen] == '.')
4268 : {
4269 1 : if (oIter->second.first >= 0)
4270 : {
4271 : // CPLDebug("PDF", "Turn '%s' off too",
4272 : // oIter->first.c_str());
4273 : m_oMapOCGNumGenToVisibilityStatePdfium
4274 1 : [oIter->second] = VISIBILITY_OFF;
4275 : }
4276 : }
4277 : }
4278 : }
4279 : else
4280 : {
4281 0 : CPLError(CE_Warning, CPLE_AppDefined, "Unknown layer '%s'",
4282 0 : papszLayersOFF[i]);
4283 : }
4284 : }
4285 5 : CSLDestroy(papszLayersOFF);
4286 :
4287 5 : m_bUseOCG = true;
4288 : }
4289 : }
4290 :
4291 : /************************************************************************/
4292 : /* GetVisibilityStateForOGCPdfium() */
4293 : /************************************************************************/
4294 :
4295 12996 : PDFDataset::VisibilityState PDFDataset::GetVisibilityStateForOGCPdfium(int nNum,
4296 : int nGen)
4297 : {
4298 : auto oIter =
4299 12996 : m_oMapOCGNumGenToVisibilityStatePdfium.find(std::pair(nNum, nGen));
4300 12996 : if (oIter == m_oMapOCGNumGenToVisibilityStatePdfium.end())
4301 8703 : return VISIBILITY_DEFAULT;
4302 4293 : return oIter->second;
4303 : }
4304 :
4305 : #endif /* HAVE_PDFIUM */
4306 :
4307 : /************************************************************************/
4308 : /* GetPagesKids() */
4309 : /************************************************************************/
4310 :
4311 758 : GDALPDFArray *PDFDataset::GetPagesKids()
4312 : {
4313 758 : const auto poCatalog = GetCatalog();
4314 758 : if (!poCatalog || poCatalog->GetType() != PDFObjectType_Dictionary)
4315 : {
4316 0 : return nullptr;
4317 : }
4318 758 : const auto poKids = poCatalog->LookupObject("Pages.Kids");
4319 758 : if (!poKids || poKids->GetType() != PDFObjectType_Array)
4320 : {
4321 0 : return nullptr;
4322 : }
4323 758 : return poKids->GetArray();
4324 : }
4325 :
4326 : /************************************************************************/
4327 : /* MapOCGsToPages() */
4328 : /************************************************************************/
4329 :
4330 379 : void PDFDataset::MapOCGsToPages()
4331 : {
4332 379 : const auto poKidsArray = GetPagesKids();
4333 379 : if (!poKidsArray)
4334 : {
4335 0 : return;
4336 : }
4337 379 : const int nKidsArrayLength = poKidsArray->GetLength();
4338 822 : for (int iPage = 0; iPage < nKidsArrayLength; ++iPage)
4339 : {
4340 443 : const auto poPage = poKidsArray->Get(iPage);
4341 443 : if (poPage && poPage->GetType() == PDFObjectType_Dictionary)
4342 : {
4343 443 : const auto poXObject = poPage->LookupObject("Resources.XObject");
4344 443 : if (poXObject && poXObject->GetType() == PDFObjectType_Dictionary)
4345 : {
4346 958 : for (const auto &oNameObjectPair :
4347 2339 : poXObject->GetDictionary()->GetValues())
4348 : {
4349 : const auto poProperties =
4350 958 : oNameObjectPair.second->LookupObject(
4351 : "Resources.Properties");
4352 1030 : if (poProperties &&
4353 72 : poProperties->GetType() == PDFObjectType_Dictionary)
4354 : {
4355 : const auto &oMap =
4356 72 : poProperties->GetDictionary()->GetValues();
4357 288 : for (const auto &[osKey, poObj] : oMap)
4358 : {
4359 432 : if (poObj->GetRefNum().toBool() &&
4360 216 : poObj->GetType() == PDFObjectType_Dictionary)
4361 : {
4362 : GDALPDFObject *poType =
4363 216 : poObj->GetDictionary()->Get("Type");
4364 : GDALPDFObject *poName =
4365 216 : poObj->GetDictionary()->Get("Name");
4366 432 : if (poType &&
4367 432 : poType->GetType() == PDFObjectType_Name &&
4368 864 : poType->GetName() == "OCG" && poName &&
4369 216 : poName->GetType() == PDFObjectType_String)
4370 : {
4371 : m_oMapOCGNumGenToPages
4372 216 : [std::pair(poObj->GetRefNum().toInt(),
4373 432 : poObj->GetRefGen())]
4374 216 : .push_back(iPage + 1);
4375 : }
4376 : }
4377 : }
4378 : }
4379 : }
4380 : }
4381 : }
4382 : }
4383 : }
4384 :
4385 : /************************************************************************/
4386 : /* FindLayerOCG() */
4387 : /************************************************************************/
4388 :
4389 353 : CPLString PDFDataset::FindLayerOCG(GDALPDFDictionary *poPageDict,
4390 : const char *pszLayerName)
4391 : {
4392 : GDALPDFObject *poProperties =
4393 353 : poPageDict->LookupObject("Resources.Properties");
4394 419 : if (poProperties != nullptr &&
4395 66 : poProperties->GetType() == PDFObjectType_Dictionary)
4396 : {
4397 66 : const auto &oMap = poProperties->GetDictionary()->GetValues();
4398 187 : for (const auto &[osKey, poObj] : oMap)
4399 : {
4400 241 : if (poObj->GetRefNum().toBool() &&
4401 120 : poObj->GetType() == PDFObjectType_Dictionary)
4402 : {
4403 120 : GDALPDFObject *poType = poObj->GetDictionary()->Get("Type");
4404 120 : GDALPDFObject *poName = poObj->GetDictionary()->Get("Name");
4405 240 : if (poType != nullptr &&
4406 240 : poType->GetType() == PDFObjectType_Name &&
4407 480 : poType->GetName() == "OCG" && poName != nullptr &&
4408 120 : poName->GetType() == PDFObjectType_String)
4409 : {
4410 120 : if (poName->GetString() == pszLayerName)
4411 0 : return osKey;
4412 : }
4413 : }
4414 : }
4415 : }
4416 353 : return "";
4417 : }
4418 :
4419 : /************************************************************************/
4420 : /* FindLayersGeneric() */
4421 : /************************************************************************/
4422 :
4423 0 : void PDFDataset::FindLayersGeneric(GDALPDFDictionary *poPageDict)
4424 : {
4425 : GDALPDFObject *poProperties =
4426 0 : poPageDict->LookupObject("Resources.Properties");
4427 0 : if (poProperties != nullptr &&
4428 0 : poProperties->GetType() == PDFObjectType_Dictionary)
4429 : {
4430 0 : const auto &oMap = poProperties->GetDictionary()->GetValues();
4431 0 : for (const auto &[osKey, poObj] : oMap)
4432 : {
4433 0 : if (poObj->GetRefNum().toBool() &&
4434 0 : poObj->GetType() == PDFObjectType_Dictionary)
4435 : {
4436 0 : GDALPDFObject *poType = poObj->GetDictionary()->Get("Type");
4437 0 : GDALPDFObject *poName = poObj->GetDictionary()->Get("Name");
4438 0 : if (poType != nullptr &&
4439 0 : poType->GetType() == PDFObjectType_Name &&
4440 0 : poType->GetName() == "OCG" && poName != nullptr &&
4441 0 : poName->GetType() == PDFObjectType_String)
4442 : {
4443 : m_aoLayerWithRef.emplace_back(
4444 0 : PDFSanitizeLayerName(poName->GetString().c_str())
4445 0 : .c_str(),
4446 0 : poObj->GetRefNum(), poObj->GetRefGen());
4447 : }
4448 : }
4449 : }
4450 : }
4451 0 : }
4452 :
4453 : /************************************************************************/
4454 : /* Open() */
4455 : /************************************************************************/
4456 :
4457 401 : PDFDataset *PDFDataset::Open(GDALOpenInfo *poOpenInfo)
4458 :
4459 : {
4460 401 : if (!PDFDatasetIdentify(poOpenInfo))
4461 2 : return nullptr;
4462 :
4463 : const char *pszUserPwd =
4464 399 : GetOption(poOpenInfo->papszOpenOptions, "USER_PWD", nullptr);
4465 :
4466 399 : const bool bOpenSubdataset = STARTS_WITH(poOpenInfo->pszFilename, "PDF:");
4467 399 : const bool bOpenSubdatasetImage =
4468 399 : STARTS_WITH(poOpenInfo->pszFilename, "PDF_IMAGE:");
4469 399 : int iPage = -1;
4470 399 : int nImageNum = -1;
4471 798 : std::string osSubdatasetName;
4472 399 : const char *pszFilename = poOpenInfo->pszFilename;
4473 :
4474 399 : if (bOpenSubdataset)
4475 : {
4476 30 : iPage = atoi(pszFilename + 4);
4477 30 : if (iPage <= 0)
4478 2 : return nullptr;
4479 28 : pszFilename = strchr(pszFilename + 4, ':');
4480 28 : if (pszFilename == nullptr)
4481 0 : return nullptr;
4482 28 : pszFilename++;
4483 28 : osSubdatasetName = CPLSPrintf("Page %d", iPage);
4484 : }
4485 369 : else if (bOpenSubdatasetImage)
4486 : {
4487 0 : iPage = atoi(pszFilename + 10);
4488 0 : if (iPage <= 0)
4489 0 : return nullptr;
4490 0 : const char *pszNext = strchr(pszFilename + 10, ':');
4491 0 : if (pszNext == nullptr)
4492 0 : return nullptr;
4493 0 : nImageNum = atoi(pszNext + 1);
4494 0 : if (nImageNum <= 0)
4495 0 : return nullptr;
4496 0 : pszFilename = strchr(pszNext + 1, ':');
4497 0 : if (pszFilename == nullptr)
4498 0 : return nullptr;
4499 0 : pszFilename++;
4500 0 : osSubdatasetName = CPLSPrintf("Image %d", nImageNum);
4501 : }
4502 : else
4503 369 : iPage = 1;
4504 :
4505 397 : std::bitset<PDFLIB_COUNT> bHasLib;
4506 397 : bHasLib.reset();
4507 : // Each library set their flag
4508 : #if defined(HAVE_POPPLER)
4509 397 : bHasLib.set(PDFLIB_POPPLER);
4510 : #endif // HAVE_POPPLER
4511 : #if defined(HAVE_PODOFO)
4512 : bHasLib.set(PDFLIB_PODOFO);
4513 : #endif // HAVE_PODOFO
4514 : #if defined(HAVE_PDFIUM)
4515 397 : bHasLib.set(PDFLIB_PDFIUM);
4516 : #endif // HAVE_PDFIUM
4517 :
4518 397 : std::bitset<PDFLIB_COUNT> bUseLib;
4519 :
4520 : // More than one library available
4521 : // Detect which one
4522 397 : if (bHasLib.count() != 1)
4523 : {
4524 397 : const char *pszDefaultLib = bHasLib.test(PDFLIB_PDFIUM) ? "PDFIUM"
4525 0 : : bHasLib.test(PDFLIB_POPPLER) ? "POPPLER"
4526 397 : : "PODOFO";
4527 : const char *pszPDFLib =
4528 397 : GetOption(poOpenInfo->papszOpenOptions, "PDF_LIB", pszDefaultLib);
4529 : while (true)
4530 : {
4531 397 : if (EQUAL(pszPDFLib, "POPPLER"))
4532 171 : bUseLib.set(PDFLIB_POPPLER);
4533 226 : else if (EQUAL(pszPDFLib, "PODOFO"))
4534 0 : bUseLib.set(PDFLIB_PODOFO);
4535 226 : else if (EQUAL(pszPDFLib, "PDFIUM"))
4536 226 : bUseLib.set(PDFLIB_PDFIUM);
4537 :
4538 397 : if (bUseLib.count() != 1 || (bHasLib & bUseLib) == 0)
4539 : {
4540 0 : CPLDebug("PDF",
4541 : "Invalid value for GDAL_PDF_LIB config option: %s. "
4542 : "Fallback to %s",
4543 : pszPDFLib, pszDefaultLib);
4544 0 : pszPDFLib = pszDefaultLib;
4545 0 : bUseLib.reset();
4546 : }
4547 : else
4548 397 : break;
4549 : }
4550 : }
4551 : else
4552 0 : bUseLib = bHasLib;
4553 :
4554 397 : GDALPDFObject *poPageObj = nullptr;
4555 : #ifdef HAVE_POPPLER
4556 397 : PDFDoc *poDocPoppler = nullptr;
4557 397 : Page *poPagePoppler = nullptr;
4558 397 : Catalog *poCatalogPoppler = nullptr;
4559 : #endif
4560 : #ifdef HAVE_PODOFO
4561 : std::unique_ptr<PoDoFo::PdfMemDocument> poDocPodofo;
4562 : PoDoFo::PdfPage *poPagePodofo = nullptr;
4563 : #endif
4564 : #ifdef HAVE_PDFIUM
4565 397 : TPdfiumDocumentStruct *poDocPdfium = nullptr;
4566 397 : TPdfiumPageStruct *poPagePdfium = nullptr;
4567 : #endif
4568 397 : int nPages = 0;
4569 397 : VSIVirtualHandleUniquePtr fp;
4570 :
4571 : #ifdef HAVE_POPPLER
4572 397 : if (bUseLib.test(PDFLIB_POPPLER))
4573 : {
4574 : static bool globalParamsCreatedByGDAL = false;
4575 : {
4576 342 : CPLMutexHolderD(&hGlobalParamsMutex);
4577 : /* poppler global variable */
4578 171 : if (globalParams == nullptr)
4579 : {
4580 2 : globalParamsCreatedByGDAL = true;
4581 2 : globalParams.reset(new GlobalParams());
4582 : }
4583 :
4584 171 : globalParams->setPrintCommands(CPLTestBool(
4585 : CPLGetConfigOption("GDAL_PDF_PRINT_COMMANDS", "FALSE")));
4586 : }
4587 :
4588 340 : const auto registerErrorCallback = []()
4589 : {
4590 : /* Set custom error handler for poppler errors */
4591 340 : setErrorCallback(PDFDatasetErrorFunction);
4592 340 : assert(globalParams); // avoid CSA false positive
4593 340 : globalParams->setErrQuiet(false);
4594 340 : };
4595 :
4596 171 : fp.reset(VSIFOpenL(pszFilename, "rb"));
4597 171 : if (!fp)
4598 4 : return nullptr;
4599 :
4600 : #ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
4601 : {
4602 : // Workaround for ossfuzz only due to
4603 : // https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=37584
4604 : // https://gitlab.freedesktop.org/poppler/poppler/-/issues/1137
4605 : GByte *pabyRet = nullptr;
4606 : vsi_l_offset nSize = 0;
4607 : if (VSIIngestFile(fp.get(), pszFilename, &pabyRet, &nSize,
4608 : 10 * 1024 * 1024))
4609 : {
4610 : // Replace nul byte by something else so that strstr() works
4611 : for (size_t i = 0; i < nSize; i++)
4612 : {
4613 : if (pabyRet[i] == 0)
4614 : pabyRet[i] = ' ';
4615 : }
4616 : if (strstr(reinterpret_cast<const char *>(pabyRet),
4617 : "/JBIG2Decode"))
4618 : {
4619 : CPLError(CE_Failure, CPLE_AppDefined,
4620 : "/JBIG2Decode found. Giving up due to potential "
4621 : "very long processing time.");
4622 : CPLFree(pabyRet);
4623 : return nullptr;
4624 : }
4625 : }
4626 : CPLFree(pabyRet);
4627 : }
4628 : #endif
4629 :
4630 170 : fp.reset(VSICreateBufferedReaderHandle(fp.release()));
4631 : while (true)
4632 : {
4633 170 : fp->Seek(0, SEEK_SET);
4634 170 : g_nPopplerErrors = 0;
4635 170 : if (globalParamsCreatedByGDAL)
4636 170 : registerErrorCallback();
4637 170 : Object oObj;
4638 : auto poStream =
4639 170 : new VSIPDFFileStream(fp.get(), pszFilename, std::move(oObj));
4640 : #if POPPLER_MAJOR_VERSION > 22 || \
4641 : (POPPLER_MAJOR_VERSION == 22 && POPPLER_MINOR_VERSION > 2)
4642 : std::optional<GooString> osUserPwd;
4643 : if (pszUserPwd)
4644 : osUserPwd = std::optional<GooString>(pszUserPwd);
4645 : try
4646 : {
4647 : poDocPoppler =
4648 : new PDFDoc(poStream, std::optional<GooString>(), osUserPwd);
4649 : }
4650 : catch (const std::exception &e)
4651 : {
4652 : CPLError(CE_Failure, CPLE_AppDefined,
4653 : "PDFDoc::PDFDoc() failed with %s", e.what());
4654 : return nullptr;
4655 : }
4656 : #else
4657 170 : GooString *poUserPwd = nullptr;
4658 170 : if (pszUserPwd)
4659 2 : poUserPwd = new GooString(pszUserPwd);
4660 170 : poDocPoppler = new PDFDoc(poStream, nullptr, poUserPwd);
4661 170 : delete poUserPwd;
4662 : #endif
4663 170 : if (globalParamsCreatedByGDAL)
4664 170 : registerErrorCallback();
4665 170 : if (g_nPopplerErrors >= MAX_POPPLER_ERRORS)
4666 : {
4667 0 : PDFFreeDoc(poDocPoppler);
4668 0 : return nullptr;
4669 : }
4670 :
4671 170 : if (!poDocPoppler->isOk() || poDocPoppler->getNumPages() == 0)
4672 : {
4673 2 : if (poDocPoppler->getErrorCode() == errEncrypted)
4674 : {
4675 2 : if (pszUserPwd && EQUAL(pszUserPwd, "ASK_INTERACTIVE"))
4676 : {
4677 : pszUserPwd =
4678 0 : PDFEnterPasswordFromConsoleIfNeeded(pszUserPwd);
4679 0 : PDFFreeDoc(poDocPoppler);
4680 :
4681 : /* Reset errors that could have been issued during
4682 : * opening and that */
4683 : /* did not result in an invalid document */
4684 0 : CPLErrorReset();
4685 :
4686 0 : continue;
4687 : }
4688 2 : else if (pszUserPwd == nullptr)
4689 : {
4690 1 : CPLError(CE_Failure, CPLE_AppDefined,
4691 : "A password is needed. You can specify it "
4692 : "through the PDF_USER_PWD "
4693 : "configuration option / USER_PWD open option "
4694 : "(that can be set to ASK_INTERACTIVE)");
4695 : }
4696 : else
4697 : {
4698 1 : CPLError(CE_Failure, CPLE_AppDefined,
4699 : "Invalid password");
4700 : }
4701 : }
4702 : else
4703 : {
4704 0 : CPLError(CE_Failure, CPLE_AppDefined, "Invalid PDF");
4705 : }
4706 :
4707 2 : PDFFreeDoc(poDocPoppler);
4708 2 : return nullptr;
4709 : }
4710 168 : else if (poDocPoppler->isLinearized() &&
4711 0 : !poStream->FoundLinearizedHint())
4712 : {
4713 : // This is a likely defect of poppler Linearization.cc file that
4714 : // recognizes a file as linearized if the /Linearized hint is
4715 : // missing, but the content of this dictionary are present. But
4716 : // given the hacks of PDFFreeDoc() and
4717 : // VSIPDFFileStream::FillBuffer() opening such a file will
4718 : // result in a null-ptr deref at closing if we try to access a
4719 : // page and build the page cache, so just exit now
4720 0 : CPLError(CE_Failure, CPLE_AppDefined, "Invalid PDF");
4721 :
4722 0 : PDFFreeDoc(poDocPoppler);
4723 0 : return nullptr;
4724 : }
4725 : else
4726 : {
4727 168 : break;
4728 : }
4729 0 : }
4730 :
4731 168 : poCatalogPoppler = poDocPoppler->getCatalog();
4732 168 : if (poCatalogPoppler == nullptr || !poCatalogPoppler->isOk())
4733 : {
4734 0 : CPLError(CE_Failure, CPLE_AppDefined,
4735 : "Invalid PDF : invalid catalog");
4736 0 : PDFFreeDoc(poDocPoppler);
4737 0 : return nullptr;
4738 : }
4739 :
4740 168 : nPages = poDocPoppler->getNumPages();
4741 :
4742 168 : if (iPage == 1 && nPages > 10000 &&
4743 0 : CPLTestBool(CPLGetConfigOption("GDAL_PDF_LIMIT_PAGE_COUNT", "YES")))
4744 : {
4745 0 : CPLError(CE_Warning, CPLE_AppDefined,
4746 : "This PDF document reports %d pages. "
4747 : "Limiting count to 10000 for performance reasons. "
4748 : "You may remove this limit by setting the "
4749 : "GDAL_PDF_LIMIT_PAGE_COUNT configuration option to NO",
4750 : nPages);
4751 0 : nPages = 10000;
4752 : }
4753 :
4754 168 : if (iPage < 1 || iPage > nPages)
4755 : {
4756 1 : CPLError(CE_Failure, CPLE_AppDefined, "Invalid page number (%d/%d)",
4757 : iPage, nPages);
4758 1 : PDFFreeDoc(poDocPoppler);
4759 1 : return nullptr;
4760 : }
4761 :
4762 : /* Sanity check to validate page count */
4763 167 : if (iPage > 1 && nPages <= 10000 && iPage != nPages)
4764 : {
4765 4 : poPagePoppler = poCatalogPoppler->getPage(nPages);
4766 4 : if (poPagePoppler == nullptr || !poPagePoppler->isOk())
4767 : {
4768 0 : CPLError(CE_Failure, CPLE_AppDefined,
4769 : "Invalid PDF : invalid page count");
4770 0 : PDFFreeDoc(poDocPoppler);
4771 0 : return nullptr;
4772 : }
4773 : }
4774 :
4775 167 : poPagePoppler = poCatalogPoppler->getPage(iPage);
4776 167 : if (poPagePoppler == nullptr || !poPagePoppler->isOk())
4777 : {
4778 0 : CPLError(CE_Failure, CPLE_AppDefined, "Invalid PDF : invalid page");
4779 0 : PDFFreeDoc(poDocPoppler);
4780 0 : return nullptr;
4781 : }
4782 :
4783 : #if POPPLER_MAJOR_VERSION > 25 || \
4784 : (POPPLER_MAJOR_VERSION == 25 && POPPLER_MINOR_VERSION >= 3)
4785 : const Object &oPageObj = poPagePoppler->getPageObj();
4786 : #else
4787 : /* Here's the dirty part: this is a private member */
4788 : /* so we had to #define private public to get it ! */
4789 167 : const Object &oPageObj = poPagePoppler->pageObj;
4790 : #endif
4791 167 : if (!oPageObj.isDict())
4792 : {
4793 0 : CPLError(CE_Failure, CPLE_AppDefined,
4794 : "Invalid PDF : !oPageObj.isDict()");
4795 0 : PDFFreeDoc(poDocPoppler);
4796 0 : return nullptr;
4797 : }
4798 :
4799 167 : poPageObj = new GDALPDFObjectPoppler(&oPageObj);
4800 167 : Ref *poPageRef = poCatalogPoppler->getPageRef(iPage);
4801 167 : if (poPageRef != nullptr)
4802 : {
4803 334 : cpl::down_cast<GDALPDFObjectPoppler *>(poPageObj)->SetRefNumAndGen(
4804 334 : GDALPDFObjectNum(poPageRef->num), poPageRef->gen);
4805 : }
4806 : }
4807 : #endif // ~ HAVE_POPPLER
4808 :
4809 : #ifdef HAVE_PODOFO
4810 : if (bUseLib.test(PDFLIB_PODOFO) && poPageObj == nullptr)
4811 : {
4812 : #if !(PODOFO_VERSION_MAJOR > 0 || \
4813 : (PODOFO_VERSION_MAJOR == 0 && PODOFO_VERSION_MINOR >= 10))
4814 : PoDoFo::PdfError::EnableDebug(false);
4815 : PoDoFo::PdfError::EnableLogging(false);
4816 : #endif
4817 :
4818 : poDocPodofo = std::make_unique<PoDoFo::PdfMemDocument>();
4819 : try
4820 : {
4821 : poDocPodofo->Load(pszFilename);
4822 : }
4823 : catch (PoDoFo::PdfError &oError)
4824 : {
4825 : #if PODOFO_VERSION_MAJOR > 0 || \
4826 : (PODOFO_VERSION_MAJOR == 0 && PODOFO_VERSION_MINOR >= 10)
4827 : if (oError.GetCode() == PoDoFo::PdfErrorCode::InvalidPassword)
4828 : #else
4829 : if (oError.GetError() == PoDoFo::ePdfError_InvalidPassword)
4830 : #endif
4831 : {
4832 : if (pszUserPwd)
4833 : {
4834 : pszUserPwd =
4835 : PDFEnterPasswordFromConsoleIfNeeded(pszUserPwd);
4836 :
4837 : try
4838 : {
4839 : #if PODOFO_VERSION_MAJOR > 0 || \
4840 : (PODOFO_VERSION_MAJOR == 0 && PODOFO_VERSION_MINOR >= 10)
4841 : poDocPodofo =
4842 : std::make_unique<PoDoFo::PdfMemDocument>();
4843 : poDocPodofo->Load(pszFilename, pszUserPwd);
4844 : #else
4845 : poDocPodofo->SetPassword(pszUserPwd);
4846 : #endif
4847 : }
4848 : catch (PoDoFo::PdfError &oError2)
4849 : {
4850 : #if PODOFO_VERSION_MAJOR > 0 || \
4851 : (PODOFO_VERSION_MAJOR == 0 && PODOFO_VERSION_MINOR >= 10)
4852 : if (oError2.GetCode() ==
4853 : PoDoFo::PdfErrorCode::InvalidPassword)
4854 : #else
4855 : if (oError2.GetError() ==
4856 : PoDoFo::ePdfError_InvalidPassword)
4857 : #endif
4858 : {
4859 : CPLError(CE_Failure, CPLE_AppDefined,
4860 : "Invalid password");
4861 : }
4862 : else
4863 : {
4864 : CPLError(CE_Failure, CPLE_AppDefined,
4865 : "Invalid PDF : %s", oError2.what());
4866 : }
4867 : return nullptr;
4868 : }
4869 : catch (...)
4870 : {
4871 : CPLError(CE_Failure, CPLE_AppDefined, "Invalid PDF");
4872 : return nullptr;
4873 : }
4874 : }
4875 : else
4876 : {
4877 : CPLError(CE_Failure, CPLE_AppDefined,
4878 : "A password is needed. You can specify it through "
4879 : "the PDF_USER_PWD "
4880 : "configuration option / USER_PWD open option "
4881 : "(that can be set to ASK_INTERACTIVE)");
4882 : return nullptr;
4883 : }
4884 : }
4885 : else
4886 : {
4887 : CPLError(CE_Failure, CPLE_AppDefined, "Invalid PDF : %s",
4888 : oError.what());
4889 : return nullptr;
4890 : }
4891 : }
4892 : catch (...)
4893 : {
4894 : CPLError(CE_Failure, CPLE_AppDefined, "Invalid PDF");
4895 : return nullptr;
4896 : }
4897 :
4898 : #if PODOFO_VERSION_MAJOR > 0 || \
4899 : (PODOFO_VERSION_MAJOR == 0 && PODOFO_VERSION_MINOR >= 10)
4900 : auto &oPageCollections = poDocPodofo->GetPages();
4901 : nPages = static_cast<int>(oPageCollections.GetCount());
4902 : #else
4903 : nPages = poDocPodofo->GetPageCount();
4904 : #endif
4905 : if (iPage < 1 || iPage > nPages)
4906 : {
4907 : CPLError(CE_Failure, CPLE_AppDefined, "Invalid page number (%d/%d)",
4908 : iPage, nPages);
4909 : return nullptr;
4910 : }
4911 :
4912 : try
4913 : {
4914 : #if PODOFO_VERSION_MAJOR > 0 || \
4915 : (PODOFO_VERSION_MAJOR == 0 && PODOFO_VERSION_MINOR >= 10)
4916 : /* Sanity check to validate page count */
4917 : if (iPage != nPages)
4918 : CPL_IGNORE_RET_VAL(oPageCollections.GetPageAt(nPages - 1));
4919 :
4920 : poPagePodofo = &oPageCollections.GetPageAt(iPage - 1);
4921 : #else
4922 : /* Sanity check to validate page count */
4923 : if (iPage != nPages)
4924 : CPL_IGNORE_RET_VAL(poDocPodofo->GetPage(nPages - 1));
4925 :
4926 : poPagePodofo = poDocPodofo->GetPage(iPage - 1);
4927 : #endif
4928 : }
4929 : catch (PoDoFo::PdfError &oError)
4930 : {
4931 : CPLError(CE_Failure, CPLE_AppDefined, "Invalid PDF : %s",
4932 : oError.what());
4933 : return nullptr;
4934 : }
4935 : catch (...)
4936 : {
4937 : CPLError(CE_Failure, CPLE_AppDefined, "Invalid PDF");
4938 : return nullptr;
4939 : }
4940 :
4941 : if (poPagePodofo == nullptr)
4942 : {
4943 : CPLError(CE_Failure, CPLE_AppDefined, "Invalid PDF : invalid page");
4944 : return nullptr;
4945 : }
4946 :
4947 : #if PODOFO_VERSION_MAJOR > 0 || \
4948 : (PODOFO_VERSION_MAJOR == 0 && PODOFO_VERSION_MINOR >= 10)
4949 : const PoDoFo::PdfObject *pObj = &poPagePodofo->GetObject();
4950 : #else
4951 : const PoDoFo::PdfObject *pObj = poPagePodofo->GetObject();
4952 : #endif
4953 : poPageObj = new GDALPDFObjectPodofo(pObj, poDocPodofo->GetObjects());
4954 : }
4955 : #endif // ~ HAVE_PODOFO
4956 :
4957 : #ifdef HAVE_PDFIUM
4958 393 : if (bUseLib.test(PDFLIB_PDFIUM) && poPageObj == nullptr)
4959 : {
4960 226 : if (!LoadPdfiumDocumentPage(pszFilename, pszUserPwd, iPage,
4961 : &poDocPdfium, &poPagePdfium, &nPages))
4962 : {
4963 : // CPLError is called inside function
4964 14 : return nullptr;
4965 : }
4966 :
4967 212 : const auto pageObj = poPagePdfium->page->GetDict();
4968 212 : if (pageObj == nullptr)
4969 : {
4970 0 : CPLError(CE_Failure, CPLE_AppDefined,
4971 : "Invalid PDF : invalid page object");
4972 0 : UnloadPdfiumDocumentPage(&poDocPdfium, &poPagePdfium);
4973 0 : return nullptr;
4974 : }
4975 212 : poPageObj = GDALPDFObjectPdfium::Build(pageObj);
4976 : }
4977 : #endif // ~ HAVE_PDFIUM
4978 :
4979 379 : if (poPageObj == nullptr)
4980 0 : return nullptr;
4981 379 : GDALPDFDictionary *poPageDict = poPageObj->GetDictionary();
4982 379 : if (poPageDict == nullptr)
4983 : {
4984 0 : delete poPageObj;
4985 :
4986 0 : CPLError(CE_Failure, CPLE_AppDefined,
4987 : "Invalid PDF : poPageDict == nullptr");
4988 : #ifdef HAVE_POPPLER
4989 0 : if (bUseLib.test(PDFLIB_POPPLER))
4990 0 : PDFFreeDoc(poDocPoppler);
4991 : #endif
4992 : #ifdef HAVE_PDFIUM
4993 0 : if (bUseLib.test(PDFLIB_PDFIUM))
4994 : {
4995 0 : UnloadPdfiumDocumentPage(&poDocPdfium, &poPagePdfium);
4996 : }
4997 : #endif
4998 0 : return nullptr;
4999 : }
5000 :
5001 379 : const char *pszDumpObject = CPLGetConfigOption("PDF_DUMP_OBJECT", nullptr);
5002 379 : if (pszDumpObject != nullptr)
5003 : {
5004 4 : GDALPDFDumper oDumper(pszFilename, pszDumpObject);
5005 2 : oDumper.Dump(poPageObj);
5006 : }
5007 :
5008 379 : PDFDataset *poDS = new PDFDataset();
5009 379 : poDS->m_fp = std::move(fp);
5010 379 : poDS->papszOpenOptions = CSLDuplicate(poOpenInfo->papszOpenOptions);
5011 379 : poDS->m_bUseLib = bUseLib;
5012 379 : poDS->m_osFilename = pszFilename;
5013 379 : poDS->eAccess = poOpenInfo->eAccess;
5014 :
5015 379 : if (nPages > 1 && !bOpenSubdataset)
5016 : {
5017 : int i;
5018 8 : CPLStringList aosList;
5019 16 : for (i = 0; i < nPages; i++)
5020 : {
5021 : char szKey[32];
5022 12 : snprintf(szKey, sizeof(szKey), "SUBDATASET_%d_NAME", i + 1);
5023 : aosList.AddNameValue(
5024 12 : szKey, CPLSPrintf("PDF:%d:%s", i + 1, poOpenInfo->pszFilename));
5025 12 : snprintf(szKey, sizeof(szKey), "SUBDATASET_%d_DESC", i + 1);
5026 : aosList.AddNameValue(szKey, CPLSPrintf("Page %d of %s", i + 1,
5027 12 : poOpenInfo->pszFilename));
5028 : }
5029 4 : poDS->SetMetadata(aosList.List(), "SUBDATASETS");
5030 : }
5031 :
5032 : #ifdef HAVE_POPPLER
5033 379 : poDS->m_poDocPoppler = poDocPoppler;
5034 : #endif
5035 : #ifdef HAVE_PODOFO
5036 : poDS->m_poDocPodofo = poDocPodofo.release();
5037 : #endif
5038 : #ifdef HAVE_PDFIUM
5039 379 : poDS->m_poDocPdfium = poDocPdfium;
5040 379 : poDS->m_poPagePdfium = poPagePdfium;
5041 : #endif
5042 379 : poDS->m_poPageObj = poPageObj;
5043 379 : poDS->m_osUserPwd = pszUserPwd ? pszUserPwd : "";
5044 379 : poDS->m_iPage = iPage;
5045 :
5046 : const char *pszDumpCatalog =
5047 379 : CPLGetConfigOption("PDF_DUMP_CATALOG", nullptr);
5048 379 : if (pszDumpCatalog != nullptr)
5049 : {
5050 0 : GDALPDFDumper oDumper(pszFilename, pszDumpCatalog);
5051 0 : auto poCatalog = poDS->GetCatalog();
5052 0 : if (poCatalog)
5053 0 : oDumper.Dump(poCatalog);
5054 : }
5055 :
5056 379 : int nBandsGuessed = 0;
5057 379 : if (nImageNum < 0)
5058 : {
5059 379 : poDS->GuessDPI(poPageDict, &nBandsGuessed);
5060 379 : if (nBandsGuessed < 4)
5061 363 : nBandsGuessed = 0;
5062 : }
5063 : else
5064 : {
5065 : const char *pszDPI =
5066 0 : GetOption(poOpenInfo->papszOpenOptions, "DPI", nullptr);
5067 0 : if (pszDPI != nullptr)
5068 : {
5069 : // coverity[tainted_data]
5070 0 : poDS->m_dfDPI = CPLAtof(pszDPI);
5071 : }
5072 : }
5073 :
5074 379 : double dfX1 = 0.0;
5075 379 : double dfY1 = 0.0;
5076 379 : double dfX2 = 0.0;
5077 379 : double dfY2 = 0.0;
5078 :
5079 : #ifdef HAVE_POPPLER
5080 379 : if (bUseLib.test(PDFLIB_POPPLER))
5081 : {
5082 167 : const auto *psMediaBox = poPagePoppler->getMediaBox();
5083 167 : dfX1 = psMediaBox->x1;
5084 167 : dfY1 = psMediaBox->y1;
5085 167 : dfX2 = psMediaBox->x2;
5086 167 : dfY2 = psMediaBox->y2;
5087 : }
5088 : #endif
5089 :
5090 : #ifdef HAVE_PODOFO
5091 : if (bUseLib.test(PDFLIB_PODOFO))
5092 : {
5093 : CPLAssert(poPagePodofo);
5094 : auto oMediaBox = poPagePodofo->GetMediaBox();
5095 : dfX1 = oMediaBox.GetLeft();
5096 : dfY1 = oMediaBox.GetBottom();
5097 : #if PODOFO_VERSION_MAJOR > 0 || \
5098 : (PODOFO_VERSION_MAJOR == 0 && PODOFO_VERSION_MINOR >= 10)
5099 : dfX2 = dfX1 + oMediaBox.Width;
5100 : dfY2 = dfY1 + oMediaBox.Height;
5101 : #else
5102 : dfX2 = dfX1 + oMediaBox.GetWidth();
5103 : dfY2 = dfY1 + oMediaBox.GetHeight();
5104 : #endif
5105 : }
5106 : #endif
5107 :
5108 : #ifdef HAVE_PDFIUM
5109 379 : if (bUseLib.test(PDFLIB_PDFIUM))
5110 : {
5111 212 : CPLAssert(poPagePdfium);
5112 212 : CFX_FloatRect rect = poPagePdfium->page->GetBBox();
5113 212 : dfX1 = rect.left;
5114 212 : dfX2 = rect.right;
5115 212 : dfY1 = rect.bottom;
5116 212 : dfY2 = rect.top;
5117 : }
5118 : #endif // ~ HAVE_PDFIUM
5119 :
5120 379 : double dfUserUnit = poDS->m_dfDPI * USER_UNIT_IN_INCH;
5121 379 : poDS->m_dfPageWidth = dfX2 - dfX1;
5122 379 : poDS->m_dfPageHeight = dfY2 - dfY1;
5123 : // CPLDebug("PDF", "left=%f right=%f bottom=%f top=%f", dfX1, dfX2, dfY1,
5124 : // dfY2);
5125 379 : const double dfXSize = floor((dfX2 - dfX1) * dfUserUnit + 0.5);
5126 379 : const double dfYSize = floor((dfY2 - dfY1) * dfUserUnit + 0.5);
5127 379 : if (!(dfXSize >= 0 && dfXSize <= INT_MAX && dfYSize >= 0 &&
5128 379 : dfYSize <= INT_MAX))
5129 : {
5130 0 : delete poDS;
5131 0 : return nullptr;
5132 : }
5133 379 : poDS->nRasterXSize = static_cast<int>(dfXSize);
5134 379 : poDS->nRasterYSize = static_cast<int>(dfYSize);
5135 :
5136 379 : if (!GDALCheckDatasetDimensions(poDS->nRasterXSize, poDS->nRasterYSize))
5137 : {
5138 0 : delete poDS;
5139 0 : return nullptr;
5140 : }
5141 :
5142 379 : double dfRotation = 0;
5143 : #ifdef HAVE_POPPLER
5144 379 : if (bUseLib.test(PDFLIB_POPPLER))
5145 167 : dfRotation = poDocPoppler->getPageRotate(iPage);
5146 : #endif
5147 :
5148 : #ifdef HAVE_PODOFO
5149 : if (bUseLib.test(PDFLIB_PODOFO))
5150 : {
5151 : CPLAssert(poPagePodofo);
5152 : #if PODOFO_VERSION_MAJOR > 0 || \
5153 : (PODOFO_VERSION_MAJOR == 0 && PODOFO_VERSION_MINOR >= 10)
5154 : dfRotation = poPagePodofo->GetRotationRaw();
5155 : #else
5156 : dfRotation = poPagePodofo->GetRotation();
5157 : #endif
5158 : }
5159 : #endif
5160 :
5161 : #ifdef HAVE_PDFIUM
5162 379 : if (bUseLib.test(PDFLIB_PDFIUM))
5163 : {
5164 212 : CPLAssert(poPagePdfium);
5165 212 : dfRotation = poPagePdfium->page->GetPageRotation() * 90;
5166 : }
5167 : #endif
5168 :
5169 379 : if (dfRotation == 90 || dfRotation == -90 || dfRotation == 270)
5170 : {
5171 : /* FIXME: the podofo case should be implemented. This needs to rotate */
5172 : /* the output of pdftoppm */
5173 : #if defined(HAVE_POPPLER) || defined(HAVE_PDFIUM)
5174 0 : if (bUseLib.test(PDFLIB_POPPLER) || bUseLib.test(PDFLIB_PDFIUM))
5175 : {
5176 0 : int nTmp = poDS->nRasterXSize;
5177 0 : poDS->nRasterXSize = poDS->nRasterYSize;
5178 0 : poDS->nRasterYSize = nTmp;
5179 : }
5180 : #endif
5181 : }
5182 :
5183 379 : if (CSLFetchNameValue(poOpenInfo->papszOpenOptions, "@OPEN_FOR_OVERVIEW"))
5184 : {
5185 2 : poDS->m_nBlockXSize = 512;
5186 2 : poDS->m_nBlockYSize = 512;
5187 : }
5188 : /* Check if the PDF is only made of regularly tiled images */
5189 : /* (like some USGS GeoPDF production) */
5190 674 : else if (dfRotation == 0.0 && !poDS->m_asTiles.empty() &&
5191 297 : EQUAL(GetOption(poOpenInfo->papszOpenOptions, "LAYERS", "ALL"),
5192 : "ALL"))
5193 : {
5194 297 : poDS->CheckTiledRaster();
5195 297 : if (!poDS->m_aiTiles.empty())
5196 18 : poDS->SetMetadataItem("INTERLEAVE", "PIXEL", "IMAGE_STRUCTURE");
5197 : }
5198 :
5199 379 : GDALPDFObject *poLGIDict = nullptr;
5200 379 : GDALPDFObject *poVP = nullptr;
5201 379 : int bIsOGCBP = FALSE;
5202 379 : if ((poLGIDict = poPageDict->Get("LGIDict")) != nullptr && nImageNum < 0)
5203 : {
5204 : /* Cf 08-139r3_GeoPDF_Encoding_Best_Practice_Version_2.2.pdf */
5205 0 : CPLDebug("PDF", "OGC Encoding Best Practice style detected");
5206 0 : if (poDS->ParseLGIDictObject(poLGIDict))
5207 : {
5208 0 : if (poDS->m_bHasCTM)
5209 : {
5210 0 : if (dfRotation == 90)
5211 : {
5212 0 : poDS->m_gt[0] = poDS->m_adfCTM[4];
5213 0 : poDS->m_gt[1] = poDS->m_adfCTM[2] / dfUserUnit;
5214 0 : poDS->m_gt[2] = poDS->m_adfCTM[0] / dfUserUnit;
5215 0 : poDS->m_gt[3] = poDS->m_adfCTM[5];
5216 0 : poDS->m_gt[4] = poDS->m_adfCTM[3] / dfUserUnit;
5217 0 : poDS->m_gt[5] = poDS->m_adfCTM[1] / dfUserUnit;
5218 : }
5219 0 : else if (dfRotation == -90 || dfRotation == 270)
5220 : {
5221 0 : poDS->m_gt[0] = poDS->m_adfCTM[4] +
5222 0 : poDS->m_adfCTM[2] * poDS->m_dfPageHeight +
5223 0 : poDS->m_adfCTM[0] * poDS->m_dfPageWidth;
5224 0 : poDS->m_gt[1] = -poDS->m_adfCTM[2] / dfUserUnit;
5225 0 : poDS->m_gt[2] = -poDS->m_adfCTM[0] / dfUserUnit;
5226 0 : poDS->m_gt[3] = poDS->m_adfCTM[5] +
5227 0 : poDS->m_adfCTM[3] * poDS->m_dfPageHeight +
5228 0 : poDS->m_adfCTM[1] * poDS->m_dfPageWidth;
5229 0 : poDS->m_gt[4] = -poDS->m_adfCTM[3] / dfUserUnit;
5230 0 : poDS->m_gt[5] = -poDS->m_adfCTM[1] / dfUserUnit;
5231 : }
5232 : else
5233 : {
5234 0 : poDS->m_gt[0] = poDS->m_adfCTM[4] +
5235 0 : poDS->m_adfCTM[2] * dfY2 +
5236 0 : poDS->m_adfCTM[0] * dfX1;
5237 0 : poDS->m_gt[1] = poDS->m_adfCTM[0] / dfUserUnit;
5238 0 : poDS->m_gt[2] = -poDS->m_adfCTM[2] / dfUserUnit;
5239 0 : poDS->m_gt[3] = poDS->m_adfCTM[5] +
5240 0 : poDS->m_adfCTM[3] * dfY2 +
5241 0 : poDS->m_adfCTM[1] * dfX1;
5242 0 : poDS->m_gt[4] = poDS->m_adfCTM[1] / dfUserUnit;
5243 0 : poDS->m_gt[5] = -poDS->m_adfCTM[3] / dfUserUnit;
5244 : }
5245 :
5246 0 : poDS->m_bGeoTransformValid = true;
5247 : }
5248 :
5249 0 : bIsOGCBP = TRUE;
5250 :
5251 : int i;
5252 0 : for (i = 0; i < poDS->m_nGCPCount; i++)
5253 : {
5254 0 : if (dfRotation == 90)
5255 : {
5256 0 : double dfPixel =
5257 0 : poDS->m_pasGCPList[i].dfGCPPixel * dfUserUnit;
5258 0 : double dfLine =
5259 0 : poDS->m_pasGCPList[i].dfGCPLine * dfUserUnit;
5260 0 : poDS->m_pasGCPList[i].dfGCPPixel = dfLine;
5261 0 : poDS->m_pasGCPList[i].dfGCPLine = dfPixel;
5262 : }
5263 0 : else if (dfRotation == -90 || dfRotation == 270)
5264 : {
5265 0 : double dfPixel =
5266 0 : poDS->m_pasGCPList[i].dfGCPPixel * dfUserUnit;
5267 0 : double dfLine =
5268 0 : poDS->m_pasGCPList[i].dfGCPLine * dfUserUnit;
5269 0 : poDS->m_pasGCPList[i].dfGCPPixel =
5270 0 : poDS->nRasterXSize - dfLine;
5271 0 : poDS->m_pasGCPList[i].dfGCPLine =
5272 0 : poDS->nRasterYSize - dfPixel;
5273 : }
5274 : else
5275 : {
5276 0 : poDS->m_pasGCPList[i].dfGCPPixel =
5277 0 : (-dfX1 + poDS->m_pasGCPList[i].dfGCPPixel) * dfUserUnit;
5278 0 : poDS->m_pasGCPList[i].dfGCPLine =
5279 0 : (dfY2 - poDS->m_pasGCPList[i].dfGCPLine) * dfUserUnit;
5280 : }
5281 : }
5282 : }
5283 : }
5284 379 : else if ((poVP = poPageDict->Get("VP")) != nullptr && nImageNum < 0)
5285 : {
5286 : /* Cf adobe_supplement_iso32000.pdf */
5287 280 : CPLDebug("PDF", "Adobe ISO32000 style Geospatial PDF perhaps ?");
5288 280 : if (dfX1 != 0 || dfY1 != 0)
5289 : {
5290 0 : CPLDebug("PDF", "non null dfX1 or dfY1 values. untested case...");
5291 : }
5292 280 : poDS->ParseVP(poVP, dfX2 - dfX1, dfY2 - dfY1);
5293 : }
5294 : else
5295 : {
5296 : GDALPDFObject *poXObject =
5297 99 : poPageDict->LookupObject("Resources.XObject");
5298 :
5299 196 : if (poXObject != nullptr &&
5300 97 : poXObject->GetType() == PDFObjectType_Dictionary)
5301 : {
5302 97 : GDALPDFDictionary *poXObjectDict = poXObject->GetDictionary();
5303 97 : const auto &oMap = poXObjectDict->GetValues();
5304 97 : int nSubDataset = 0;
5305 398 : for (const auto &[osKey, poObj] : oMap)
5306 : {
5307 301 : if (poObj->GetType() == PDFObjectType_Dictionary)
5308 : {
5309 301 : GDALPDFDictionary *poDict = poObj->GetDictionary();
5310 301 : GDALPDFObject *poSubtype = nullptr;
5311 301 : GDALPDFObject *poMeasure = nullptr;
5312 301 : GDALPDFObject *poWidth = nullptr;
5313 301 : GDALPDFObject *poHeight = nullptr;
5314 301 : int nW = 0;
5315 301 : int nH = 0;
5316 301 : if ((poSubtype = poDict->Get("Subtype")) != nullptr &&
5317 602 : poSubtype->GetType() == PDFObjectType_Name &&
5318 301 : poSubtype->GetName() == "Image" &&
5319 256 : (poMeasure = poDict->Get("Measure")) != nullptr &&
5320 0 : poMeasure->GetType() == PDFObjectType_Dictionary &&
5321 0 : (poWidth = poDict->Get("Width")) != nullptr &&
5322 0 : poWidth->GetType() == PDFObjectType_Int &&
5323 0 : (nW = poWidth->GetInt()) > 0 &&
5324 0 : (poHeight = poDict->Get("Height")) != nullptr &&
5325 602 : poHeight->GetType() == PDFObjectType_Int &&
5326 0 : (nH = poHeight->GetInt()) > 0)
5327 : {
5328 0 : if (nImageNum < 0)
5329 0 : CPLDebug("PDF",
5330 : "Measure found on Image object (%d)",
5331 0 : poObj->GetRefNum().toInt());
5332 :
5333 0 : GDALPDFObject *poColorSpace = poDict->Get("ColorSpace");
5334 : GDALPDFObject *poBitsPerComponent =
5335 0 : poDict->Get("BitsPerComponent");
5336 0 : if (poObj->GetRefNum().toBool() &&
5337 0 : poObj->GetRefGen() == 0 &&
5338 0 : poColorSpace != nullptr &&
5339 0 : poColorSpace->GetType() == PDFObjectType_Name &&
5340 0 : (poColorSpace->GetName() == "DeviceGray" ||
5341 0 : poColorSpace->GetName() == "DeviceRGB") &&
5342 0 : (poBitsPerComponent == nullptr ||
5343 0 : (poBitsPerComponent->GetType() ==
5344 0 : PDFObjectType_Int &&
5345 0 : poBitsPerComponent->GetInt() == 8)))
5346 : {
5347 0 : if (nImageNum < 0)
5348 : {
5349 0 : nSubDataset++;
5350 0 : poDS->SetMetadataItem(
5351 : CPLSPrintf("SUBDATASET_%d_NAME",
5352 : nSubDataset),
5353 : CPLSPrintf("PDF_IMAGE:%d:%d:%s", iPage,
5354 0 : poObj->GetRefNum().toInt(),
5355 : pszFilename),
5356 : "SUBDATASETS");
5357 0 : poDS->SetMetadataItem(
5358 : CPLSPrintf("SUBDATASET_%d_DESC",
5359 : nSubDataset),
5360 : CPLSPrintf("Georeferenced image of size "
5361 : "%dx%d of page %d of %s",
5362 : nW, nH, iPage, pszFilename),
5363 : "SUBDATASETS");
5364 : }
5365 0 : else if (poObj->GetRefNum().toInt() == nImageNum)
5366 : {
5367 0 : poDS->nRasterXSize = nW;
5368 0 : poDS->nRasterYSize = nH;
5369 0 : poDS->ParseMeasure(poMeasure, nW, nH, 0, nH, nW,
5370 : 0);
5371 0 : poDS->m_poImageObj = poObj;
5372 0 : if (poColorSpace->GetName() == "DeviceGray")
5373 0 : nBandsGuessed = 1;
5374 0 : break;
5375 : }
5376 : }
5377 : }
5378 : }
5379 : }
5380 : }
5381 :
5382 99 : if (nImageNum >= 0 && poDS->m_poImageObj == nullptr)
5383 : {
5384 0 : CPLError(CE_Failure, CPLE_AppDefined, "Cannot find image %d",
5385 : nImageNum);
5386 0 : delete poDS;
5387 0 : return nullptr;
5388 : }
5389 :
5390 : /* Not a geospatial PDF doc */
5391 : }
5392 :
5393 : /* If pixel size or top left coordinates are very close to an int, round
5394 : * them to the int */
5395 : double dfEps =
5396 379 : (fabs(poDS->m_gt[0]) > 1e5 && fabs(poDS->m_gt[3]) > 1e5) ? 1e-5 : 1e-8;
5397 379 : poDS->m_gt[0] = ROUND_IF_CLOSE(poDS->m_gt[0], dfEps);
5398 379 : poDS->m_gt[1] = ROUND_IF_CLOSE(poDS->m_gt[1]);
5399 379 : poDS->m_gt[3] = ROUND_IF_CLOSE(poDS->m_gt[3], dfEps);
5400 379 : poDS->m_gt[5] = ROUND_IF_CLOSE(poDS->m_gt[5]);
5401 :
5402 379 : if (bUseLib.test(PDFLIB_PDFIUM))
5403 : {
5404 : // Attempt to "fix" the loss of precision due to the use of float32 for
5405 : // numbers by pdfium
5406 312 : if ((fabs(poDS->m_gt[0]) > 1e5 || fabs(poDS->m_gt[3]) > 1e5) &&
5407 112 : fabs(poDS->m_gt[0] - std::round(poDS->m_gt[0])) <
5408 112 : 1e-6 * fabs(poDS->m_gt[0]) &&
5409 99 : fabs(poDS->m_gt[1] - std::round(poDS->m_gt[1])) <
5410 99 : 1e-3 * fabs(poDS->m_gt[1]) &&
5411 89 : fabs(poDS->m_gt[3] - std::round(poDS->m_gt[3])) <
5412 513 : 1e-6 * fabs(poDS->m_gt[3]) &&
5413 89 : fabs(poDS->m_gt[5] - std::round(poDS->m_gt[5])) <
5414 89 : 1e-3 * fabs(poDS->m_gt[5]))
5415 : {
5416 623 : for (int i = 0; i < 6; i++)
5417 : {
5418 534 : poDS->m_gt[i] = std::round(poDS->m_gt[i]);
5419 : }
5420 : }
5421 : }
5422 :
5423 379 : if (poDS->m_poNeatLine)
5424 : {
5425 279 : char *pszNeatLineWkt = nullptr;
5426 279 : OGRLinearRing *poRing = poDS->m_poNeatLine->getExteriorRing();
5427 : /* Adobe style is already in target SRS units */
5428 279 : if (bIsOGCBP)
5429 : {
5430 0 : int nPoints = poRing->getNumPoints();
5431 : int i;
5432 :
5433 0 : for (i = 0; i < nPoints; i++)
5434 : {
5435 : double x, y;
5436 0 : if (dfRotation == 90.0)
5437 : {
5438 0 : x = poRing->getY(i) * dfUserUnit;
5439 0 : y = poRing->getX(i) * dfUserUnit;
5440 : }
5441 0 : else if (dfRotation == -90.0 || dfRotation == 270.0)
5442 : {
5443 0 : x = poDS->nRasterXSize - poRing->getY(i) * dfUserUnit;
5444 0 : y = poDS->nRasterYSize - poRing->getX(i) * dfUserUnit;
5445 : }
5446 : else
5447 : {
5448 0 : x = (-dfX1 + poRing->getX(i)) * dfUserUnit;
5449 0 : y = (dfY2 - poRing->getY(i)) * dfUserUnit;
5450 : }
5451 : double X =
5452 0 : poDS->m_gt[0] + x * poDS->m_gt[1] + y * poDS->m_gt[2];
5453 : double Y =
5454 0 : poDS->m_gt[3] + x * poDS->m_gt[4] + y * poDS->m_gt[5];
5455 0 : poRing->setPoint(i, X, Y);
5456 : }
5457 : }
5458 279 : poRing->closeRings();
5459 :
5460 279 : poDS->m_poNeatLine->exportToWkt(&pszNeatLineWkt);
5461 279 : if (nImageNum < 0)
5462 279 : poDS->SetMetadataItem("NEATLINE", pszNeatLineWkt);
5463 279 : CPLFree(pszNeatLineWkt);
5464 : }
5465 :
5466 379 : poDS->MapOCGsToPages();
5467 :
5468 : #ifdef HAVE_POPPLER
5469 379 : if (bUseLib.test(PDFLIB_POPPLER))
5470 : {
5471 167 : auto poMetadata = poCatalogPoppler->readMetadata();
5472 167 : if (poMetadata)
5473 : {
5474 17 : const char *pszContent = poMetadata->c_str();
5475 17 : if (pszContent != nullptr &&
5476 17 : STARTS_WITH(pszContent, "<?xpacket begin="))
5477 : {
5478 17 : const char *const apszMDList[2] = {pszContent, nullptr};
5479 17 : poDS->SetMetadata(const_cast<char **>(apszMDList), "xml:XMP");
5480 : }
5481 : #if (POPPLER_MAJOR_VERSION < 21 || \
5482 : (POPPLER_MAJOR_VERSION == 21 && POPPLER_MINOR_VERSION < 10))
5483 17 : delete poMetadata;
5484 : #endif
5485 : }
5486 :
5487 : /* Read Info object */
5488 : /* The test is necessary since with some corrupted PDFs
5489 : * poDocPoppler->getDocInfo() */
5490 : /* might abort() */
5491 167 : if (poDocPoppler->getXRef()->isOk())
5492 : {
5493 334 : Object oInfo = poDocPoppler->getDocInfo();
5494 334 : GDALPDFObjectPoppler oInfoObjPoppler(&oInfo, FALSE);
5495 167 : poDS->ParseInfo(&oInfoObjPoppler);
5496 : }
5497 :
5498 : /* Find layers */
5499 322 : poDS->FindLayersPoppler(
5500 155 : (bOpenSubdataset || bOpenSubdatasetImage) ? iPage : 0);
5501 :
5502 : /* Turn user specified layers on or off */
5503 167 : poDS->TurnLayersOnOffPoppler();
5504 : }
5505 : #endif
5506 :
5507 : #ifdef HAVE_PODOFO
5508 : if (bUseLib.test(PDFLIB_PODOFO))
5509 : {
5510 : for (const auto &obj : poDS->m_poDocPodofo->GetObjects())
5511 : {
5512 : GDALPDFObjectPodofo oObjPodofo(obj,
5513 : poDS->m_poDocPodofo->GetObjects());
5514 : poDS->FindXMP(&oObjPodofo);
5515 : }
5516 :
5517 : /* Find layers */
5518 : poDS->FindLayersGeneric(poPageDict);
5519 :
5520 : /* Read Info object */
5521 : const PoDoFo::PdfInfo *poInfo = poDS->m_poDocPodofo->GetInfo();
5522 : if (poInfo != nullptr)
5523 : {
5524 : GDALPDFObjectPodofo oInfoObjPodofo(
5525 : #if PODOFO_VERSION_MAJOR > 0 || \
5526 : (PODOFO_VERSION_MAJOR == 0 && PODOFO_VERSION_MINOR >= 10)
5527 : &(poInfo->GetObject()),
5528 : #else
5529 : poInfo->GetObject(),
5530 : #endif
5531 : poDS->m_poDocPodofo->GetObjects());
5532 : poDS->ParseInfo(&oInfoObjPodofo);
5533 : }
5534 : }
5535 : #endif
5536 : #ifdef HAVE_PDFIUM
5537 379 : if (bUseLib.test(PDFLIB_PDFIUM))
5538 : {
5539 : // coverity is confused by WrapRetain(), believing that multiple
5540 : // smart pointers manage the same raw pointer. Which is actually
5541 : // true, but a RetainPtr holds a reference counted object. It is
5542 : // thus safe to have several RetainPtr holding it.
5543 : // coverity[multiple_init_smart_ptr]
5544 212 : GDALPDFObjectPdfium *poRoot = GDALPDFObjectPdfium::Build(
5545 424 : pdfium::WrapRetain(poDocPdfium->doc->GetRoot()));
5546 212 : if (poRoot->GetType() == PDFObjectType_Dictionary)
5547 : {
5548 212 : GDALPDFDictionary *poDict = poRoot->GetDictionary();
5549 212 : GDALPDFObject *poMetadata(poDict->Get("Metadata"));
5550 212 : if (poMetadata != nullptr)
5551 : {
5552 20 : GDALPDFStream *poStream = poMetadata->GetStream();
5553 20 : if (poStream != nullptr)
5554 : {
5555 18 : char *pszContent = poStream->GetBytes();
5556 18 : const auto nLength = poStream->GetLength();
5557 18 : if (pszContent != nullptr && nLength > 15 &&
5558 18 : STARTS_WITH(pszContent, "<?xpacket begin="))
5559 : {
5560 : char *apszMDList[2];
5561 18 : apszMDList[0] = pszContent;
5562 18 : apszMDList[1] = nullptr;
5563 18 : poDS->SetMetadata(apszMDList, "xml:XMP");
5564 : }
5565 18 : CPLFree(pszContent);
5566 : }
5567 : }
5568 : }
5569 212 : delete poRoot;
5570 :
5571 : /* Find layers */
5572 212 : poDS->FindLayersPdfium((bOpenSubdataset || bOpenSubdatasetImage) ? iPage
5573 : : 0);
5574 :
5575 : /* Turn user specified layers on or off */
5576 212 : poDS->TurnLayersOnOffPdfium();
5577 :
5578 : GDALPDFObjectPdfium *poInfo =
5579 212 : GDALPDFObjectPdfium::Build(poDocPdfium->doc->GetInfo());
5580 212 : if (poInfo)
5581 : {
5582 : /* Read Info object */
5583 38 : poDS->ParseInfo(poInfo);
5584 38 : delete poInfo;
5585 : }
5586 : }
5587 : #endif // ~ HAVE_PDFIUM
5588 :
5589 379 : int nBands = 3;
5590 : #ifdef HAVE_PDFIUM
5591 : // Use Alpha channel for PDFIUM as default format RGBA
5592 379 : if (bUseLib.test(PDFLIB_PDFIUM))
5593 212 : nBands = 4;
5594 : #endif
5595 379 : if (nBandsGuessed)
5596 16 : nBands = nBandsGuessed;
5597 : const char *pszPDFBands =
5598 379 : GetOption(poOpenInfo->papszOpenOptions, "BANDS", nullptr);
5599 379 : if (pszPDFBands)
5600 : {
5601 2 : nBands = atoi(pszPDFBands);
5602 2 : if (nBands != 3 && nBands != 4)
5603 : {
5604 0 : CPLError(CE_Warning, CPLE_NotSupported,
5605 : "Invalid value for GDAL_PDF_BANDS. Using 3 as a fallback");
5606 0 : nBands = 3;
5607 : }
5608 : }
5609 : #ifdef HAVE_PODOFO
5610 : if (bUseLib.test(PDFLIB_PODOFO) && nBands == 4 && poDS->m_aiTiles.empty())
5611 : {
5612 : CPLError(CE_Warning, CPLE_NotSupported,
5613 : "GDAL_PDF_BANDS=4 not supported when PDF driver is compiled "
5614 : "against Podofo. "
5615 : "Using 3 as a fallback");
5616 : nBands = 3;
5617 : }
5618 : #endif
5619 :
5620 : int iBand;
5621 1734 : for (iBand = 1; iBand <= nBands; iBand++)
5622 : {
5623 1355 : if (poDS->m_poImageObj != nullptr)
5624 0 : poDS->SetBand(iBand, new PDFImageRasterBand(poDS, iBand));
5625 : else
5626 1355 : poDS->SetBand(iBand, new PDFRasterBand(poDS, iBand, 0));
5627 : }
5628 :
5629 : /* Check if this is a raster-only PDF file and that we are */
5630 : /* opened in vector-only mode */
5631 867 : if ((poOpenInfo->nOpenFlags & GDAL_OF_RASTER) == 0 &&
5632 396 : (poOpenInfo->nOpenFlags & GDAL_OF_VECTOR) != 0 &&
5633 17 : !poDS->OpenVectorLayers(poPageDict))
5634 : {
5635 0 : CPLDebug("PDF", "This is a raster-only PDF dataset, "
5636 : "but it has been opened in vector-only mode");
5637 : /* Clear dirty flag */
5638 0 : poDS->m_bProjDirty = false;
5639 0 : poDS->m_bNeatLineDirty = false;
5640 0 : poDS->m_bInfoDirty = false;
5641 0 : poDS->m_bXMPDirty = false;
5642 0 : delete poDS;
5643 0 : return nullptr;
5644 : }
5645 :
5646 : /* -------------------------------------------------------------------- */
5647 : /* Initialize any PAM information. */
5648 : /* -------------------------------------------------------------------- */
5649 379 : if (bOpenSubdataset || bOpenSubdatasetImage)
5650 : {
5651 24 : poDS->SetPhysicalFilename(pszFilename);
5652 24 : poDS->SetSubdatasetName(osSubdatasetName.c_str());
5653 : }
5654 : else
5655 : {
5656 355 : poDS->SetDescription(poOpenInfo->pszFilename);
5657 : }
5658 :
5659 379 : poDS->TryLoadXML();
5660 :
5661 : /* -------------------------------------------------------------------- */
5662 : /* Support overviews. */
5663 : /* -------------------------------------------------------------------- */
5664 379 : if (!CSLFetchNameValue(poOpenInfo->papszOpenOptions, "@OPEN_FOR_OVERVIEW"))
5665 : {
5666 377 : poDS->oOvManager.Initialize(poDS, poOpenInfo->pszFilename);
5667 : }
5668 :
5669 : /* Clear dirty flag */
5670 379 : poDS->m_bProjDirty = false;
5671 379 : poDS->m_bNeatLineDirty = false;
5672 379 : poDS->m_bInfoDirty = false;
5673 379 : poDS->m_bXMPDirty = false;
5674 :
5675 379 : return (poDS);
5676 : }
5677 :
5678 : /************************************************************************/
5679 : /* ParseLGIDictObject() */
5680 : /************************************************************************/
5681 :
5682 0 : int PDFDataset::ParseLGIDictObject(GDALPDFObject *poLGIDict)
5683 : {
5684 0 : bool bOK = false;
5685 0 : if (poLGIDict->GetType() == PDFObjectType_Array)
5686 : {
5687 0 : GDALPDFArray *poArray = poLGIDict->GetArray();
5688 0 : int nArrayLength = poArray->GetLength();
5689 0 : int iMax = -1;
5690 0 : GDALPDFObject *poArrayElt = nullptr;
5691 0 : for (int i = 0; i < nArrayLength; i++)
5692 : {
5693 0 : if ((poArrayElt = poArray->Get(i)) == nullptr ||
5694 0 : poArrayElt->GetType() != PDFObjectType_Dictionary)
5695 : {
5696 0 : CPLError(CE_Failure, CPLE_AppDefined,
5697 : "LGIDict[%d] is not a dictionary", i);
5698 0 : return FALSE;
5699 : }
5700 :
5701 0 : int bIsBestCandidate = FALSE;
5702 0 : if (ParseLGIDictDictFirstPass(poArrayElt->GetDictionary(),
5703 0 : &bIsBestCandidate))
5704 : {
5705 0 : if (bIsBestCandidate || iMax < 0)
5706 0 : iMax = i;
5707 : }
5708 : }
5709 :
5710 0 : if (iMax < 0)
5711 0 : return FALSE;
5712 :
5713 0 : poArrayElt = poArray->Get(iMax);
5714 0 : bOK = CPL_TO_BOOL(
5715 0 : ParseLGIDictDictSecondPass(poArrayElt->GetDictionary()));
5716 : }
5717 0 : else if (poLGIDict->GetType() == PDFObjectType_Dictionary)
5718 : {
5719 0 : bOK = ParseLGIDictDictFirstPass(poLGIDict->GetDictionary()) &&
5720 0 : ParseLGIDictDictSecondPass(poLGIDict->GetDictionary());
5721 : }
5722 : else
5723 : {
5724 0 : CPLError(CE_Failure, CPLE_AppDefined, "LGIDict is of type %s",
5725 0 : poLGIDict->GetTypeName());
5726 : }
5727 :
5728 0 : return bOK;
5729 : }
5730 :
5731 : /************************************************************************/
5732 : /* Get() */
5733 : /************************************************************************/
5734 :
5735 19940 : static double Get(GDALPDFObject *poObj, int nIndice)
5736 : {
5737 19940 : if (poObj->GetType() == PDFObjectType_Array && nIndice >= 0)
5738 : {
5739 8856 : poObj = poObj->GetArray()->Get(nIndice);
5740 8856 : if (poObj == nullptr)
5741 0 : return 0;
5742 8856 : return Get(poObj);
5743 : }
5744 11084 : else if (poObj->GetType() == PDFObjectType_Int)
5745 8873 : return poObj->GetInt();
5746 2211 : else if (poObj->GetType() == PDFObjectType_Real)
5747 2211 : return poObj->GetReal();
5748 0 : else if (poObj->GetType() == PDFObjectType_String)
5749 : {
5750 0 : const char *pszStr = poObj->GetString().c_str();
5751 0 : size_t nLen = strlen(pszStr);
5752 0 : if (nLen == 0)
5753 0 : return 0;
5754 : /* cf Military_Installations_2008.pdf that has values like "96 0 0.0W"
5755 : */
5756 0 : char chLast = pszStr[nLen - 1];
5757 0 : if (chLast == 'W' || chLast == 'E' || chLast == 'N' || chLast == 'S')
5758 : {
5759 0 : double dfDeg = CPLAtof(pszStr);
5760 0 : double dfMin = 0.0;
5761 0 : double dfSec = 0.0;
5762 0 : const char *pszNext = strchr(pszStr, ' ');
5763 0 : if (pszNext)
5764 0 : pszNext++;
5765 0 : if (pszNext)
5766 0 : dfMin = CPLAtof(pszNext);
5767 0 : if (pszNext)
5768 0 : pszNext = strchr(pszNext, ' ');
5769 0 : if (pszNext)
5770 0 : pszNext++;
5771 0 : if (pszNext)
5772 0 : dfSec = CPLAtof(pszNext);
5773 0 : double dfVal = dfDeg + dfMin / 60 + dfSec / 3600;
5774 0 : if (chLast == 'W' || chLast == 'S')
5775 0 : return -dfVal;
5776 : else
5777 0 : return dfVal;
5778 : }
5779 0 : return CPLAtof(pszStr);
5780 : }
5781 : else
5782 : {
5783 0 : CPLError(CE_Warning, CPLE_AppDefined, "Unexpected type : %s",
5784 0 : poObj->GetTypeName());
5785 0 : return 0;
5786 : }
5787 : }
5788 :
5789 : /************************************************************************/
5790 : /* Get() */
5791 : /************************************************************************/
5792 :
5793 0 : static double Get(GDALPDFDictionary *poDict, const char *pszName)
5794 : {
5795 0 : GDALPDFObject *poObj = poDict->Get(pszName);
5796 0 : if (poObj != nullptr)
5797 0 : return Get(poObj);
5798 0 : CPLError(CE_Failure, CPLE_AppDefined, "Cannot find parameter %s", pszName);
5799 0 : return 0;
5800 : }
5801 :
5802 : /************************************************************************/
5803 : /* ParseLGIDictDictFirstPass() */
5804 : /************************************************************************/
5805 :
5806 0 : int PDFDataset::ParseLGIDictDictFirstPass(GDALPDFDictionary *poLGIDict,
5807 : int *pbIsBestCandidate)
5808 : {
5809 0 : if (pbIsBestCandidate)
5810 0 : *pbIsBestCandidate = FALSE;
5811 :
5812 0 : if (poLGIDict == nullptr)
5813 0 : return FALSE;
5814 :
5815 : /* -------------------------------------------------------------------- */
5816 : /* Extract Type attribute */
5817 : /* -------------------------------------------------------------------- */
5818 0 : GDALPDFObject *poType = poLGIDict->Get("Type");
5819 0 : if (poType == nullptr)
5820 : {
5821 0 : CPLError(CE_Failure, CPLE_AppDefined,
5822 : "Cannot find Type of LGIDict object");
5823 0 : return FALSE;
5824 : }
5825 :
5826 0 : if (poType->GetType() != PDFObjectType_Name)
5827 : {
5828 0 : CPLError(CE_Failure, CPLE_AppDefined,
5829 : "Invalid type for Type of LGIDict object");
5830 0 : return FALSE;
5831 : }
5832 :
5833 0 : if (strcmp(poType->GetName().c_str(), "LGIDict") != 0)
5834 : {
5835 0 : CPLError(CE_Failure, CPLE_AppDefined,
5836 : "Invalid value for Type of LGIDict object : %s",
5837 0 : poType->GetName().c_str());
5838 0 : return FALSE;
5839 : }
5840 :
5841 : /* -------------------------------------------------------------------- */
5842 : /* Extract Version attribute */
5843 : /* -------------------------------------------------------------------- */
5844 0 : GDALPDFObject *poVersion = poLGIDict->Get("Version");
5845 0 : if (poVersion == nullptr)
5846 : {
5847 0 : CPLError(CE_Failure, CPLE_AppDefined,
5848 : "Cannot find Version of LGIDict object");
5849 0 : return FALSE;
5850 : }
5851 :
5852 0 : if (poVersion->GetType() == PDFObjectType_String)
5853 : {
5854 : /* OGC best practice is 2.1 */
5855 0 : CPLDebug("PDF", "LGIDict Version : %s", poVersion->GetString().c_str());
5856 : }
5857 0 : else if (poVersion->GetType() == PDFObjectType_Int)
5858 : {
5859 : /* Old TerraGo is 2 */
5860 0 : CPLDebug("PDF", "LGIDict Version : %d", poVersion->GetInt());
5861 : }
5862 :
5863 : /* USGS PDF maps have several LGIDict. Keep the one whose description */
5864 : /* is "Map Layers" by default */
5865 : const char *pszNeatlineToSelect =
5866 0 : GetOption(papszOpenOptions, "NEATLINE", "Map Layers");
5867 :
5868 : /* -------------------------------------------------------------------- */
5869 : /* Extract Neatline attribute */
5870 : /* -------------------------------------------------------------------- */
5871 0 : GDALPDFObject *poNeatline = poLGIDict->Get("Neatline");
5872 0 : if (poNeatline != nullptr && poNeatline->GetType() == PDFObjectType_Array)
5873 : {
5874 0 : int nLength = poNeatline->GetArray()->GetLength();
5875 0 : if ((nLength % 2) != 0 || nLength < 4)
5876 : {
5877 0 : CPLError(CE_Failure, CPLE_AppDefined,
5878 : "Invalid length for Neatline");
5879 0 : return FALSE;
5880 : }
5881 :
5882 0 : GDALPDFObject *poDescription = poLGIDict->Get("Description");
5883 0 : bool bIsAskedNeatline = false;
5884 0 : if (poDescription != nullptr &&
5885 0 : poDescription->GetType() == PDFObjectType_String)
5886 : {
5887 0 : CPLDebug("PDF", "Description = %s",
5888 0 : poDescription->GetString().c_str());
5889 :
5890 0 : if (EQUAL(poDescription->GetString().c_str(), pszNeatlineToSelect))
5891 : {
5892 0 : m_dfMaxArea = 1e300;
5893 0 : bIsAskedNeatline = true;
5894 : }
5895 : }
5896 :
5897 0 : if (!bIsAskedNeatline)
5898 : {
5899 0 : double dfMinX = 0.0;
5900 0 : double dfMinY = 0.0;
5901 0 : double dfMaxX = 0.0;
5902 0 : double dfMaxY = 0.0;
5903 0 : for (int i = 0; i < nLength; i += 2)
5904 : {
5905 0 : double dfX = Get(poNeatline, i);
5906 0 : double dfY = Get(poNeatline, i + 1);
5907 0 : if (i == 0 || dfX < dfMinX)
5908 0 : dfMinX = dfX;
5909 0 : if (i == 0 || dfY < dfMinY)
5910 0 : dfMinY = dfY;
5911 0 : if (i == 0 || dfX > dfMaxX)
5912 0 : dfMaxX = dfX;
5913 0 : if (i == 0 || dfY > dfMaxY)
5914 0 : dfMaxY = dfY;
5915 : }
5916 0 : double dfArea = (dfMaxX - dfMinX) * (dfMaxY - dfMinY);
5917 0 : if (dfArea < m_dfMaxArea)
5918 : {
5919 0 : CPLDebug("PDF", "Not the largest neatline. Skipping it");
5920 0 : return TRUE;
5921 : }
5922 :
5923 0 : CPLDebug("PDF", "This is the largest neatline for now");
5924 0 : m_dfMaxArea = dfArea;
5925 : }
5926 : else
5927 0 : CPLDebug("PDF", "The \"%s\" registration will be selected",
5928 : pszNeatlineToSelect);
5929 :
5930 0 : if (pbIsBestCandidate)
5931 0 : *pbIsBestCandidate = TRUE;
5932 :
5933 0 : delete m_poNeatLine;
5934 0 : m_poNeatLine = new OGRPolygon();
5935 0 : OGRLinearRing *poRing = new OGRLinearRing();
5936 0 : if (nLength == 4)
5937 : {
5938 : /* 2 points only ? They are the bounding box */
5939 0 : double dfX1 = Get(poNeatline, 0);
5940 0 : double dfY1 = Get(poNeatline, 1);
5941 0 : double dfX2 = Get(poNeatline, 2);
5942 0 : double dfY2 = Get(poNeatline, 3);
5943 0 : poRing->addPoint(dfX1, dfY1);
5944 0 : poRing->addPoint(dfX2, dfY1);
5945 0 : poRing->addPoint(dfX2, dfY2);
5946 0 : poRing->addPoint(dfX1, dfY2);
5947 : }
5948 : else
5949 : {
5950 0 : for (int i = 0; i < nLength; i += 2)
5951 : {
5952 0 : double dfX = Get(poNeatline, i);
5953 0 : double dfY = Get(poNeatline, i + 1);
5954 0 : poRing->addPoint(dfX, dfY);
5955 : }
5956 : }
5957 0 : poRing->closeRings();
5958 0 : m_poNeatLine->addRingDirectly(poRing);
5959 : }
5960 :
5961 0 : return TRUE;
5962 : }
5963 :
5964 : /************************************************************************/
5965 : /* ParseLGIDictDictSecondPass() */
5966 : /************************************************************************/
5967 :
5968 0 : int PDFDataset::ParseLGIDictDictSecondPass(GDALPDFDictionary *poLGIDict)
5969 : {
5970 : int i;
5971 :
5972 : /* -------------------------------------------------------------------- */
5973 : /* Extract Description attribute */
5974 : /* -------------------------------------------------------------------- */
5975 0 : GDALPDFObject *poDescription = poLGIDict->Get("Description");
5976 0 : if (poDescription != nullptr &&
5977 0 : poDescription->GetType() == PDFObjectType_String)
5978 : {
5979 0 : CPLDebug("PDF", "Description = %s", poDescription->GetString().c_str());
5980 : }
5981 :
5982 : /* -------------------------------------------------------------------- */
5983 : /* Extract CTM attribute */
5984 : /* -------------------------------------------------------------------- */
5985 0 : GDALPDFObject *poCTM = poLGIDict->Get("CTM");
5986 0 : m_bHasCTM = false;
5987 0 : if (poCTM != nullptr && poCTM->GetType() == PDFObjectType_Array &&
5988 0 : CPLTestBool(CPLGetConfigOption("PDF_USE_CTM", "YES")))
5989 : {
5990 0 : int nLength = poCTM->GetArray()->GetLength();
5991 0 : if (nLength != 6)
5992 : {
5993 0 : CPLError(CE_Failure, CPLE_AppDefined, "Invalid length for CTM");
5994 0 : return FALSE;
5995 : }
5996 :
5997 0 : m_bHasCTM = true;
5998 0 : for (i = 0; i < nLength; i++)
5999 : {
6000 0 : m_adfCTM[i] = Get(poCTM, i);
6001 : /* Nullify rotation terms that are significantly smaller than */
6002 : /* scaling terms. */
6003 0 : if ((i == 1 || i == 2) &&
6004 0 : fabs(m_adfCTM[i]) < fabs(m_adfCTM[0]) * 1e-10)
6005 0 : m_adfCTM[i] = 0;
6006 0 : CPLDebug("PDF", "CTM[%d] = %.16g", i, m_adfCTM[i]);
6007 : }
6008 : }
6009 :
6010 : /* -------------------------------------------------------------------- */
6011 : /* Extract Registration attribute */
6012 : /* -------------------------------------------------------------------- */
6013 0 : GDALPDFObject *poRegistration = poLGIDict->Get("Registration");
6014 0 : if (poRegistration != nullptr &&
6015 0 : poRegistration->GetType() == PDFObjectType_Array)
6016 : {
6017 0 : GDALPDFArray *poRegistrationArray = poRegistration->GetArray();
6018 0 : int nLength = poRegistrationArray->GetLength();
6019 0 : if (nLength > 4 || (!m_bHasCTM && nLength >= 2) ||
6020 0 : CPLTestBool(CPLGetConfigOption("PDF_REPORT_GCPS", "NO")))
6021 : {
6022 0 : m_nGCPCount = 0;
6023 0 : m_pasGCPList =
6024 0 : static_cast<GDAL_GCP *>(CPLCalloc(sizeof(GDAL_GCP), nLength));
6025 :
6026 0 : for (i = 0; i < nLength; i++)
6027 : {
6028 0 : GDALPDFObject *poGCP = poRegistrationArray->Get(i);
6029 0 : if (poGCP != nullptr &&
6030 0 : poGCP->GetType() == PDFObjectType_Array &&
6031 0 : poGCP->GetArray()->GetLength() == 4)
6032 : {
6033 0 : double dfUserX = Get(poGCP, 0);
6034 0 : double dfUserY = Get(poGCP, 1);
6035 0 : double dfX = Get(poGCP, 2);
6036 0 : double dfY = Get(poGCP, 3);
6037 0 : CPLDebug("PDF", "GCP[%d].userX = %.16g", i, dfUserX);
6038 0 : CPLDebug("PDF", "GCP[%d].userY = %.16g", i, dfUserY);
6039 0 : CPLDebug("PDF", "GCP[%d].x = %.16g", i, dfX);
6040 0 : CPLDebug("PDF", "GCP[%d].y = %.16g", i, dfY);
6041 :
6042 : char szID[32];
6043 0 : snprintf(szID, sizeof(szID), "%d", m_nGCPCount + 1);
6044 0 : m_pasGCPList[m_nGCPCount].pszId = CPLStrdup(szID);
6045 0 : m_pasGCPList[m_nGCPCount].pszInfo = CPLStrdup("");
6046 0 : m_pasGCPList[m_nGCPCount].dfGCPPixel = dfUserX;
6047 0 : m_pasGCPList[m_nGCPCount].dfGCPLine = dfUserY;
6048 0 : m_pasGCPList[m_nGCPCount].dfGCPX = dfX;
6049 0 : m_pasGCPList[m_nGCPCount].dfGCPY = dfY;
6050 0 : m_nGCPCount++;
6051 : }
6052 : }
6053 :
6054 0 : if (m_nGCPCount == 0)
6055 : {
6056 0 : CPLFree(m_pasGCPList);
6057 0 : m_pasGCPList = nullptr;
6058 : }
6059 : }
6060 : }
6061 :
6062 0 : if (!m_bHasCTM && m_nGCPCount == 0)
6063 : {
6064 0 : CPLDebug("PDF", "Neither CTM nor Registration found");
6065 0 : return FALSE;
6066 : }
6067 :
6068 : /* -------------------------------------------------------------------- */
6069 : /* Extract Projection attribute */
6070 : /* -------------------------------------------------------------------- */
6071 0 : GDALPDFObject *poProjection = poLGIDict->Get("Projection");
6072 0 : if (poProjection == nullptr ||
6073 0 : poProjection->GetType() != PDFObjectType_Dictionary)
6074 : {
6075 0 : CPLError(CE_Failure, CPLE_AppDefined, "Could not find Projection");
6076 0 : return FALSE;
6077 : }
6078 :
6079 0 : return ParseProjDict(poProjection->GetDictionary());
6080 : }
6081 :
6082 : /************************************************************************/
6083 : /* ParseProjDict() */
6084 : /************************************************************************/
6085 :
6086 0 : int PDFDataset::ParseProjDict(GDALPDFDictionary *poProjDict)
6087 : {
6088 0 : if (poProjDict == nullptr)
6089 0 : return FALSE;
6090 0 : OGRSpatialReference oSRS;
6091 0 : oSRS.SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER);
6092 :
6093 : /* -------------------------------------------------------------------- */
6094 : /* Extract WKT attribute (GDAL extension) */
6095 : /* -------------------------------------------------------------------- */
6096 0 : GDALPDFObject *poWKT = poProjDict->Get("WKT");
6097 0 : if (poWKT != nullptr && poWKT->GetType() == PDFObjectType_String &&
6098 0 : CPLTestBool(CPLGetConfigOption("GDAL_PDF_OGC_BP_READ_WKT", "TRUE")))
6099 : {
6100 0 : CPLDebug("PDF", "Found WKT attribute (GDAL extension). Using it");
6101 0 : const char *pszWKTRead = poWKT->GetString().c_str();
6102 0 : if (pszWKTRead[0] != 0)
6103 0 : m_oSRS.importFromWkt(pszWKTRead);
6104 0 : return TRUE;
6105 : }
6106 :
6107 : /* -------------------------------------------------------------------- */
6108 : /* Extract Type attribute */
6109 : /* -------------------------------------------------------------------- */
6110 0 : GDALPDFObject *poType = poProjDict->Get("Type");
6111 0 : if (poType == nullptr)
6112 : {
6113 0 : CPLError(CE_Failure, CPLE_AppDefined,
6114 : "Cannot find Type of Projection object");
6115 0 : return FALSE;
6116 : }
6117 :
6118 0 : if (poType->GetType() != PDFObjectType_Name)
6119 : {
6120 0 : CPLError(CE_Failure, CPLE_AppDefined,
6121 : "Invalid type for Type of Projection object");
6122 0 : return FALSE;
6123 : }
6124 :
6125 0 : if (strcmp(poType->GetName().c_str(), "Projection") != 0)
6126 : {
6127 0 : CPLError(CE_Failure, CPLE_AppDefined,
6128 : "Invalid value for Type of Projection object : %s",
6129 0 : poType->GetName().c_str());
6130 0 : return FALSE;
6131 : }
6132 :
6133 : /* -------------------------------------------------------------------- */
6134 : /* Extract Datum attribute */
6135 : /* -------------------------------------------------------------------- */
6136 0 : int bIsWGS84 = FALSE;
6137 0 : int bIsNAD83 = FALSE;
6138 : /* int bIsNAD27 = FALSE; */
6139 :
6140 0 : GDALPDFObject *poDatum = poProjDict->Get("Datum");
6141 0 : if (poDatum != nullptr)
6142 : {
6143 0 : if (poDatum->GetType() == PDFObjectType_String)
6144 : {
6145 : /* Using Annex A of
6146 : * http://portal.opengeospatial.org/files/?artifact_id=40537 */
6147 0 : const char *pszDatum = poDatum->GetString().c_str();
6148 0 : CPLDebug("PDF", "Datum = %s", pszDatum);
6149 0 : if (EQUAL(pszDatum, "WE") || EQUAL(pszDatum, "WGE"))
6150 : {
6151 0 : bIsWGS84 = TRUE;
6152 0 : oSRS.SetWellKnownGeogCS("WGS84");
6153 : }
6154 0 : else if (EQUAL(pszDatum, "NAR") || STARTS_WITH_CI(pszDatum, "NAR-"))
6155 : {
6156 0 : bIsNAD83 = TRUE;
6157 0 : oSRS.SetWellKnownGeogCS("NAD83");
6158 : }
6159 0 : else if (EQUAL(pszDatum, "NAS") || STARTS_WITH_CI(pszDatum, "NAS-"))
6160 : {
6161 : /* bIsNAD27 = TRUE; */
6162 0 : oSRS.SetWellKnownGeogCS("NAD27");
6163 : }
6164 0 : else if (EQUAL(pszDatum, "HEN")) /* HERAT North, Afghanistan */
6165 : {
6166 0 : oSRS.SetGeogCS("unknown" /*const char * pszGeogName*/,
6167 : "unknown" /*const char * pszDatumName */,
6168 : "International 1924", 6378388, 297);
6169 0 : oSRS.SetTOWGS84(-333, -222, 114);
6170 : }
6171 0 : else if (EQUAL(pszDatum, "ING-A")) /* INDIAN 1960, Vietnam 16N */
6172 : {
6173 0 : oSRS.importFromEPSG(4131);
6174 : }
6175 0 : else if (EQUAL(pszDatum, "GDS")) /* Geocentric Datum of Australia */
6176 : {
6177 0 : oSRS.importFromEPSG(4283);
6178 : }
6179 0 : else if (STARTS_WITH_CI(pszDatum, "OHA-")) /* Old Hawaiian */
6180 : {
6181 0 : oSRS.importFromEPSG(4135); /* matches OHA-M (Mean) */
6182 0 : if (!EQUAL(pszDatum, "OHA-M"))
6183 : {
6184 0 : CPLError(CE_Warning, CPLE_AppDefined,
6185 : "Using OHA-M (Old Hawaiian Mean) definition for "
6186 : "%s. Potential issue with datum shift parameters",
6187 : pszDatum);
6188 0 : OGR_SRSNode *poNode = oSRS.GetRoot();
6189 0 : int iChild = poNode->FindChild("AUTHORITY");
6190 0 : if (iChild != -1)
6191 0 : poNode->DestroyChild(iChild);
6192 0 : iChild = poNode->FindChild("DATUM");
6193 0 : if (iChild != -1)
6194 : {
6195 0 : poNode = poNode->GetChild(iChild);
6196 0 : iChild = poNode->FindChild("AUTHORITY");
6197 0 : if (iChild != -1)
6198 0 : poNode->DestroyChild(iChild);
6199 : }
6200 : }
6201 : }
6202 : else
6203 : {
6204 0 : CPLError(CE_Warning, CPLE_AppDefined,
6205 : "Unhandled (yet) value for Datum : %s. Defaulting to "
6206 : "WGS84...",
6207 : pszDatum);
6208 0 : oSRS.SetGeogCS("unknown" /*const char * pszGeogName*/,
6209 : "unknown" /*const char * pszDatumName */,
6210 : "unknown", 6378137, 298.257223563);
6211 : }
6212 : }
6213 0 : else if (poDatum->GetType() == PDFObjectType_Dictionary)
6214 : {
6215 0 : GDALPDFDictionary *poDatumDict = poDatum->GetDictionary();
6216 :
6217 0 : GDALPDFObject *poDatumDescription = poDatumDict->Get("Description");
6218 0 : const char *pszDatumDescription = "unknown";
6219 0 : if (poDatumDescription != nullptr &&
6220 0 : poDatumDescription->GetType() == PDFObjectType_String)
6221 0 : pszDatumDescription = poDatumDescription->GetString().c_str();
6222 0 : CPLDebug("PDF", "Datum.Description = %s", pszDatumDescription);
6223 :
6224 0 : GDALPDFObject *poEllipsoid = poDatumDict->Get("Ellipsoid");
6225 0 : if (poEllipsoid == nullptr ||
6226 0 : !(poEllipsoid->GetType() == PDFObjectType_String ||
6227 0 : poEllipsoid->GetType() == PDFObjectType_Dictionary))
6228 : {
6229 0 : CPLError(
6230 : CE_Warning, CPLE_AppDefined,
6231 : "Cannot find Ellipsoid in Datum. Defaulting to WGS84...");
6232 0 : oSRS.SetGeogCS("unknown", pszDatumDescription, "unknown",
6233 : 6378137, 298.257223563);
6234 : }
6235 0 : else if (poEllipsoid->GetType() == PDFObjectType_String)
6236 : {
6237 0 : const char *pszEllipsoid = poEllipsoid->GetString().c_str();
6238 0 : CPLDebug("PDF", "Datum.Ellipsoid = %s", pszEllipsoid);
6239 0 : if (EQUAL(pszEllipsoid, "WE"))
6240 : {
6241 0 : oSRS.SetGeogCS("unknown", pszDatumDescription, "WGS 84",
6242 : 6378137, 298.257223563);
6243 : }
6244 : else
6245 : {
6246 0 : CPLError(CE_Warning, CPLE_AppDefined,
6247 : "Unhandled (yet) value for Ellipsoid : %s. "
6248 : "Defaulting to WGS84...",
6249 : pszEllipsoid);
6250 0 : oSRS.SetGeogCS("unknown", pszDatumDescription, pszEllipsoid,
6251 : 6378137, 298.257223563);
6252 : }
6253 : }
6254 : else // if (poEllipsoid->GetType() == PDFObjectType_Dictionary)
6255 : {
6256 : GDALPDFDictionary *poEllipsoidDict =
6257 0 : poEllipsoid->GetDictionary();
6258 :
6259 : GDALPDFObject *poEllipsoidDescription =
6260 0 : poEllipsoidDict->Get("Description");
6261 0 : const char *pszEllipsoidDescription = "unknown";
6262 0 : if (poEllipsoidDescription != nullptr &&
6263 0 : poEllipsoidDescription->GetType() == PDFObjectType_String)
6264 : pszEllipsoidDescription =
6265 0 : poEllipsoidDescription->GetString().c_str();
6266 0 : CPLDebug("PDF", "Datum.Ellipsoid.Description = %s",
6267 : pszEllipsoidDescription);
6268 :
6269 0 : double dfSemiMajor = Get(poEllipsoidDict, "SemiMajorAxis");
6270 0 : CPLDebug("PDF", "Datum.Ellipsoid.SemiMajorAxis = %.16g",
6271 : dfSemiMajor);
6272 0 : double dfInvFlattening = -1.0;
6273 :
6274 0 : if (poEllipsoidDict->Get("InvFlattening"))
6275 : {
6276 0 : dfInvFlattening = Get(poEllipsoidDict, "InvFlattening");
6277 0 : CPLDebug("PDF", "Datum.Ellipsoid.InvFlattening = %.16g",
6278 : dfInvFlattening);
6279 : }
6280 0 : else if (poEllipsoidDict->Get("SemiMinorAxis"))
6281 : {
6282 0 : double dfSemiMinor = Get(poEllipsoidDict, "SemiMinorAxis");
6283 0 : CPLDebug("PDF", "Datum.Ellipsoid.SemiMinorAxis = %.16g",
6284 : dfSemiMinor);
6285 : dfInvFlattening =
6286 0 : OSRCalcInvFlattening(dfSemiMajor, dfSemiMinor);
6287 : }
6288 :
6289 0 : if (dfSemiMajor != 0.0 && dfInvFlattening != -1.0)
6290 : {
6291 0 : oSRS.SetGeogCS("unknown", pszDatumDescription,
6292 : pszEllipsoidDescription, dfSemiMajor,
6293 : dfInvFlattening);
6294 : }
6295 : else
6296 : {
6297 0 : CPLError(
6298 : CE_Warning, CPLE_AppDefined,
6299 : "Invalid Ellipsoid object. Defaulting to WGS84...");
6300 0 : oSRS.SetGeogCS("unknown", pszDatumDescription,
6301 : pszEllipsoidDescription, 6378137,
6302 : 298.257223563);
6303 : }
6304 : }
6305 :
6306 0 : GDALPDFObject *poTOWGS84 = poDatumDict->Get("ToWGS84");
6307 0 : if (poTOWGS84 != nullptr &&
6308 0 : poTOWGS84->GetType() == PDFObjectType_Dictionary)
6309 : {
6310 0 : GDALPDFDictionary *poTOWGS84Dict = poTOWGS84->GetDictionary();
6311 0 : double dx = Get(poTOWGS84Dict, "dx");
6312 0 : double dy = Get(poTOWGS84Dict, "dy");
6313 0 : double dz = Get(poTOWGS84Dict, "dz");
6314 0 : if (poTOWGS84Dict->Get("rx") && poTOWGS84Dict->Get("ry") &&
6315 0 : poTOWGS84Dict->Get("rz") && poTOWGS84Dict->Get("sf"))
6316 : {
6317 0 : double rx = Get(poTOWGS84Dict, "rx");
6318 0 : double ry = Get(poTOWGS84Dict, "ry");
6319 0 : double rz = Get(poTOWGS84Dict, "rz");
6320 0 : double sf = Get(poTOWGS84Dict, "sf");
6321 0 : oSRS.SetTOWGS84(dx, dy, dz, rx, ry, rz, sf);
6322 : }
6323 : else
6324 : {
6325 0 : oSRS.SetTOWGS84(dx, dy, dz);
6326 : }
6327 : }
6328 : }
6329 : }
6330 :
6331 : /* -------------------------------------------------------------------- */
6332 : /* Extract Hemisphere attribute */
6333 : /* -------------------------------------------------------------------- */
6334 0 : CPLString osHemisphere;
6335 0 : GDALPDFObject *poHemisphere = poProjDict->Get("Hemisphere");
6336 0 : if (poHemisphere != nullptr &&
6337 0 : poHemisphere->GetType() == PDFObjectType_String)
6338 : {
6339 0 : osHemisphere = poHemisphere->GetString();
6340 : }
6341 :
6342 : /* -------------------------------------------------------------------- */
6343 : /* Extract ProjectionType attribute */
6344 : /* -------------------------------------------------------------------- */
6345 0 : GDALPDFObject *poProjectionType = poProjDict->Get("ProjectionType");
6346 0 : if (poProjectionType == nullptr ||
6347 0 : poProjectionType->GetType() != PDFObjectType_String)
6348 : {
6349 0 : CPLError(CE_Failure, CPLE_AppDefined,
6350 : "Cannot find ProjectionType of Projection object");
6351 0 : return FALSE;
6352 : }
6353 0 : CPLString osProjectionType(poProjectionType->GetString());
6354 0 : CPLDebug("PDF", "Projection.ProjectionType = %s", osProjectionType.c_str());
6355 :
6356 : /* Unhandled: NONE, GEODETIC */
6357 :
6358 0 : if (EQUAL(osProjectionType, "GEOGRAPHIC"))
6359 : {
6360 : /* Nothing to do */
6361 : }
6362 :
6363 : /* Unhandled: LOCAL CARTESIAN, MG (MGRS) */
6364 :
6365 0 : else if (EQUAL(osProjectionType, "UT")) /* UTM */
6366 : {
6367 0 : const double dfZone = Get(poProjDict, "Zone");
6368 0 : if (dfZone >= 1 && dfZone <= 60)
6369 : {
6370 0 : int nZone = static_cast<int>(dfZone);
6371 0 : int bNorth = EQUAL(osHemisphere, "N");
6372 0 : if (bIsWGS84)
6373 0 : oSRS.importFromEPSG(((bNorth) ? 32600 : 32700) + nZone);
6374 : else
6375 0 : oSRS.SetUTM(nZone, bNorth);
6376 : }
6377 : }
6378 :
6379 0 : else if (EQUAL(osProjectionType,
6380 : "UP")) /* Universal Polar Stereographic (UPS) */
6381 : {
6382 0 : int bNorth = EQUAL(osHemisphere, "N");
6383 0 : if (bIsWGS84)
6384 0 : oSRS.importFromEPSG((bNorth) ? 32661 : 32761);
6385 : else
6386 0 : oSRS.SetPS((bNorth) ? 90 : -90, 0, 0.994, 200000, 200000);
6387 : }
6388 :
6389 0 : else if (EQUAL(osProjectionType, "SPCS")) /* State Plane */
6390 : {
6391 0 : const double dfZone = Get(poProjDict, "Zone");
6392 0 : if (dfZone >= 0 && dfZone <= INT_MAX)
6393 : {
6394 0 : int nZone = static_cast<int>(dfZone);
6395 0 : oSRS.SetStatePlane(nZone, bIsNAD83);
6396 : }
6397 : }
6398 :
6399 0 : else if (EQUAL(osProjectionType, "AC")) /* Albers Equal Area Conic */
6400 : {
6401 0 : double dfStdP1 = Get(poProjDict, "StandardParallelOne");
6402 0 : double dfStdP2 = Get(poProjDict, "StandardParallelTwo");
6403 0 : double dfCenterLat = Get(poProjDict, "OriginLatitude");
6404 0 : double dfCenterLong = Get(poProjDict, "CentralMeridian");
6405 0 : double dfFalseEasting = Get(poProjDict, "FalseEasting");
6406 0 : double dfFalseNorthing = Get(poProjDict, "FalseNorthing");
6407 0 : oSRS.SetACEA(dfStdP1, dfStdP2, dfCenterLat, dfCenterLong,
6408 : dfFalseEasting, dfFalseNorthing);
6409 : }
6410 :
6411 0 : else if (EQUAL(osProjectionType, "AL")) /* Azimuthal Equidistant */
6412 : {
6413 0 : double dfCenterLat = Get(poProjDict, "OriginLatitude");
6414 0 : double dfCenterLong = Get(poProjDict, "CentralMeridian");
6415 0 : double dfFalseEasting = Get(poProjDict, "FalseEasting");
6416 0 : double dfFalseNorthing = Get(poProjDict, "FalseNorthing");
6417 0 : oSRS.SetAE(dfCenterLat, dfCenterLong, dfFalseEasting, dfFalseNorthing);
6418 : }
6419 :
6420 0 : else if (EQUAL(osProjectionType, "BF")) /* Bonne */
6421 : {
6422 0 : double dfStdP1 = Get(poProjDict, "OriginLatitude");
6423 0 : double dfCentralMeridian = Get(poProjDict, "CentralMeridian");
6424 0 : double dfFalseEasting = Get(poProjDict, "FalseEasting");
6425 0 : double dfFalseNorthing = Get(poProjDict, "FalseNorthing");
6426 0 : oSRS.SetBonne(dfStdP1, dfCentralMeridian, dfFalseEasting,
6427 : dfFalseNorthing);
6428 : }
6429 :
6430 0 : else if (EQUAL(osProjectionType, "CS")) /* Cassini */
6431 : {
6432 0 : double dfCenterLat = Get(poProjDict, "OriginLatitude");
6433 0 : double dfCenterLong = Get(poProjDict, "CentralMeridian");
6434 0 : double dfFalseEasting = Get(poProjDict, "FalseEasting");
6435 0 : double dfFalseNorthing = Get(poProjDict, "FalseNorthing");
6436 0 : oSRS.SetCS(dfCenterLat, dfCenterLong, dfFalseEasting, dfFalseNorthing);
6437 : }
6438 :
6439 0 : else if (EQUAL(osProjectionType, "LI")) /* Cylindrical Equal Area */
6440 : {
6441 0 : double dfStdP1 = Get(poProjDict, "OriginLatitude");
6442 0 : double dfCentralMeridian = Get(poProjDict, "CentralMeridian");
6443 0 : double dfFalseEasting = Get(poProjDict, "FalseEasting");
6444 0 : double dfFalseNorthing = Get(poProjDict, "FalseNorthing");
6445 0 : oSRS.SetCEA(dfStdP1, dfCentralMeridian, dfFalseEasting,
6446 : dfFalseNorthing);
6447 : }
6448 :
6449 0 : else if (EQUAL(osProjectionType, "EF")) /* Eckert IV */
6450 : {
6451 0 : double dfCentralMeridian = Get(poProjDict, "CentralMeridian");
6452 0 : double dfFalseEasting = Get(poProjDict, "FalseEasting");
6453 0 : double dfFalseNorthing = Get(poProjDict, "FalseNorthing");
6454 0 : oSRS.SetEckertIV(dfCentralMeridian, dfFalseEasting, dfFalseNorthing);
6455 : }
6456 :
6457 0 : else if (EQUAL(osProjectionType, "ED")) /* Eckert VI */
6458 : {
6459 0 : double dfCentralMeridian = Get(poProjDict, "CentralMeridian");
6460 0 : double dfFalseEasting = Get(poProjDict, "FalseEasting");
6461 0 : double dfFalseNorthing = Get(poProjDict, "FalseNorthing");
6462 0 : oSRS.SetEckertVI(dfCentralMeridian, dfFalseEasting, dfFalseNorthing);
6463 : }
6464 :
6465 0 : else if (EQUAL(osProjectionType, "CP")) /* Equidistant Cylindrical */
6466 : {
6467 0 : double dfCenterLat = Get(poProjDict, "StandardParallel");
6468 0 : double dfCenterLong = Get(poProjDict, "CentralMeridian");
6469 0 : double dfFalseEasting = Get(poProjDict, "FalseEasting");
6470 0 : double dfFalseNorthing = Get(poProjDict, "FalseNorthing");
6471 0 : oSRS.SetEquirectangular(dfCenterLat, dfCenterLong, dfFalseEasting,
6472 : dfFalseNorthing);
6473 : }
6474 :
6475 0 : else if (EQUAL(osProjectionType, "GN")) /* Gnomonic */
6476 : {
6477 0 : double dfCenterLat = Get(poProjDict, "OriginLatitude");
6478 0 : double dfCenterLong = Get(poProjDict, "CentralMeridian");
6479 0 : double dfFalseEasting = Get(poProjDict, "FalseEasting");
6480 0 : double dfFalseNorthing = Get(poProjDict, "FalseNorthing");
6481 0 : oSRS.SetGnomonic(dfCenterLat, dfCenterLong, dfFalseEasting,
6482 : dfFalseNorthing);
6483 : }
6484 :
6485 0 : else if (EQUAL(osProjectionType, "LE")) /* Lambert Conformal Conic */
6486 : {
6487 0 : double dfStdP1 = Get(poProjDict, "StandardParallelOne");
6488 0 : double dfStdP2 = Get(poProjDict, "StandardParallelTwo");
6489 0 : double dfCenterLat = Get(poProjDict, "OriginLatitude");
6490 0 : double dfCenterLong = Get(poProjDict, "CentralMeridian");
6491 0 : double dfFalseEasting = Get(poProjDict, "FalseEasting");
6492 0 : double dfFalseNorthing = Get(poProjDict, "FalseNorthing");
6493 0 : oSRS.SetLCC(dfStdP1, dfStdP2, dfCenterLat, dfCenterLong, dfFalseEasting,
6494 : dfFalseNorthing);
6495 : }
6496 :
6497 0 : else if (EQUAL(osProjectionType, "MC")) /* Mercator */
6498 : {
6499 : #ifdef not_supported
6500 : if (poProjDict->Get("StandardParallelOne") == nullptr)
6501 : #endif
6502 : {
6503 0 : double dfCenterLat = Get(poProjDict, "OriginLatitude");
6504 0 : double dfCenterLong = Get(poProjDict, "CentralMeridian");
6505 0 : double dfScale = Get(poProjDict, "ScaleFactor");
6506 0 : double dfFalseEasting = Get(poProjDict, "FalseEasting");
6507 0 : double dfFalseNorthing = Get(poProjDict, "FalseNorthing");
6508 0 : oSRS.SetMercator(dfCenterLat, dfCenterLong, dfScale, dfFalseEasting,
6509 : dfFalseNorthing);
6510 : }
6511 : #ifdef not_supported
6512 : else
6513 : {
6514 : double dfStdP1 = Get(poProjDict, "StandardParallelOne");
6515 : double dfCenterLat = poProjDict->Get("OriginLatitude")
6516 : ? Get(poProjDict, "OriginLatitude")
6517 : : 0;
6518 : double dfCenterLong = Get(poProjDict, "CentralMeridian");
6519 : double dfFalseEasting = Get(poProjDict, "FalseEasting");
6520 : double dfFalseNorthing = Get(poProjDict, "FalseNorthing");
6521 : oSRS.SetMercator2SP(dfStdP1, dfCenterLat, dfCenterLong,
6522 : dfFalseEasting, dfFalseNorthing);
6523 : }
6524 : #endif
6525 : }
6526 :
6527 0 : else if (EQUAL(osProjectionType, "MH")) /* Miller Cylindrical */
6528 : {
6529 0 : double dfCenterLat = 0 /* ? */;
6530 0 : double dfCenterLong = Get(poProjDict, "CentralMeridian");
6531 0 : double dfFalseEasting = Get(poProjDict, "FalseEasting");
6532 0 : double dfFalseNorthing = Get(poProjDict, "FalseNorthing");
6533 0 : oSRS.SetMC(dfCenterLat, dfCenterLong, dfFalseEasting, dfFalseNorthing);
6534 : }
6535 :
6536 0 : else if (EQUAL(osProjectionType, "MP")) /* Mollweide */
6537 : {
6538 0 : double dfCentralMeridian = Get(poProjDict, "CentralMeridian");
6539 0 : double dfFalseEasting = Get(poProjDict, "FalseEasting");
6540 0 : double dfFalseNorthing = Get(poProjDict, "FalseNorthing");
6541 0 : oSRS.SetMollweide(dfCentralMeridian, dfFalseEasting, dfFalseNorthing);
6542 : }
6543 :
6544 : /* Unhandled: "NY" : Ney's (Modified Lambert Conformal Conic) */
6545 :
6546 0 : else if (EQUAL(osProjectionType, "NT")) /* New Zealand Map Grid */
6547 : {
6548 : /* No parameter specified in the PDF, so let's take the ones of
6549 : * EPSG:27200 */
6550 0 : double dfCenterLat = -41;
6551 0 : double dfCenterLong = 173;
6552 0 : double dfFalseEasting = 2510000;
6553 0 : double dfFalseNorthing = 6023150;
6554 0 : oSRS.SetNZMG(dfCenterLat, dfCenterLong, dfFalseEasting,
6555 : dfFalseNorthing);
6556 : }
6557 :
6558 0 : else if (EQUAL(osProjectionType, "OC")) /* Oblique Mercator */
6559 : {
6560 0 : double dfCenterLat = Get(poProjDict, "OriginLatitude");
6561 0 : double dfLat1 = Get(poProjDict, "LatitudeOne");
6562 0 : double dfLong1 = Get(poProjDict, "LongitudeOne");
6563 0 : double dfLat2 = Get(poProjDict, "LatitudeTwo");
6564 0 : double dfLong2 = Get(poProjDict, "LongitudeTwo");
6565 0 : double dfScale = Get(poProjDict, "ScaleFactor");
6566 0 : double dfFalseEasting = Get(poProjDict, "FalseEasting");
6567 0 : double dfFalseNorthing = Get(poProjDict, "FalseNorthing");
6568 0 : oSRS.SetHOM2PNO(dfCenterLat, dfLat1, dfLong1, dfLat2, dfLong2, dfScale,
6569 : dfFalseEasting, dfFalseNorthing);
6570 : }
6571 :
6572 0 : else if (EQUAL(osProjectionType, "OD")) /* Orthographic */
6573 : {
6574 0 : double dfCenterLat = Get(poProjDict, "OriginLatitude");
6575 0 : double dfCenterLong = Get(poProjDict, "CentralMeridian");
6576 0 : double dfFalseEasting = Get(poProjDict, "FalseEasting");
6577 0 : double dfFalseNorthing = Get(poProjDict, "FalseNorthing");
6578 0 : oSRS.SetOrthographic(dfCenterLat, dfCenterLong, dfFalseEasting,
6579 : dfFalseNorthing);
6580 : }
6581 :
6582 0 : else if (EQUAL(osProjectionType, "PG")) /* Polar Stereographic */
6583 : {
6584 0 : double dfCenterLat = Get(poProjDict, "LatitudeTrueScale");
6585 0 : double dfCenterLong = Get(poProjDict, "LongitudeDownFromPole");
6586 0 : double dfScale = 1.0;
6587 0 : double dfFalseEasting = Get(poProjDict, "FalseEasting");
6588 0 : double dfFalseNorthing = Get(poProjDict, "FalseNorthing");
6589 0 : oSRS.SetPS(dfCenterLat, dfCenterLong, dfScale, dfFalseEasting,
6590 : dfFalseNorthing);
6591 : }
6592 :
6593 0 : else if (EQUAL(osProjectionType, "PH")) /* Polyconic */
6594 : {
6595 0 : double dfCenterLat = Get(poProjDict, "OriginLatitude");
6596 0 : double dfCenterLong = Get(poProjDict, "CentralMeridian");
6597 0 : double dfFalseEasting = Get(poProjDict, "FalseEasting");
6598 0 : double dfFalseNorthing = Get(poProjDict, "FalseNorthing");
6599 0 : oSRS.SetPolyconic(dfCenterLat, dfCenterLong, dfFalseEasting,
6600 : dfFalseNorthing);
6601 : }
6602 :
6603 0 : else if (EQUAL(osProjectionType, "SA")) /* Sinusoidal */
6604 : {
6605 0 : double dfCenterLong = Get(poProjDict, "CentralMeridian");
6606 0 : double dfFalseEasting = Get(poProjDict, "FalseEasting");
6607 0 : double dfFalseNorthing = Get(poProjDict, "FalseNorthing");
6608 0 : oSRS.SetSinusoidal(dfCenterLong, dfFalseEasting, dfFalseNorthing);
6609 : }
6610 :
6611 0 : else if (EQUAL(osProjectionType, "SD")) /* Stereographic */
6612 : {
6613 0 : double dfCenterLat = Get(poProjDict, "OriginLatitude");
6614 0 : double dfCenterLong = Get(poProjDict, "CentralMeridian");
6615 0 : double dfScale = 1.0;
6616 0 : double dfFalseEasting = Get(poProjDict, "FalseEasting");
6617 0 : double dfFalseNorthing = Get(poProjDict, "FalseNorthing");
6618 0 : oSRS.SetStereographic(dfCenterLat, dfCenterLong, dfScale,
6619 : dfFalseEasting, dfFalseNorthing);
6620 : }
6621 :
6622 0 : else if (EQUAL(osProjectionType, "TC")) /* Transverse Mercator */
6623 : {
6624 0 : double dfCenterLat = Get(poProjDict, "OriginLatitude");
6625 0 : double dfCenterLong = Get(poProjDict, "CentralMeridian");
6626 0 : double dfScale = Get(poProjDict, "ScaleFactor");
6627 0 : double dfFalseEasting = Get(poProjDict, "FalseEasting");
6628 0 : double dfFalseNorthing = Get(poProjDict, "FalseNorthing");
6629 0 : if (dfCenterLat == 0.0 && dfScale == 0.9996 && dfCenterLong >= -180 &&
6630 0 : dfCenterLong <= 180 && dfFalseEasting == 500000 &&
6631 0 : (dfFalseNorthing == 0.0 || dfFalseNorthing == 10000000.0))
6632 : {
6633 0 : const int nZone =
6634 0 : static_cast<int>(floor((dfCenterLong + 180.0) / 6.0) + 1);
6635 0 : int bNorth = dfFalseNorthing == 0;
6636 0 : if (bIsWGS84)
6637 0 : oSRS.importFromEPSG(((bNorth) ? 32600 : 32700) + nZone);
6638 0 : else if (bIsNAD83 && bNorth)
6639 0 : oSRS.importFromEPSG(26900 + nZone);
6640 : else
6641 0 : oSRS.SetUTM(nZone, bNorth);
6642 : }
6643 : else
6644 : {
6645 0 : oSRS.SetTM(dfCenterLat, dfCenterLong, dfScale, dfFalseEasting,
6646 : dfFalseNorthing);
6647 : }
6648 : }
6649 :
6650 : /* Unhandled TX : Transverse Cylindrical Equal Area */
6651 :
6652 0 : else if (EQUAL(osProjectionType, "VA")) /* Van der Grinten */
6653 : {
6654 0 : double dfCenterLong = Get(poProjDict, "CentralMeridian");
6655 0 : double dfFalseEasting = Get(poProjDict, "FalseEasting");
6656 0 : double dfFalseNorthing = Get(poProjDict, "FalseNorthing");
6657 0 : oSRS.SetVDG(dfCenterLong, dfFalseEasting, dfFalseNorthing);
6658 : }
6659 :
6660 : else
6661 : {
6662 0 : CPLError(CE_Failure, CPLE_AppDefined,
6663 : "Unhandled (yet) value for ProjectionType : %s",
6664 : osProjectionType.c_str());
6665 0 : return FALSE;
6666 : }
6667 :
6668 : /* -------------------------------------------------------------------- */
6669 : /* Extract Units attribute */
6670 : /* -------------------------------------------------------------------- */
6671 0 : CPLString osUnits;
6672 0 : GDALPDFObject *poUnits = poProjDict->Get("Units");
6673 0 : if (poUnits != nullptr && poUnits->GetType() == PDFObjectType_String &&
6674 0 : !EQUAL(osProjectionType, "GEOGRAPHIC"))
6675 : {
6676 0 : osUnits = poUnits->GetString();
6677 0 : CPLDebug("PDF", "Projection.Units = %s", osUnits.c_str());
6678 :
6679 : // This is super weird. The false easting/northing of the SRS
6680 : // are expressed in the unit, but the geotransform is expressed in
6681 : // meters. Hence this hack to have an equivalent SRS definition, but
6682 : // with linear units converted in meters.
6683 0 : if (EQUAL(osUnits, "M"))
6684 0 : oSRS.SetLinearUnits("Meter", 1.0);
6685 0 : else if (EQUAL(osUnits, "FT"))
6686 : {
6687 0 : oSRS.SetLinearUnits("foot", 0.3048);
6688 0 : oSRS.SetLinearUnitsAndUpdateParameters("Meter", 1.0);
6689 : }
6690 0 : else if (EQUAL(osUnits, "USSF"))
6691 : {
6692 0 : oSRS.SetLinearUnits(SRS_UL_US_FOOT, CPLAtof(SRS_UL_US_FOOT_CONV));
6693 0 : oSRS.SetLinearUnitsAndUpdateParameters("Meter", 1.0);
6694 : }
6695 : else
6696 0 : CPLError(CE_Warning, CPLE_AppDefined, "Unhandled unit: %s",
6697 : osUnits.c_str());
6698 : }
6699 :
6700 : /* -------------------------------------------------------------------- */
6701 : /* Export SpatialRef */
6702 : /* -------------------------------------------------------------------- */
6703 0 : m_oSRS = std::move(oSRS);
6704 :
6705 0 : return TRUE;
6706 : }
6707 :
6708 : /************************************************************************/
6709 : /* ParseVP() */
6710 : /************************************************************************/
6711 :
6712 280 : int PDFDataset::ParseVP(GDALPDFObject *poVP, double dfMediaBoxWidth,
6713 : double dfMediaBoxHeight)
6714 : {
6715 : int i;
6716 :
6717 280 : if (poVP->GetType() != PDFObjectType_Array)
6718 0 : return FALSE;
6719 :
6720 280 : GDALPDFArray *poVPArray = poVP->GetArray();
6721 :
6722 280 : int nLength = poVPArray->GetLength();
6723 280 : CPLDebug("PDF", "VP length = %d", nLength);
6724 280 : if (nLength < 1)
6725 0 : return FALSE;
6726 :
6727 : /* -------------------------------------------------------------------- */
6728 : /* Find the largest BBox */
6729 : /* -------------------------------------------------------------------- */
6730 : const char *pszNeatlineToSelect =
6731 280 : GetOption(papszOpenOptions, "NEATLINE", "Map Layers");
6732 :
6733 280 : int iLargest = 0;
6734 280 : int iRequestedVP = -1;
6735 280 : double dfLargestArea = 0;
6736 :
6737 576 : for (i = 0; i < nLength; i++)
6738 : {
6739 296 : GDALPDFObject *poVPElt = poVPArray->Get(i);
6740 592 : if (poVPElt == nullptr ||
6741 296 : poVPElt->GetType() != PDFObjectType_Dictionary)
6742 : {
6743 0 : return FALSE;
6744 : }
6745 :
6746 296 : GDALPDFDictionary *poVPEltDict = poVPElt->GetDictionary();
6747 :
6748 296 : GDALPDFObject *poMeasure = poVPEltDict->Get("Measure");
6749 592 : if (poMeasure == nullptr ||
6750 296 : poMeasure->GetType() != PDFObjectType_Dictionary)
6751 : {
6752 0 : continue;
6753 : }
6754 : /* --------------------------------------------------------------------
6755 : */
6756 : /* Extract Subtype attribute */
6757 : /* --------------------------------------------------------------------
6758 : */
6759 296 : GDALPDFDictionary *poMeasureDict = poMeasure->GetDictionary();
6760 296 : GDALPDFObject *poSubtype = poMeasureDict->Get("Subtype");
6761 296 : if (poSubtype == nullptr || poSubtype->GetType() != PDFObjectType_Name)
6762 : {
6763 0 : continue;
6764 : }
6765 :
6766 296 : CPLDebug("PDF", "Subtype = %s", poSubtype->GetName().c_str());
6767 296 : if (!EQUAL(poSubtype->GetName().c_str(), "GEO"))
6768 : {
6769 0 : continue;
6770 : }
6771 :
6772 296 : GDALPDFObject *poName = poVPEltDict->Get("Name");
6773 296 : if (poName != nullptr && poName->GetType() == PDFObjectType_String)
6774 : {
6775 293 : CPLDebug("PDF", "Name = %s", poName->GetString().c_str());
6776 293 : if (EQUAL(poName->GetString().c_str(), pszNeatlineToSelect))
6777 : {
6778 0 : iRequestedVP = i;
6779 : }
6780 : }
6781 :
6782 296 : GDALPDFObject *poBBox = poVPEltDict->Get("BBox");
6783 296 : if (poBBox == nullptr || poBBox->GetType() != PDFObjectType_Array)
6784 : {
6785 0 : CPLError(CE_Failure, CPLE_AppDefined, "Cannot find Bbox object");
6786 0 : return FALSE;
6787 : }
6788 :
6789 296 : int nBboxLength = poBBox->GetArray()->GetLength();
6790 296 : if (nBboxLength != 4)
6791 : {
6792 0 : CPLError(CE_Failure, CPLE_AppDefined,
6793 : "Invalid length for Bbox object");
6794 0 : return FALSE;
6795 : }
6796 :
6797 : double adfBBox[4];
6798 296 : adfBBox[0] = Get(poBBox, 0);
6799 296 : adfBBox[1] = Get(poBBox, 1);
6800 296 : adfBBox[2] = Get(poBBox, 2);
6801 296 : adfBBox[3] = Get(poBBox, 3);
6802 296 : double dfArea =
6803 296 : fabs(adfBBox[2] - adfBBox[0]) * fabs(adfBBox[3] - adfBBox[1]);
6804 296 : if (dfArea > dfLargestArea)
6805 : {
6806 280 : iLargest = i;
6807 280 : dfLargestArea = dfArea;
6808 : }
6809 : }
6810 :
6811 280 : if (nLength > 1)
6812 : {
6813 16 : CPLDebug("PDF", "Largest BBox in VP array is element %d", iLargest);
6814 : }
6815 :
6816 280 : GDALPDFObject *poVPElt = nullptr;
6817 :
6818 280 : if (iRequestedVP > -1)
6819 : {
6820 0 : CPLDebug("PDF", "Requested NEATLINE BBox in VP array is element %d",
6821 : iRequestedVP);
6822 0 : poVPElt = poVPArray->Get(iRequestedVP);
6823 : }
6824 : else
6825 : {
6826 280 : poVPElt = poVPArray->Get(iLargest);
6827 : }
6828 :
6829 280 : if (poVPElt == nullptr || poVPElt->GetType() != PDFObjectType_Dictionary)
6830 : {
6831 0 : return FALSE;
6832 : }
6833 :
6834 280 : GDALPDFDictionary *poVPEltDict = poVPElt->GetDictionary();
6835 :
6836 280 : GDALPDFObject *poBBox = poVPEltDict->Get("BBox");
6837 280 : if (poBBox == nullptr || poBBox->GetType() != PDFObjectType_Array)
6838 : {
6839 0 : CPLError(CE_Failure, CPLE_AppDefined, "Cannot find Bbox object");
6840 0 : return FALSE;
6841 : }
6842 :
6843 280 : int nBboxLength = poBBox->GetArray()->GetLength();
6844 280 : if (nBboxLength != 4)
6845 : {
6846 0 : CPLError(CE_Failure, CPLE_AppDefined, "Invalid length for Bbox object");
6847 0 : return FALSE;
6848 : }
6849 :
6850 280 : double dfULX = Get(poBBox, 0);
6851 280 : double dfULY = dfMediaBoxHeight - Get(poBBox, 1);
6852 280 : double dfLRX = Get(poBBox, 2);
6853 280 : double dfLRY = dfMediaBoxHeight - Get(poBBox, 3);
6854 :
6855 : /* -------------------------------------------------------------------- */
6856 : /* Extract Measure attribute */
6857 : /* -------------------------------------------------------------------- */
6858 280 : GDALPDFObject *poMeasure = poVPEltDict->Get("Measure");
6859 560 : if (poMeasure == nullptr ||
6860 280 : poMeasure->GetType() != PDFObjectType_Dictionary)
6861 : {
6862 0 : CPLError(CE_Failure, CPLE_AppDefined, "Cannot find Measure object");
6863 0 : return FALSE;
6864 : }
6865 :
6866 280 : int bRet = ParseMeasure(poMeasure, dfMediaBoxWidth, dfMediaBoxHeight, dfULX,
6867 : dfULY, dfLRX, dfLRY);
6868 :
6869 : /* -------------------------------------------------------------------- */
6870 : /* Extract PointData attribute */
6871 : /* -------------------------------------------------------------------- */
6872 280 : GDALPDFObject *poPointData = poVPEltDict->Get("PtData");
6873 280 : if (poPointData != nullptr &&
6874 0 : poPointData->GetType() == PDFObjectType_Dictionary)
6875 : {
6876 0 : CPLDebug("PDF", "Found PointData");
6877 : }
6878 :
6879 280 : return bRet;
6880 : }
6881 :
6882 : /************************************************************************/
6883 : /* ParseMeasure() */
6884 : /************************************************************************/
6885 :
6886 280 : int PDFDataset::ParseMeasure(GDALPDFObject *poMeasure, double dfMediaBoxWidth,
6887 : double dfMediaBoxHeight, double dfULX,
6888 : double dfULY, double dfLRX, double dfLRY)
6889 : {
6890 280 : GDALPDFDictionary *poMeasureDict = poMeasure->GetDictionary();
6891 :
6892 : /* -------------------------------------------------------------------- */
6893 : /* Extract Subtype attribute */
6894 : /* -------------------------------------------------------------------- */
6895 280 : GDALPDFObject *poSubtype = poMeasureDict->Get("Subtype");
6896 280 : if (poSubtype == nullptr || poSubtype->GetType() != PDFObjectType_Name)
6897 : {
6898 0 : CPLError(CE_Failure, CPLE_AppDefined, "Cannot find Subtype object");
6899 0 : return FALSE;
6900 : }
6901 :
6902 280 : CPLDebug("PDF", "Subtype = %s", poSubtype->GetName().c_str());
6903 280 : if (!EQUAL(poSubtype->GetName().c_str(), "GEO"))
6904 0 : return FALSE;
6905 :
6906 : /* -------------------------------------------------------------------- */
6907 : /* Extract Bounds attribute (optional) */
6908 : /* -------------------------------------------------------------------- */
6909 :
6910 : /* http://acrobatusers.com/sites/default/files/gallery_pictures/SEVERODVINSK.pdf
6911 : */
6912 : /* has lgit:LPTS, lgit:GPTS and lgit:Bounds that have more precision than */
6913 : /* LPTS, GPTS and Bounds. Use those ones */
6914 :
6915 280 : GDALPDFObject *poBounds = poMeasureDict->Get("lgit:Bounds");
6916 280 : if (poBounds != nullptr && poBounds->GetType() == PDFObjectType_Array)
6917 : {
6918 0 : CPLDebug("PDF", "Using lgit:Bounds");
6919 : }
6920 557 : else if ((poBounds = poMeasureDict->Get("Bounds")) == nullptr ||
6921 277 : poBounds->GetType() != PDFObjectType_Array)
6922 : {
6923 3 : poBounds = nullptr;
6924 : }
6925 :
6926 280 : if (poBounds != nullptr)
6927 : {
6928 277 : int nBoundsLength = poBounds->GetArray()->GetLength();
6929 277 : if (nBoundsLength == 8)
6930 : {
6931 : double adfBounds[8];
6932 2331 : for (int i = 0; i < 8; i++)
6933 : {
6934 2072 : adfBounds[i] = Get(poBounds, i);
6935 2072 : CPLDebug("PDF", "Bounds[%d] = %f", i, adfBounds[i]);
6936 : }
6937 :
6938 : // TODO we should use it to restrict the neatline but
6939 : // I have yet to set a sample where bounds are not the four
6940 : // corners of the unit square.
6941 : }
6942 : }
6943 :
6944 : /* -------------------------------------------------------------------- */
6945 : /* Extract GPTS attribute */
6946 : /* -------------------------------------------------------------------- */
6947 280 : GDALPDFObject *poGPTS = poMeasureDict->Get("lgit:GPTS");
6948 280 : if (poGPTS != nullptr && poGPTS->GetType() == PDFObjectType_Array)
6949 : {
6950 0 : CPLDebug("PDF", "Using lgit:GPTS");
6951 : }
6952 560 : else if ((poGPTS = poMeasureDict->Get("GPTS")) == nullptr ||
6953 280 : poGPTS->GetType() != PDFObjectType_Array)
6954 : {
6955 0 : CPLError(CE_Failure, CPLE_AppDefined, "Cannot find GPTS object");
6956 0 : return FALSE;
6957 : }
6958 :
6959 280 : int nGPTSLength = poGPTS->GetArray()->GetLength();
6960 280 : if ((nGPTSLength % 2) != 0 || nGPTSLength < 6)
6961 : {
6962 0 : CPLError(CE_Failure, CPLE_AppDefined, "Invalid length for GPTS object");
6963 0 : return FALSE;
6964 : }
6965 :
6966 560 : std::vector<double> adfGPTS(nGPTSLength);
6967 2520 : for (int i = 0; i < nGPTSLength; i++)
6968 : {
6969 2240 : adfGPTS[i] = Get(poGPTS, i);
6970 2240 : CPLDebug("PDF", "GPTS[%d] = %.18f", i, adfGPTS[i]);
6971 : }
6972 :
6973 : /* -------------------------------------------------------------------- */
6974 : /* Extract LPTS attribute */
6975 : /* -------------------------------------------------------------------- */
6976 280 : GDALPDFObject *poLPTS = poMeasureDict->Get("lgit:LPTS");
6977 280 : if (poLPTS != nullptr && poLPTS->GetType() == PDFObjectType_Array)
6978 : {
6979 0 : CPLDebug("PDF", "Using lgit:LPTS");
6980 : }
6981 560 : else if ((poLPTS = poMeasureDict->Get("LPTS")) == nullptr ||
6982 280 : poLPTS->GetType() != PDFObjectType_Array)
6983 : {
6984 0 : CPLError(CE_Failure, CPLE_AppDefined, "Cannot find LPTS object");
6985 0 : return FALSE;
6986 : }
6987 :
6988 280 : int nLPTSLength = poLPTS->GetArray()->GetLength();
6989 280 : if (nLPTSLength != nGPTSLength)
6990 : {
6991 0 : CPLError(CE_Failure, CPLE_AppDefined, "Invalid length for LPTS object");
6992 0 : return FALSE;
6993 : }
6994 :
6995 560 : std::vector<double> adfLPTS(nLPTSLength);
6996 2520 : for (int i = 0; i < nLPTSLength; i++)
6997 : {
6998 2240 : adfLPTS[i] = Get(poLPTS, i);
6999 2240 : CPLDebug("PDF", "LPTS[%d] = %f", i, adfLPTS[i]);
7000 : }
7001 :
7002 : /* -------------------------------------------------------------------- */
7003 : /* Extract GCS attribute */
7004 : /* -------------------------------------------------------------------- */
7005 280 : GDALPDFObject *poGCS = poMeasureDict->Get("GCS");
7006 280 : if (poGCS == nullptr || poGCS->GetType() != PDFObjectType_Dictionary)
7007 : {
7008 0 : CPLError(CE_Failure, CPLE_AppDefined, "Cannot find GCS object");
7009 0 : return FALSE;
7010 : }
7011 :
7012 280 : GDALPDFDictionary *poGCSDict = poGCS->GetDictionary();
7013 :
7014 : /* -------------------------------------------------------------------- */
7015 : /* Extract GCS.Type attribute */
7016 : /* -------------------------------------------------------------------- */
7017 280 : GDALPDFObject *poGCSType = poGCSDict->Get("Type");
7018 280 : if (poGCSType == nullptr || poGCSType->GetType() != PDFObjectType_Name)
7019 : {
7020 0 : CPLError(CE_Failure, CPLE_AppDefined, "Cannot find GCS.Type object");
7021 0 : return FALSE;
7022 : }
7023 :
7024 280 : CPLDebug("PDF", "GCS.Type = %s", poGCSType->GetName().c_str());
7025 :
7026 : /* -------------------------------------------------------------------- */
7027 : /* Extract EPSG attribute */
7028 : /* -------------------------------------------------------------------- */
7029 280 : GDALPDFObject *poEPSG = poGCSDict->Get("EPSG");
7030 280 : int nEPSGCode = 0;
7031 280 : if (poEPSG != nullptr && poEPSG->GetType() == PDFObjectType_Int)
7032 : {
7033 237 : nEPSGCode = poEPSG->GetInt();
7034 237 : CPLDebug("PDF", "GCS.EPSG = %d", nEPSGCode);
7035 : }
7036 :
7037 : /* -------------------------------------------------------------------- */
7038 : /* Extract GCS.WKT attribute */
7039 : /* -------------------------------------------------------------------- */
7040 280 : GDALPDFObject *poGCSWKT = poGCSDict->Get("WKT");
7041 280 : if (poGCSWKT != nullptr && poGCSWKT->GetType() != PDFObjectType_String)
7042 : {
7043 0 : poGCSWKT = nullptr;
7044 : }
7045 :
7046 280 : if (poGCSWKT != nullptr)
7047 277 : CPLDebug("PDF", "GCS.WKT = %s", poGCSWKT->GetString().c_str());
7048 :
7049 280 : if (nEPSGCode <= 0 && poGCSWKT == nullptr)
7050 : {
7051 0 : CPLError(CE_Failure, CPLE_AppDefined,
7052 : "Cannot find GCS.WKT or GCS.EPSG objects");
7053 0 : return FALSE;
7054 : }
7055 :
7056 280 : if (poGCSWKT != nullptr)
7057 : {
7058 277 : m_oSRS.importFromWkt(poGCSWKT->GetString().c_str());
7059 : }
7060 :
7061 280 : bool bSRSOK = false;
7062 280 : if (nEPSGCode != 0)
7063 : {
7064 : // At time of writing EPSG CRS codes are <= 32767.
7065 : // The usual practice is that codes >= 100000 are in the ESRI namespace
7066 : // instead
7067 237 : if (nEPSGCode >= 100000)
7068 : {
7069 4 : CPLErrorHandlerPusher oHandler(CPLQuietErrorHandler);
7070 4 : OGRSpatialReference oSRS_ESRI;
7071 2 : oSRS_ESRI.SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER);
7072 2 : if (oSRS_ESRI.SetFromUserInput(CPLSPrintf("ESRI:%d", nEPSGCode)) ==
7073 : OGRERR_NONE)
7074 : {
7075 2 : bSRSOK = true;
7076 :
7077 : // Check consistency of ESRI:xxxx and WKT definitions
7078 2 : if (poGCSWKT != nullptr)
7079 : {
7080 3 : if (!m_oSRS.GetName() ||
7081 1 : (!EQUAL(oSRS_ESRI.GetName(), m_oSRS.GetName()) &&
7082 0 : !oSRS_ESRI.IsSame(&m_oSRS)))
7083 : {
7084 1 : CPLDebug("PDF",
7085 : "Definition from ESRI:%d and WKT=%s do not "
7086 : "match. Using WKT string",
7087 1 : nEPSGCode, poGCSWKT->GetString().c_str());
7088 1 : bSRSOK = false;
7089 : }
7090 : }
7091 2 : if (bSRSOK)
7092 : {
7093 1 : m_oSRS = std::move(oSRS_ESRI);
7094 : }
7095 : }
7096 : }
7097 235 : else if (m_oSRS.importFromEPSG(nEPSGCode) == OGRERR_NONE)
7098 : {
7099 235 : bSRSOK = true;
7100 : }
7101 : }
7102 :
7103 280 : if (!bSRSOK)
7104 : {
7105 44 : if (poGCSWKT == nullptr)
7106 : {
7107 0 : CPLError(CE_Failure, CPLE_AppDefined,
7108 : "Cannot resolve EPSG object, and GCS.WKT not found");
7109 0 : return FALSE;
7110 : }
7111 :
7112 44 : if (m_oSRS.importFromWkt(poGCSWKT->GetString().c_str()) != OGRERR_NONE)
7113 : {
7114 1 : m_oSRS.Clear();
7115 1 : return FALSE;
7116 : }
7117 : }
7118 :
7119 : /* -------------------------------------------------------------------- */
7120 : /* Compute geotransform */
7121 : /* -------------------------------------------------------------------- */
7122 279 : OGRSpatialReference *poSRSGeog = m_oSRS.CloneGeogCS();
7123 :
7124 : /* Files found at
7125 : * http://carto.iict.ch/blog/publications-cartographiques-au-format-geospatial-pdf/
7126 : */
7127 : /* are in a PROJCS. However the coordinates in GPTS array are not in (lat,
7128 : * long) as required by the */
7129 : /* ISO 32000 supplement spec, but in (northing, easting). Adobe reader is
7130 : * able to understand that, */
7131 : /* so let's also try to do it with a heuristics. */
7132 :
7133 279 : bool bReproject = true;
7134 279 : if (m_oSRS.IsProjected())
7135 : {
7136 1030 : for (int i = 0; i < nGPTSLength / 2; i++)
7137 : {
7138 824 : if (fabs(adfGPTS[2 * i]) > 91 || fabs(adfGPTS[2 * i + 1]) > 361)
7139 : {
7140 0 : CPLDebug("PDF", "GPTS coordinates seems to be in (northing, "
7141 : "easting), which is non-standard");
7142 0 : bReproject = false;
7143 0 : break;
7144 : }
7145 : }
7146 : }
7147 :
7148 279 : OGRCoordinateTransformation *poCT = nullptr;
7149 279 : if (bReproject)
7150 : {
7151 279 : poCT = OGRCreateCoordinateTransformation(poSRSGeog, &m_oSRS);
7152 279 : if (poCT == nullptr)
7153 : {
7154 0 : delete poSRSGeog;
7155 0 : m_oSRS.Clear();
7156 0 : return FALSE;
7157 : }
7158 : }
7159 :
7160 558 : std::vector<GDAL_GCP> asGCPS(nGPTSLength / 2);
7161 :
7162 : /* Create NEATLINE */
7163 279 : OGRLinearRing *poRing = nullptr;
7164 279 : if (nGPTSLength == 8)
7165 : {
7166 279 : m_poNeatLine = new OGRPolygon();
7167 279 : poRing = new OGRLinearRing();
7168 279 : m_poNeatLine->addRingDirectly(poRing);
7169 : }
7170 :
7171 1395 : for (int i = 0; i < nGPTSLength / 2; i++)
7172 : {
7173 : /* We probably assume LPTS is 0 or 1 */
7174 2232 : asGCPS[i].dfGCPPixel =
7175 1116 : (dfULX * (1 - adfLPTS[2 * i + 0]) + dfLRX * adfLPTS[2 * i + 0]) /
7176 1116 : dfMediaBoxWidth * nRasterXSize;
7177 2232 : asGCPS[i].dfGCPLine =
7178 1116 : (dfULY * (1 - adfLPTS[2 * i + 1]) + dfLRY * adfLPTS[2 * i + 1]) /
7179 1116 : dfMediaBoxHeight * nRasterYSize;
7180 :
7181 1116 : double lat = adfGPTS[2 * i];
7182 1116 : double lon = adfGPTS[2 * i + 1];
7183 1116 : double x = lon;
7184 1116 : double y = lat;
7185 1116 : if (bReproject)
7186 : {
7187 1116 : if (!poCT->Transform(1, &x, &y, nullptr))
7188 : {
7189 0 : CPLError(CE_Failure, CPLE_AppDefined,
7190 : "Cannot reproject (%f, %f)", lon, lat);
7191 0 : delete poSRSGeog;
7192 0 : delete poCT;
7193 0 : m_oSRS.Clear();
7194 0 : return FALSE;
7195 : }
7196 : }
7197 :
7198 1116 : x = ROUND_IF_CLOSE(x);
7199 1116 : y = ROUND_IF_CLOSE(y);
7200 :
7201 1116 : asGCPS[i].dfGCPX = x;
7202 1116 : asGCPS[i].dfGCPY = y;
7203 :
7204 1116 : if (poRing)
7205 1116 : poRing->addPoint(x, y);
7206 : }
7207 :
7208 279 : delete poSRSGeog;
7209 279 : delete poCT;
7210 :
7211 279 : if (!GDALGCPsToGeoTransform(nGPTSLength / 2, asGCPS.data(), m_gt.data(),
7212 : FALSE))
7213 : {
7214 2 : CPLDebug("PDF",
7215 : "Could not compute GT with exact match. Try with approximate");
7216 2 : if (!GDALGCPsToGeoTransform(nGPTSLength / 2, asGCPS.data(), m_gt.data(),
7217 : TRUE))
7218 : {
7219 0 : CPLError(CE_Failure, CPLE_AppDefined,
7220 : "Could not compute GT with approximate match.");
7221 0 : return FALSE;
7222 : }
7223 : }
7224 279 : m_bGeoTransformValid = true;
7225 :
7226 : // If the non scaling terms of the geotransform are significantly smaller
7227 : // than the pixel size, then nullify them as being just artifacts of
7228 : // reprojection and GDALGCPsToGeoTransform() numerical imprecisions.
7229 279 : const double dfPixelSize = std::min(fabs(m_gt[1]), fabs(m_gt[5]));
7230 279 : const double dfRotationShearTerm = std::max(fabs(m_gt[2]), fabs(m_gt[4]));
7231 377 : if (dfRotationShearTerm < 1e-5 * dfPixelSize ||
7232 98 : (m_bUseLib.test(PDFLIB_PDFIUM) &&
7233 372 : std::min(fabs(m_gt[2]), fabs(m_gt[4])) < 1e-5 * dfPixelSize))
7234 : {
7235 194 : dfLRX = m_gt[0] + nRasterXSize * m_gt[1] + nRasterYSize * m_gt[2];
7236 194 : dfLRY = m_gt[3] + nRasterXSize * m_gt[4] + nRasterYSize * m_gt[5];
7237 194 : m_gt[1] = (dfLRX - m_gt[0]) / nRasterXSize;
7238 194 : m_gt[5] = (dfLRY - m_gt[3]) / nRasterYSize;
7239 194 : m_gt[2] = m_gt[4] = 0;
7240 : }
7241 :
7242 279 : return TRUE;
7243 : }
7244 :
7245 : /************************************************************************/
7246 : /* GetSpatialRef() */
7247 : /************************************************************************/
7248 :
7249 95 : const OGRSpatialReference *PDFDataset::GetSpatialRef() const
7250 : {
7251 95 : const auto poSRS = GDALPamDataset::GetSpatialRef();
7252 95 : if (poSRS)
7253 38 : return poSRS;
7254 :
7255 57 : if (!m_oSRS.IsEmpty() && m_bGeoTransformValid)
7256 55 : return &m_oSRS;
7257 2 : return nullptr;
7258 : }
7259 :
7260 : /************************************************************************/
7261 : /* GetGeoTransform() */
7262 : /************************************************************************/
7263 :
7264 47 : CPLErr PDFDataset::GetGeoTransform(GDALGeoTransform >) const
7265 :
7266 : {
7267 47 : if (GDALPamDataset::GetGeoTransform(gt) == CE_None)
7268 : {
7269 6 : return CE_None;
7270 : }
7271 :
7272 41 : gt = m_gt;
7273 41 : return ((m_bGeoTransformValid) ? CE_None : CE_Failure);
7274 : }
7275 :
7276 : /************************************************************************/
7277 : /* SetSpatialRef() */
7278 : /************************************************************************/
7279 :
7280 11 : CPLErr PDFDataset::SetSpatialRef(const OGRSpatialReference *poSRS)
7281 : {
7282 11 : if (eAccess == GA_ReadOnly)
7283 4 : GDALPamDataset::SetSpatialRef(poSRS);
7284 :
7285 11 : m_oSRS.Clear();
7286 11 : if (poSRS)
7287 9 : m_oSRS = *poSRS;
7288 11 : m_bProjDirty = true;
7289 11 : return CE_None;
7290 : }
7291 :
7292 : /************************************************************************/
7293 : /* SetGeoTransform() */
7294 : /************************************************************************/
7295 :
7296 9 : CPLErr PDFDataset::SetGeoTransform(const GDALGeoTransform >)
7297 : {
7298 9 : if (eAccess == GA_ReadOnly)
7299 4 : GDALPamDataset::SetGeoTransform(gt);
7300 :
7301 9 : m_gt = gt;
7302 9 : m_bGeoTransformValid = true;
7303 9 : m_bProjDirty = true;
7304 :
7305 : /* Reset NEATLINE if not explicitly set by the user */
7306 9 : if (!m_bNeatLineDirty)
7307 9 : SetMetadataItem("NEATLINE", nullptr);
7308 9 : return CE_None;
7309 : }
7310 :
7311 : /************************************************************************/
7312 : /* GetMetadataDomainList() */
7313 : /************************************************************************/
7314 :
7315 1 : char **PDFDataset::GetMetadataDomainList()
7316 : {
7317 1 : return BuildMetadataDomainList(GDALPamDataset::GetMetadataDomainList(),
7318 : TRUE, "xml:XMP", "LAYERS",
7319 1 : "EMBEDDED_METADATA", nullptr);
7320 : }
7321 :
7322 : /************************************************************************/
7323 : /* GetMetadata() */
7324 : /************************************************************************/
7325 :
7326 2089 : char **PDFDataset::GetMetadata(const char *pszDomain)
7327 : {
7328 2089 : if (pszDomain != nullptr && EQUAL(pszDomain, "EMBEDDED_METADATA"))
7329 : {
7330 1 : char **papszRet = m_oMDMD_PDF.GetMetadata(pszDomain);
7331 1 : if (papszRet)
7332 0 : return papszRet;
7333 :
7334 1 : GDALPDFObject *poCatalog = GetCatalog();
7335 1 : if (poCatalog == nullptr)
7336 0 : return nullptr;
7337 : GDALPDFObject *poFirstElt =
7338 1 : poCatalog->LookupObject("Names.EmbeddedFiles.Names[0]");
7339 : GDALPDFObject *poF =
7340 1 : poCatalog->LookupObject("Names.EmbeddedFiles.Names[1].EF.F");
7341 :
7342 1 : if (poFirstElt == nullptr ||
7343 1 : poFirstElt->GetType() != PDFObjectType_String ||
7344 0 : poFirstElt->GetString() != "Metadata")
7345 1 : return nullptr;
7346 0 : if (poF == nullptr || poF->GetType() != PDFObjectType_Dictionary)
7347 0 : return nullptr;
7348 0 : GDALPDFStream *poStream = poF->GetStream();
7349 0 : if (poStream == nullptr)
7350 0 : return nullptr;
7351 :
7352 0 : char *apszMetadata[2] = {nullptr, nullptr};
7353 0 : apszMetadata[0] = poStream->GetBytes();
7354 0 : m_oMDMD_PDF.SetMetadata(apszMetadata, pszDomain);
7355 0 : VSIFree(apszMetadata[0]);
7356 0 : return m_oMDMD_PDF.GetMetadata(pszDomain);
7357 : }
7358 2088 : if (pszDomain == nullptr || EQUAL(pszDomain, ""))
7359 : {
7360 217 : char **papszPAMMD = GDALPamDataset::GetMetadata(pszDomain);
7361 222 : for (char **papszIter = papszPAMMD; papszIter && *papszIter;
7362 : ++papszIter)
7363 : {
7364 5 : char *pszKey = nullptr;
7365 5 : const char *pszValue = CPLParseNameValue(*papszIter, &pszKey);
7366 5 : if (pszKey && pszValue)
7367 : {
7368 5 : if (m_oMDMD_PDF.GetMetadataItem(pszKey, pszDomain) == nullptr)
7369 4 : m_oMDMD_PDF.SetMetadataItem(pszKey, pszValue, pszDomain);
7370 : }
7371 5 : CPLFree(pszKey);
7372 : }
7373 217 : return m_oMDMD_PDF.GetMetadata(pszDomain);
7374 : }
7375 1871 : if (EQUAL(pszDomain, "LAYERS") || EQUAL(pszDomain, "xml:XMP") ||
7376 1821 : EQUAL(pszDomain, "SUBDATASETS"))
7377 : {
7378 52 : return m_oMDMD_PDF.GetMetadata(pszDomain);
7379 : }
7380 1819 : return GDALPamDataset::GetMetadata(pszDomain);
7381 : }
7382 :
7383 : /************************************************************************/
7384 : /* SetMetadata() */
7385 : /************************************************************************/
7386 :
7387 128 : CPLErr PDFDataset::SetMetadata(char **papszMetadata, const char *pszDomain)
7388 : {
7389 128 : if (pszDomain == nullptr || EQUAL(pszDomain, ""))
7390 : {
7391 83 : char **papszMetadataDup = CSLDuplicate(papszMetadata);
7392 83 : m_oMDMD_PDF.SetMetadata(nullptr, pszDomain);
7393 :
7394 259 : for (char **papszIter = papszMetadataDup; papszIter && *papszIter;
7395 : ++papszIter)
7396 : {
7397 176 : char *pszKey = nullptr;
7398 176 : const char *pszValue = CPLParseNameValue(*papszIter, &pszKey);
7399 176 : if (pszKey && pszValue)
7400 : {
7401 173 : SetMetadataItem(pszKey, pszValue, pszDomain);
7402 : }
7403 176 : CPLFree(pszKey);
7404 : }
7405 83 : CSLDestroy(papszMetadataDup);
7406 83 : return CE_None;
7407 : }
7408 45 : else if (EQUAL(pszDomain, "xml:XMP"))
7409 : {
7410 41 : m_bXMPDirty = true;
7411 41 : return m_oMDMD_PDF.SetMetadata(papszMetadata, pszDomain);
7412 : }
7413 4 : else if (EQUAL(pszDomain, "SUBDATASETS"))
7414 : {
7415 4 : return m_oMDMD_PDF.SetMetadata(papszMetadata, pszDomain);
7416 : }
7417 : else
7418 : {
7419 0 : return GDALPamDataset::SetMetadata(papszMetadata, pszDomain);
7420 : }
7421 : }
7422 :
7423 : /************************************************************************/
7424 : /* GetMetadataItem() */
7425 : /************************************************************************/
7426 :
7427 1921 : const char *PDFDataset::GetMetadataItem(const char *pszName,
7428 : const char *pszDomain)
7429 : {
7430 1921 : if (pszDomain != nullptr && EQUAL(pszDomain, "_INTERNAL_") &&
7431 0 : pszName != nullptr && EQUAL(pszName, "PDF_LIB"))
7432 : {
7433 0 : if (m_bUseLib.test(PDFLIB_POPPLER))
7434 0 : return "POPPLER";
7435 0 : if (m_bUseLib.test(PDFLIB_PODOFO))
7436 0 : return "PODOFO";
7437 0 : if (m_bUseLib.test(PDFLIB_PDFIUM))
7438 0 : return "PDFIUM";
7439 : }
7440 1921 : return CSLFetchNameValue(GetMetadata(pszDomain), pszName);
7441 : }
7442 :
7443 : /************************************************************************/
7444 : /* SetMetadataItem() */
7445 : /************************************************************************/
7446 :
7447 1324 : CPLErr PDFDataset::SetMetadataItem(const char *pszName, const char *pszValue,
7448 : const char *pszDomain)
7449 : {
7450 1324 : if (pszDomain == nullptr || EQUAL(pszDomain, ""))
7451 : {
7452 1222 : if (EQUAL(pszName, "NEATLINE"))
7453 : {
7454 : const char *pszOldValue =
7455 350 : m_oMDMD_PDF.GetMetadataItem(pszName, pszDomain);
7456 350 : if ((pszValue == nullptr && pszOldValue != nullptr) ||
7457 347 : (pszValue != nullptr && pszOldValue == nullptr) ||
7458 2 : (pszValue != nullptr && pszOldValue != nullptr &&
7459 2 : strcmp(pszValue, pszOldValue) != 0))
7460 : {
7461 342 : m_bProjDirty = true;
7462 342 : m_bNeatLineDirty = true;
7463 : }
7464 350 : return m_oMDMD_PDF.SetMetadataItem(pszName, pszValue, pszDomain);
7465 : }
7466 : else
7467 : {
7468 872 : if (EQUAL(pszName, "AUTHOR") || EQUAL(pszName, "PRODUCER") ||
7469 829 : EQUAL(pszName, "CREATOR") || EQUAL(pszName, "CREATION_DATE") ||
7470 737 : EQUAL(pszName, "SUBJECT") || EQUAL(pszName, "TITLE") ||
7471 703 : EQUAL(pszName, "KEYWORDS"))
7472 : {
7473 181 : if (pszValue == nullptr)
7474 2 : pszValue = "";
7475 : const char *pszOldValue =
7476 181 : m_oMDMD_PDF.GetMetadataItem(pszName, pszDomain);
7477 181 : if (pszOldValue == nullptr ||
7478 4 : strcmp(pszValue, pszOldValue) != 0)
7479 : {
7480 181 : m_bInfoDirty = true;
7481 : }
7482 181 : return m_oMDMD_PDF.SetMetadataItem(pszName, pszValue,
7483 181 : pszDomain);
7484 : }
7485 691 : else if (EQUAL(pszName, "DPI"))
7486 : {
7487 688 : return m_oMDMD_PDF.SetMetadataItem(pszName, pszValue,
7488 688 : pszDomain);
7489 : }
7490 : else
7491 : {
7492 3 : m_oMDMD_PDF.SetMetadataItem(pszName, pszValue, pszDomain);
7493 3 : return GDALPamDataset::SetMetadataItem(pszName, pszValue,
7494 3 : pszDomain);
7495 : }
7496 : }
7497 : }
7498 102 : else if (EQUAL(pszDomain, "xml:XMP"))
7499 : {
7500 0 : m_bXMPDirty = true;
7501 0 : return m_oMDMD_PDF.SetMetadataItem(pszName, pszValue, pszDomain);
7502 : }
7503 102 : else if (EQUAL(pszDomain, "SUBDATASETS"))
7504 : {
7505 0 : return m_oMDMD_PDF.SetMetadataItem(pszName, pszValue, pszDomain);
7506 : }
7507 : else
7508 : {
7509 102 : return GDALPamDataset::SetMetadataItem(pszName, pszValue, pszDomain);
7510 : }
7511 : }
7512 :
7513 : /************************************************************************/
7514 : /* GetGCPCount() */
7515 : /************************************************************************/
7516 :
7517 21 : int PDFDataset::GetGCPCount()
7518 : {
7519 21 : return m_nGCPCount;
7520 : }
7521 :
7522 : /************************************************************************/
7523 : /* GetGCPSpatialRef() */
7524 : /************************************************************************/
7525 :
7526 4 : const OGRSpatialReference *PDFDataset::GetGCPSpatialRef() const
7527 : {
7528 4 : if (!m_oSRS.IsEmpty() && m_nGCPCount != 0)
7529 2 : return &m_oSRS;
7530 2 : return nullptr;
7531 : }
7532 :
7533 : /************************************************************************/
7534 : /* GetGCPs() */
7535 : /************************************************************************/
7536 :
7537 4 : const GDAL_GCP *PDFDataset::GetGCPs()
7538 : {
7539 4 : return m_pasGCPList;
7540 : }
7541 :
7542 : /************************************************************************/
7543 : /* SetGCPs() */
7544 : /************************************************************************/
7545 :
7546 2 : CPLErr PDFDataset::SetGCPs(int nGCPCountIn, const GDAL_GCP *pasGCPListIn,
7547 : const OGRSpatialReference *poSRS)
7548 : {
7549 : const char *pszGEO_ENCODING =
7550 2 : CPLGetConfigOption("GDAL_PDF_GEO_ENCODING", "ISO32000");
7551 2 : if (nGCPCountIn != 4 && EQUAL(pszGEO_ENCODING, "ISO32000"))
7552 : {
7553 0 : CPLError(CE_Failure, CPLE_NotSupported,
7554 : "PDF driver only supports writing 4 GCPs when "
7555 : "GDAL_PDF_GEO_ENCODING=ISO32000.");
7556 0 : return CE_Failure;
7557 : }
7558 :
7559 : /* Free previous GCPs */
7560 2 : GDALDeinitGCPs(m_nGCPCount, m_pasGCPList);
7561 2 : CPLFree(m_pasGCPList);
7562 :
7563 : /* Duplicate in GCPs */
7564 2 : m_nGCPCount = nGCPCountIn;
7565 2 : m_pasGCPList = GDALDuplicateGCPs(m_nGCPCount, pasGCPListIn);
7566 :
7567 2 : m_oSRS.Clear();
7568 2 : if (poSRS)
7569 2 : m_oSRS = *poSRS;
7570 :
7571 2 : m_bProjDirty = true;
7572 :
7573 : /* Reset NEATLINE if not explicitly set by the user */
7574 2 : if (!m_bNeatLineDirty)
7575 2 : SetMetadataItem("NEATLINE", nullptr);
7576 :
7577 2 : return CE_None;
7578 : }
7579 :
7580 : #endif // #ifdef HAVE_PDF_READ_SUPPORT
7581 :
7582 : /************************************************************************/
7583 : /* GDALPDFOpen() */
7584 : /************************************************************************/
7585 :
7586 90 : GDALDataset *GDALPDFOpen(
7587 : #ifdef HAVE_PDF_READ_SUPPORT
7588 : const char *pszFilename, GDALAccess eAccess
7589 : #else
7590 : CPL_UNUSED const char *pszFilename, CPL_UNUSED GDALAccess eAccess
7591 : #endif
7592 : )
7593 : {
7594 : #ifdef HAVE_PDF_READ_SUPPORT
7595 180 : GDALOpenInfo oOpenInfo(pszFilename, eAccess);
7596 180 : return PDFDataset::Open(&oOpenInfo);
7597 : #else
7598 : return nullptr;
7599 : #endif
7600 : }
7601 :
7602 : /************************************************************************/
7603 : /* GDALPDFUnloadDriver() */
7604 : /************************************************************************/
7605 :
7606 10 : static void GDALPDFUnloadDriver(CPL_UNUSED GDALDriver *poDriver)
7607 : {
7608 : #ifdef HAVE_POPPLER
7609 10 : if (hGlobalParamsMutex != nullptr)
7610 0 : CPLDestroyMutex(hGlobalParamsMutex);
7611 : #endif
7612 : #ifdef HAVE_PDFIUM
7613 10 : if (PDFDataset::g_bPdfiumInit)
7614 : {
7615 2 : CPLCreateOrAcquireMutex(&g_oPdfiumLoadDocMutex, PDFIUM_MUTEX_TIMEOUT);
7616 : // Destroy every loaded document or page
7617 2 : TMapPdfiumDatasets::iterator itDoc;
7618 2 : TMapPdfiumPages::iterator itPage;
7619 2 : for (itDoc = g_mPdfiumDatasets.begin();
7620 2 : itDoc != g_mPdfiumDatasets.end(); ++itDoc)
7621 : {
7622 0 : TPdfiumDocumentStruct *pDoc = itDoc->second;
7623 0 : for (itPage = pDoc->pages.begin(); itPage != pDoc->pages.end();
7624 0 : ++itPage)
7625 : {
7626 0 : TPdfiumPageStruct *pPage = itPage->second;
7627 :
7628 0 : CPLCreateOrAcquireMutex(&g_oPdfiumReadMutex,
7629 : PDFIUM_MUTEX_TIMEOUT);
7630 0 : CPLCreateOrAcquireMutex(&(pPage->readMutex),
7631 : PDFIUM_MUTEX_TIMEOUT);
7632 0 : CPLReleaseMutex(pPage->readMutex);
7633 0 : CPLDestroyMutex(pPage->readMutex);
7634 0 : FPDF_ClosePage(FPDFPageFromIPDFPage(pPage->page));
7635 0 : delete pPage;
7636 0 : CPLReleaseMutex(g_oPdfiumReadMutex);
7637 : } // ~ foreach page
7638 :
7639 0 : FPDF_CloseDocument(FPDFDocumentFromCPDFDocument(pDoc->doc));
7640 0 : CPLFree(pDoc->filename);
7641 0 : VSIFCloseL(static_cast<VSILFILE *>(pDoc->psFileAccess->m_Param));
7642 0 : delete pDoc->psFileAccess;
7643 0 : pDoc->pages.clear();
7644 :
7645 0 : delete pDoc;
7646 : } // ~ foreach document
7647 2 : g_mPdfiumDatasets.clear();
7648 2 : FPDF_DestroyLibrary();
7649 2 : PDFDataset::g_bPdfiumInit = FALSE;
7650 :
7651 2 : CPLReleaseMutex(g_oPdfiumLoadDocMutex);
7652 :
7653 2 : if (g_oPdfiumReadMutex)
7654 0 : CPLDestroyMutex(g_oPdfiumReadMutex);
7655 2 : CPLDestroyMutex(g_oPdfiumLoadDocMutex);
7656 : }
7657 : #endif
7658 10 : }
7659 :
7660 : /************************************************************************/
7661 : /* PDFSanitizeLayerName() */
7662 : /************************************************************************/
7663 :
7664 461 : CPLString PDFSanitizeLayerName(const char *pszName)
7665 : {
7666 461 : if (!CPLTestBool(CPLGetConfigOption("GDAL_PDF_LAUNDER_LAYER_NAMES", "YES")))
7667 0 : return pszName;
7668 :
7669 922 : CPLString osName;
7670 4172 : for (int i = 0; pszName[i] != '\0'; i++)
7671 : {
7672 3711 : if (pszName[i] == ' ' || pszName[i] == '.' || pszName[i] == ',')
7673 172 : osName += "_";
7674 3539 : else if (pszName[i] != '"')
7675 3539 : osName += pszName[i];
7676 : }
7677 461 : if (osName.empty())
7678 3 : osName = "unnamed";
7679 461 : return osName;
7680 : }
7681 :
7682 : /************************************************************************/
7683 : /* GDALPDFListLayersAlgorithm */
7684 : /************************************************************************/
7685 :
7686 : #ifdef HAVE_PDF_READ_SUPPORT
7687 :
7688 : class GDALPDFListLayersAlgorithm final : public GDALAlgorithm
7689 : {
7690 : public:
7691 13 : GDALPDFListLayersAlgorithm()
7692 13 : : GDALAlgorithm("list-layers",
7693 26 : std::string("List layers of a PDF dataset"),
7694 39 : "/drivers/raster/pdf.html")
7695 : {
7696 13 : AddInputDatasetArg(&m_dataset, GDAL_OF_RASTER | GDAL_OF_VECTOR);
7697 13 : AddOutputFormatArg(&m_format).SetDefault(m_format).SetChoices("json",
7698 13 : "text");
7699 13 : AddOutputStringArg(&m_output);
7700 13 : }
7701 :
7702 : protected:
7703 : bool RunImpl(GDALProgressFunc, void *) override;
7704 :
7705 : private:
7706 : GDALArgDatasetValue m_dataset{};
7707 : std::string m_format = "json";
7708 : std::string m_output{};
7709 : };
7710 :
7711 3 : bool GDALPDFListLayersAlgorithm::RunImpl(GDALProgressFunc, void *)
7712 : {
7713 3 : auto poDS = dynamic_cast<PDFDataset *>(m_dataset.GetDatasetRef());
7714 3 : if (!poDS)
7715 : {
7716 1 : ReportError(CE_Failure, CPLE_AppDefined, "%s is not a PDF",
7717 1 : m_dataset.GetName().c_str());
7718 1 : return false;
7719 : }
7720 2 : if (m_format == "json")
7721 : {
7722 2 : CPLJSonStreamingWriter oWriter(nullptr, nullptr);
7723 1 : oWriter.StartArray();
7724 10 : for (const auto &[key, value] : cpl::IterateNameValue(
7725 11 : const_cast<CSLConstList>(poDS->GetMetadata("LAYERS"))))
7726 : {
7727 5 : CPL_IGNORE_RET_VAL(key);
7728 5 : oWriter.Add(value);
7729 : }
7730 1 : oWriter.EndArray();
7731 1 : m_output = oWriter.GetString();
7732 1 : m_output += '\n';
7733 : }
7734 : else
7735 : {
7736 10 : for (const auto &[key, value] : cpl::IterateNameValue(
7737 11 : const_cast<CSLConstList>(poDS->GetMetadata("LAYERS"))))
7738 : {
7739 5 : CPL_IGNORE_RET_VAL(key);
7740 5 : m_output += value;
7741 5 : m_output += '\n';
7742 : }
7743 : }
7744 2 : return true;
7745 : }
7746 :
7747 : /************************************************************************/
7748 : /* GDALPDFInstantiateAlgorithm() */
7749 : /************************************************************************/
7750 :
7751 : static GDALAlgorithm *
7752 13 : GDALPDFInstantiateAlgorithm(const std::vector<std::string> &aosPath)
7753 : {
7754 13 : if (aosPath.size() == 1 && aosPath[0] == "list-layers")
7755 : {
7756 13 : return std::make_unique<GDALPDFListLayersAlgorithm>().release();
7757 : }
7758 : else
7759 : {
7760 0 : return nullptr;
7761 : }
7762 : }
7763 :
7764 : #endif // HAVE_PDF_READ_SUPPORT
7765 :
7766 : /************************************************************************/
7767 : /* GDALRegister_PDF() */
7768 : /************************************************************************/
7769 :
7770 18 : void GDALRegister_PDF()
7771 :
7772 : {
7773 18 : if (!GDAL_CHECK_VERSION("PDF driver"))
7774 0 : return;
7775 :
7776 18 : if (GDALGetDriverByName(DRIVER_NAME) != nullptr)
7777 0 : return;
7778 :
7779 18 : GDALDriver *poDriver = new GDALDriver();
7780 18 : PDFDriverSetCommonMetadata(poDriver);
7781 :
7782 : #ifdef HAVE_PDF_READ_SUPPORT
7783 18 : poDriver->pfnOpen = PDFDataset::OpenWrapper;
7784 18 : poDriver->pfnInstantiateAlgorithm = GDALPDFInstantiateAlgorithm;
7785 : #endif // HAVE_PDF_READ_SUPPORT
7786 :
7787 18 : poDriver->pfnCreateCopy = GDALPDFCreateCopy;
7788 18 : poDriver->pfnCreate = PDFWritableVectorDataset::Create;
7789 18 : poDriver->pfnUnloadDriver = GDALPDFUnloadDriver;
7790 :
7791 18 : GetGDALDriverManager()->RegisterDriver(poDriver);
7792 : }
|