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 final : 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 56 : GDALPDFOutputDev(SplashColorMode colorModeA, int bitmapRowPadA,
96 : bool reverseVideoA, SplashColorPtr paperColorA)
97 56 : : SplashOutputDev(colorModeA, bitmapRowPadA, reverseVideoA,
98 : paperColorA),
99 56 : bEnableVector(TRUE), bEnableText(TRUE), bEnableBitmap(TRUE)
100 : {
101 56 : }
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 : void startPage(int pageNum, GfxState *state, XRef *xrefIn) override;
119 :
120 1673 : void stroke(GfxState *state) override
121 : {
122 1673 : if (bEnableVector)
123 1664 : SplashOutputDev::stroke(state);
124 1673 : }
125 :
126 8 : void fill(GfxState *state) override
127 : {
128 8 : if (bEnableVector)
129 8 : SplashOutputDev::fill(state);
130 8 : }
131 :
132 38 : 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 : void beginTextObject(GfxState *state) override
149 : {
150 681 : if (bEnableText)
151 678 : SplashOutputDev::beginTextObject(state);
152 681 : }
153 :
154 681 : 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 43 : 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 43 : if (bEnableBitmap)
203 40 : 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 43 : }
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 56 : void GDALPDFOutputDev::startPage(int pageNum, GfxState *state, XRef *xrefIn)
257 : {
258 56 : SplashOutputDev::startPage(pageNum, state, xrefIn);
259 56 : SplashBitmap *poBitmap = getBitmap();
260 112 : memset(poBitmap->getDataPtr(), 255,
261 56 : static_cast<size_t>(poBitmap->getRowSize()) * poBitmap->getHeight());
262 56 : }
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 1 : GDALPDFDumper(const char *pszFilename, const char *pszDumpFile,
284 : int nDepthLimitIn = -1)
285 1 : : nDepthLimit(nDepthLimitIn),
286 1 : bDumpParent(CPLGetConfigOption("PDF_DUMP_PARENT", "FALSE"))
287 : {
288 1 : if (strcmp(pszDumpFile, "stderr") == 0)
289 0 : f = stderr;
290 1 : else if (EQUAL(pszDumpFile, "YES"))
291 0 : f = fopen(CPLSPrintf("dump_%s.txt", CPLGetFilename(pszFilename)),
292 : "wt");
293 : else
294 1 : f = fopen(pszDumpFile, "wt");
295 1 : if (f == nullptr)
296 0 : f = stderr;
297 1 : }
298 :
299 1 : ~GDALPDFDumper()
300 1 : {
301 1 : if (f != stderr)
302 1 : fclose(f);
303 1 : }
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 3 : void GDALPDFDumper::Dump(GDALPDFArray *poArray, int nDepth)
311 : {
312 3 : if (nDepthLimit >= 0 && nDepth > nDepthLimit)
313 0 : return;
314 :
315 3 : int nLength = poArray->GetLength();
316 : int i;
317 6 : CPLString osIndent;
318 14 : for (i = 0; i < nDepth; i++)
319 11 : osIndent += " ";
320 8 : for (i = 0; i < nLength; i++)
321 : {
322 5 : fprintf(f, "%sItem[%d]:", osIndent.c_str(), i);
323 5 : GDALPDFObject *poObj = nullptr;
324 5 : if ((poObj = poArray->Get(i)) != nullptr)
325 : {
326 5 : if (poObj->GetType() == PDFObjectType_String ||
327 5 : poObj->GetType() == PDFObjectType_Null ||
328 5 : poObj->GetType() == PDFObjectType_Bool ||
329 5 : poObj->GetType() == PDFObjectType_Int ||
330 11 : poObj->GetType() == PDFObjectType_Real ||
331 1 : poObj->GetType() == PDFObjectType_Name)
332 : {
333 4 : fprintf(f, " ");
334 4 : DumpSimplified(poObj);
335 4 : fprintf(f, "\n");
336 : }
337 : else
338 : {
339 1 : fprintf(f, "\n");
340 1 : Dump(poObj, nDepth + 1);
341 : }
342 : }
343 : }
344 : }
345 :
346 493 : void GDALPDFDumper::DumpSimplified(GDALPDFObject *poObj)
347 : {
348 493 : 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 247 : case PDFObjectType_Int:
363 247 : fprintf(f, "%d (int)", poObj->GetInt());
364 247 : break;
365 :
366 0 : case PDFObjectType_Real:
367 0 : fprintf(f, "%f (real)", poObj->GetReal());
368 0 : break;
369 :
370 246 : case PDFObjectType_Name:
371 246 : fprintf(f, "%s (name)", poObj->GetName().c_str());
372 246 : break;
373 :
374 0 : default:
375 0 : fprintf(f, "unknown !");
376 0 : break;
377 : }
378 493 : }
379 :
380 70 : void GDALPDFDumper::Dump(GDALPDFObject *poObj, int nDepth)
381 : {
382 70 : if (nDepthLimit >= 0 && nDepth > nDepthLimit)
383 1 : return;
384 :
385 : int i;
386 70 : CPLString osIndent;
387 516 : for (i = 0; i < nDepth; i++)
388 446 : osIndent += " ";
389 70 : fprintf(f, "%sType = %s", osIndent.c_str(), poObj->GetTypeName());
390 70 : int nRefNum = poObj->GetRefNum().toInt();
391 70 : if (nRefNum != 0)
392 66 : fprintf(f, ", Num = %d, Gen = %d", nRefNum, poObj->GetRefGen());
393 70 : fprintf(f, "\n");
394 :
395 70 : if (nRefNum != 0)
396 : {
397 66 : if (aoSetObjectExplored.find(nRefNum) != aoSetObjectExplored.end())
398 1 : return;
399 65 : aoSetObjectExplored.insert(nRefNum);
400 : }
401 :
402 69 : switch (poObj->GetType())
403 : {
404 3 : case PDFObjectType_Array:
405 3 : Dump(poObj->GetArray(), nDepth + 1);
406 3 : break;
407 :
408 66 : case PDFObjectType_Dictionary:
409 66 : Dump(poObj->GetDictionary(), nDepth + 1);
410 66 : 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 69 : GDALPDFStream *poStream = poObj->GetStream();
430 69 : if (poStream != nullptr)
431 : {
432 61 : fprintf(f,
433 : "%sHas stream (" CPL_FRMT_GIB
434 : " uncompressed bytes, " CPL_FRMT_GIB " raw bytes)\n",
435 61 : osIndent.c_str(), static_cast<GIntBig>(poStream->GetLength()),
436 61 : static_cast<GIntBig>(poStream->GetRawLength()));
437 : }
438 : }
439 :
440 66 : void GDALPDFDumper::Dump(GDALPDFDictionary *poDict, int nDepth)
441 : {
442 66 : if (nDepthLimit >= 0 && nDepth > nDepthLimit)
443 0 : return;
444 :
445 132 : CPLString osIndent;
446 564 : for (int i = 0; i < nDepth; i++)
447 498 : osIndent += " ";
448 66 : int i = 0;
449 66 : const auto &oMap = poDict->GetValues();
450 623 : for (const auto &[osKey, poObj] : oMap)
451 : {
452 557 : fprintf(f, "%sItem[%d] : %s", osIndent.c_str(), i, osKey.c_str());
453 557 : ++i;
454 557 : 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 557 : if (poObj != nullptr)
463 : {
464 557 : if (poObj->GetType() == PDFObjectType_String ||
465 557 : poObj->GetType() == PDFObjectType_Null ||
466 557 : poObj->GetType() == PDFObjectType_Bool ||
467 557 : poObj->GetType() == PDFObjectType_Int ||
468 1428 : poObj->GetType() == PDFObjectType_Real ||
469 314 : poObj->GetType() == PDFObjectType_Name)
470 : {
471 489 : fprintf(f, " = ");
472 489 : DumpSimplified(poObj);
473 489 : fprintf(f, "\n");
474 : }
475 : else
476 : {
477 68 : fprintf(f, "\n");
478 68 : Dump(poObj, nDepth + 1);
479 : }
480 : }
481 : }
482 : }
483 :
484 : /************************************************************************/
485 : /* PDFRasterBand() */
486 : /************************************************************************/
487 :
488 649 : PDFRasterBand::PDFRasterBand(PDFDataset *poDSIn, int nBandIn,
489 649 : int nResolutionLevelIn)
490 649 : : nResolutionLevel(nResolutionLevelIn)
491 : {
492 649 : poDS = poDSIn;
493 649 : nBand = nBandIn;
494 :
495 649 : eDataType = GDT_Byte;
496 :
497 649 : if (nResolutionLevel > 0)
498 : {
499 0 : nBlockXSize = 256;
500 0 : nBlockYSize = 256;
501 0 : poDSIn->SetMetadataItem("INTERLEAVE", "PIXEL", "IMAGE_STRUCTURE");
502 : }
503 649 : else if (poDSIn->m_nBlockXSize)
504 : {
505 36 : nBlockXSize = poDSIn->m_nBlockXSize;
506 36 : nBlockYSize = poDSIn->m_nBlockYSize;
507 36 : poDSIn->SetMetadataItem("INTERLEAVE", "PIXEL", "IMAGE_STRUCTURE");
508 : }
509 613 : else if (poDSIn->GetRasterXSize() <
510 613 : 64 * 1024 * 1024 / poDSIn->GetRasterYSize())
511 : {
512 610 : nBlockXSize = poDSIn->GetRasterXSize();
513 610 : nBlockYSize = 1;
514 : }
515 : else
516 : {
517 3 : nBlockXSize = std::min(1024, poDSIn->GetRasterXSize());
518 3 : nBlockYSize = std::min(1024, poDSIn->GetRasterYSize());
519 3 : poDSIn->SetMetadataItem("INTERLEAVE", "PIXEL", "IMAGE_STRUCTURE");
520 : }
521 649 : }
522 :
523 : /************************************************************************/
524 : /* InitOverviews() */
525 : /************************************************************************/
526 :
527 5 : void PDFDataset::InitOverviews()
528 : {
529 : #ifdef HAVE_PDFIUM
530 : // Only if used pdfium, make "arbitrary overviews"
531 : // Blocks are 256x256
532 : if (m_bUseLib.test(PDFLIB_PDFIUM) && m_apoOvrDS.empty() &&
533 : m_apoOvrDSBackup.empty())
534 : {
535 : int nXSize = nRasterXSize;
536 : int nYSize = nRasterYSize;
537 : constexpr int minSize = 256;
538 : int nDiscard = 1;
539 : while (nXSize > minSize || nYSize > minSize)
540 : {
541 : nXSize = (nXSize + 1) / 2;
542 : nYSize = (nYSize + 1) / 2;
543 :
544 : auto poOvrDS = std::make_unique<PDFDataset>(this, nXSize, nYSize);
545 :
546 : for (int i = 0; i < nBands; i++)
547 : poOvrDS->SetBand(
548 : i + 1, new PDFRasterBand(poOvrDS.get(), i + 1, nDiscard));
549 :
550 : m_apoOvrDS.emplace_back(std::move(poOvrDS));
551 : ++nDiscard;
552 : }
553 : }
554 : #endif
555 : #if defined(HAVE_POPPLER) || defined(HAVE_PODOFO)
556 13 : if (!m_bUseLib.test(PDFLIB_PDFIUM) && m_apoOvrDS.empty() &&
557 13 : m_apoOvrDSBackup.empty() && m_osUserPwd != "ASK_INTERACTIVE")
558 : {
559 2 : int nXSize = nRasterXSize;
560 2 : int nYSize = nRasterYSize;
561 2 : constexpr int minSize = 256;
562 2 : double dfDPI = m_dfDPI;
563 4 : 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 5 : }
586 :
587 : /************************************************************************/
588 : /* GetColorInterpretation() */
589 : /************************************************************************/
590 :
591 16 : GDALColorInterp PDFRasterBand::GetColorInterpretation()
592 : {
593 16 : PDFDataset *poGDS = cpl::down_cast<PDFDataset *>(poDS);
594 16 : if (poGDS->nBands == 1)
595 0 : return GCI_GrayIndex;
596 : else
597 16 : return static_cast<GDALColorInterp>(GCI_RedBand + (nBand - 1));
598 : }
599 :
600 : /************************************************************************/
601 : /* GetOverviewCount() */
602 : /************************************************************************/
603 :
604 9 : int PDFRasterBand::GetOverviewCount()
605 : {
606 9 : PDFDataset *poGDS = cpl::down_cast<PDFDataset *>(poDS);
607 9 : if (poGDS->m_bIsOvrDS)
608 0 : return 0;
609 9 : if (GDALPamRasterBand::GetOverviewCount() > 0)
610 4 : return GDALPamRasterBand::GetOverviewCount();
611 : else
612 : {
613 5 : poGDS->InitOverviews();
614 5 : return static_cast<int>(poGDS->m_apoOvrDS.size());
615 : }
616 : }
617 :
618 : /************************************************************************/
619 : /* GetOverview() */
620 : /************************************************************************/
621 :
622 4 : GDALRasterBand *PDFRasterBand::GetOverview(int iOverviewIndex)
623 : {
624 4 : if (GDALPamRasterBand::GetOverviewCount() > 0)
625 1 : return GDALPamRasterBand::GetOverview(iOverviewIndex);
626 :
627 3 : else if (iOverviewIndex < 0 || iOverviewIndex >= GetOverviewCount())
628 2 : return nullptr;
629 : else
630 : {
631 1 : PDFDataset *poGDS = cpl::down_cast<PDFDataset *>(poDS);
632 1 : return poGDS->m_apoOvrDS[iOverviewIndex]->GetRasterBand(nBand);
633 : }
634 : }
635 :
636 : /************************************************************************/
637 : /* ~PDFRasterBand() */
638 : /************************************************************************/
639 :
640 1298 : PDFRasterBand::~PDFRasterBand()
641 : {
642 1298 : }
643 :
644 : /************************************************************************/
645 : /* IReadBlockFromTile() */
646 : /************************************************************************/
647 :
648 160 : CPLErr PDFRasterBand::IReadBlockFromTile(int nBlockXOff, int nBlockYOff,
649 : void *pImage)
650 :
651 : {
652 160 : PDFDataset *poGDS = cpl::down_cast<PDFDataset *>(poDS);
653 :
654 160 : int nReqXSize = nBlockXSize;
655 160 : int nReqYSize = nBlockYSize;
656 160 : if ((nBlockXOff + 1) * nBlockXSize > nRasterXSize)
657 20 : nReqXSize = nRasterXSize - nBlockXOff * nBlockXSize;
658 160 : if ((nBlockYOff + 1) * nBlockYSize > nRasterYSize)
659 24 : nReqYSize = nRasterYSize - nBlockYOff * nBlockYSize;
660 :
661 160 : int nXBlocks = DIV_ROUND_UP(nRasterXSize, nBlockXSize);
662 160 : int iTile = poGDS->m_aiTiles[nBlockYOff * nXBlocks + nBlockXOff];
663 160 : if (iTile < 0)
664 : {
665 0 : memset(pImage, 0, static_cast<size_t>(nBlockXSize) * nBlockYSize);
666 0 : return CE_None;
667 : }
668 :
669 160 : GDALPDFTileDesc &sTile = poGDS->m_asTiles[iTile];
670 160 : GDALPDFObject *poImage = sTile.poImage;
671 :
672 160 : if (nBand == 4)
673 : {
674 30 : GDALPDFDictionary *poImageDict = poImage->GetDictionary();
675 30 : GDALPDFObject *poSMask = poImageDict->Get("SMask");
676 60 : if (poSMask != nullptr &&
677 30 : poSMask->GetType() == PDFObjectType_Dictionary)
678 : {
679 30 : GDALPDFDictionary *poSMaskDict = poSMask->GetDictionary();
680 30 : GDALPDFObject *poWidth = poSMaskDict->Get("Width");
681 30 : GDALPDFObject *poHeight = poSMaskDict->Get("Height");
682 30 : GDALPDFObject *poColorSpace = poSMaskDict->Get("ColorSpace");
683 : GDALPDFObject *poBitsPerComponent =
684 30 : poSMaskDict->Get("BitsPerComponent");
685 30 : double dfBits = 0;
686 30 : if (poBitsPerComponent)
687 30 : dfBits = Get(poBitsPerComponent);
688 30 : if (poWidth && Get(poWidth) == nReqXSize && poHeight &&
689 30 : Get(poHeight) == nReqYSize && poColorSpace &&
690 60 : poColorSpace->GetType() == PDFObjectType_Name &&
691 112 : poColorSpace->GetName() == "DeviceGray" &&
692 22 : (dfBits == 1 || dfBits == 8))
693 : {
694 30 : GDALPDFStream *poStream = poSMask->GetStream();
695 30 : GByte *pabyStream = nullptr;
696 :
697 30 : if (poStream == nullptr)
698 0 : return CE_Failure;
699 :
700 30 : pabyStream = reinterpret_cast<GByte *>(poStream->GetBytes());
701 30 : if (pabyStream == nullptr)
702 0 : return CE_Failure;
703 :
704 30 : const int nReqXSize1 = (nReqXSize + 7) / 8;
705 52 : if ((dfBits == 8 &&
706 22 : static_cast<size_t>(poStream->GetLength()) !=
707 60 : static_cast<size_t>(nReqXSize) * nReqYSize) ||
708 8 : (dfBits == 1 &&
709 8 : static_cast<size_t>(poStream->GetLength()) !=
710 8 : static_cast<size_t>(nReqXSize1) * nReqYSize))
711 : {
712 0 : VSIFree(pabyStream);
713 0 : return CE_Failure;
714 : }
715 :
716 30 : GByte *pabyData = static_cast<GByte *>(pImage);
717 30 : if (nReqXSize != nBlockXSize || nReqYSize != nBlockYSize)
718 : {
719 10 : memset(pabyData, 0,
720 10 : static_cast<size_t>(nBlockXSize) * nBlockYSize);
721 : }
722 :
723 30 : if (dfBits == 8)
724 : {
725 686 : for (int j = 0; j < nReqYSize; j++)
726 : {
727 21912 : for (int i = 0; i < nReqXSize; i++)
728 : {
729 21248 : pabyData[j * nBlockXSize + i] =
730 21248 : pabyStream[j * nReqXSize + i];
731 : }
732 : }
733 : }
734 : else
735 : {
736 244 : for (int j = 0; j < nReqYSize; j++)
737 : {
738 3288 : for (int i = 0; i < nReqXSize; i++)
739 : {
740 3052 : if (pabyStream[j * nReqXSize1 + i / 8] &
741 3052 : (1 << (7 - (i % 8))))
742 896 : pabyData[j * nBlockXSize + i] = 255;
743 : else
744 2156 : pabyData[j * nBlockXSize + i] = 0;
745 : }
746 : }
747 : }
748 :
749 30 : VSIFree(pabyStream);
750 30 : 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 130 : 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 130 : if (!poGDS->m_bTried)
770 : {
771 5 : poGDS->m_bTried = true;
772 5 : poGDS->m_pabyCachedData =
773 5 : static_cast<GByte *>(VSIMalloc3(3, nBlockXSize, nBlockYSize));
774 : }
775 130 : if (poGDS->m_pabyCachedData == nullptr)
776 0 : return CE_Failure;
777 :
778 130 : GDALPDFStream *poStream = poImage->GetStream();
779 130 : GByte *pabyStream = nullptr;
780 :
781 130 : if (poStream == nullptr)
782 0 : return CE_Failure;
783 :
784 130 : pabyStream = reinterpret_cast<GByte *>(poStream->GetBytes());
785 130 : if (pabyStream == nullptr)
786 0 : return CE_Failure;
787 :
788 130 : if (static_cast<size_t>(poStream->GetLength()) !=
789 130 : static_cast<size_t>(sTile.nBands) * nReqXSize * nReqYSize)
790 : {
791 0 : VSIFree(pabyStream);
792 0 : return CE_Failure;
793 : }
794 :
795 130 : memcpy(poGDS->m_pabyCachedData, pabyStream,
796 130 : static_cast<size_t>(poStream->GetLength()));
797 130 : VSIFree(pabyStream);
798 130 : poGDS->m_nLastBlockXOff = nBlockXOff;
799 130 : poGDS->m_nLastBlockYOff = nBlockYOff;
800 : }
801 :
802 130 : GByte *pabyData = static_cast<GByte *>(pImage);
803 130 : if (nBand != 4 && (nReqXSize != nBlockXSize || nReqYSize != nBlockYSize))
804 : {
805 30 : memset(pabyData, 0, static_cast<size_t>(nBlockXSize) * nBlockYSize);
806 : }
807 :
808 130 : if (poGDS->nBands >= 3 && sTile.nBands == 3)
809 : {
810 2790 : for (int j = 0; j < nReqYSize; j++)
811 : {
812 75600 : for (int i = 0; i < nReqXSize; i++)
813 : {
814 72900 : pabyData[j * nBlockXSize + i] =
815 : poGDS
816 72900 : ->m_pabyCachedData[3 * (j * nReqXSize + i) + nBand - 1];
817 : }
818 90 : }
819 : }
820 40 : else if (sTile.nBands == 1)
821 : {
822 6184 : for (int j = 0; j < nReqYSize; j++)
823 : {
824 1054720 : for (int i = 0; i < nReqXSize; i++)
825 : {
826 1048580 : pabyData[j * nBlockXSize + i] =
827 1048580 : poGDS->m_pabyCachedData[j * nReqXSize + i];
828 : }
829 : }
830 : }
831 :
832 130 : return CE_None;
833 : }
834 :
835 : /************************************************************************/
836 : /* GetSuggestedBlockAccessPattern() */
837 : /************************************************************************/
838 :
839 : GDALSuggestedBlockAccessPattern
840 1 : PDFRasterBand::GetSuggestedBlockAccessPattern() const
841 : {
842 1 : PDFDataset *poGDS = cpl::down_cast<PDFDataset *>(poDS);
843 1 : if (!poGDS->m_aiTiles.empty())
844 0 : return GSBAP_RANDOM;
845 1 : return GSBAP_LARGEST_CHUNK_POSSIBLE;
846 : }
847 :
848 : /************************************************************************/
849 : /* IReadBlock() */
850 : /************************************************************************/
851 :
852 25832 : CPLErr PDFRasterBand::IReadBlock(int nBlockXOff, int nBlockYOff, void *pImage)
853 :
854 : {
855 25832 : PDFDataset *poGDS = cpl::down_cast<PDFDataset *>(poDS);
856 :
857 25832 : if (!poGDS->m_aiTiles.empty())
858 : {
859 160 : if (IReadBlockFromTile(nBlockXOff, nBlockYOff, pImage) == CE_None)
860 : {
861 160 : 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 25672 : int nReqXSize = nBlockXSize;
875 25672 : int nReqYSize = nBlockYSize;
876 25672 : if ((nBlockXOff + 1) * nBlockXSize > nRasterXSize)
877 0 : nReqXSize = nRasterXSize - nBlockXOff * nBlockXSize;
878 25672 : if (nBlockYSize == 1)
879 25671 : nReqYSize = nRasterYSize;
880 1 : else if ((nBlockYOff + 1) * nBlockYSize > nRasterYSize)
881 0 : nReqYSize = nRasterYSize - nBlockYOff * nBlockYSize;
882 :
883 25672 : if (!poGDS->m_bTried)
884 : {
885 55 : poGDS->m_bTried = true;
886 55 : if (nBlockYSize == 1)
887 162 : poGDS->m_pabyCachedData = static_cast<GByte *>(VSIMalloc3(
888 54 : std::max(3, poGDS->nBands), nRasterXSize, nRasterYSize));
889 : else
890 3 : poGDS->m_pabyCachedData = static_cast<GByte *>(VSIMalloc3(
891 1 : std::max(3, poGDS->nBands), nBlockXSize, nBlockYSize));
892 : }
893 25672 : if (poGDS->m_pabyCachedData == nullptr)
894 0 : return CE_Failure;
895 :
896 25672 : if (poGDS->m_nLastBlockXOff == nBlockXOff &&
897 25617 : (nBlockYSize == 1 || poGDS->m_nLastBlockYOff == nBlockYOff) &&
898 25617 : 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 55 : const int nReqXOff = nBlockXOff * nBlockXSize;
915 55 : const int nReqYOff = (nBlockYSize == 1) ? 0 : nBlockYOff * nBlockYSize;
916 55 : const GSpacing nPixelSpace = 1;
917 55 : const GSpacing nLineSpace = nBlockXSize;
918 55 : const GSpacing nBandSpace =
919 55 : static_cast<GSpacing>(nBlockXSize) *
920 55 : ((nBlockYSize == 1) ? nRasterYSize : nBlockYSize);
921 :
922 55 : CPLErr eErr = poGDS->ReadPixels(nReqXOff, nReqYOff, nReqXSize,
923 : nReqYSize, nPixelSpace, nLineSpace,
924 : nBandSpace, poGDS->m_pabyCachedData);
925 :
926 55 : if (eErr == CE_None)
927 : {
928 55 : poGDS->m_nLastBlockXOff = nBlockXOff;
929 55 : poGDS->m_nLastBlockYOff = nBlockYOff;
930 : }
931 : else
932 : {
933 0 : CPLFree(poGDS->m_pabyCachedData);
934 0 : poGDS->m_pabyCachedData = nullptr;
935 : }
936 : }
937 25672 : if (poGDS->m_pabyCachedData == nullptr)
938 0 : return CE_Failure;
939 :
940 25672 : if (nBlockYSize == 1)
941 25671 : memcpy(pImage,
942 25671 : poGDS->m_pabyCachedData +
943 25671 : (nBand - 1) * nBlockXSize * nRasterYSize +
944 25671 : nBlockYOff * nBlockXSize,
945 25671 : nBlockXSize);
946 : else
947 : {
948 1 : memcpy(pImage,
949 1 : poGDS->m_pabyCachedData +
950 1 : static_cast<size_t>(nBand - 1) * nBlockXSize * nBlockYSize,
951 1 : static_cast<size_t>(nBlockXSize) * nBlockYSize);
952 :
953 1 : if (poGDS->m_bCacheBlocksForOtherBands && nBand == 1)
954 : {
955 3 : for (int iBand = 2; iBand <= poGDS->nBands; ++iBand)
956 : {
957 4 : auto poOtherBand = cpl::down_cast<PDFRasterBand *>(
958 2 : poGDS->papoBands[iBand - 1]);
959 : GDALRasterBlock *poBlock =
960 2 : poOtherBand->TryGetLockedBlockRef(nBlockXOff, nBlockYOff);
961 2 : if (poBlock)
962 : {
963 0 : poBlock->DropLock();
964 : }
965 : else
966 : {
967 4 : poBlock = poOtherBand->GetLockedBlockRef(nBlockXOff,
968 2 : nBlockYOff, TRUE);
969 2 : if (poBlock)
970 : {
971 4 : memcpy(poBlock->GetDataRef(),
972 2 : poGDS->m_pabyCachedData +
973 2 : static_cast<size_t>(iBand - 1) *
974 2 : nBlockXSize * nBlockYSize,
975 2 : static_cast<size_t>(nBlockXSize) * nBlockYSize);
976 2 : poBlock->DropLock();
977 : }
978 : }
979 : }
980 : }
981 : }
982 :
983 25672 : return CE_None;
984 : }
985 :
986 : /************************************************************************/
987 : /* PDFEnterPasswordFromConsoleIfNeeded() */
988 : /************************************************************************/
989 :
990 2 : static const char *PDFEnterPasswordFromConsoleIfNeeded(const char *pszUserPwd)
991 : {
992 2 : if (EQUAL(pszUserPwd, "ASK_INTERACTIVE"))
993 : {
994 : static char szPassword[81];
995 2 : printf("Enter password (will be echo'ed in the console): "); /*ok*/
996 2 : if (nullptr == fgets(szPassword, sizeof(szPassword), stdin))
997 : {
998 0 : fprintf(stderr, "WARNING: Error getting password.\n"); /*ok*/
999 : }
1000 2 : szPassword[sizeof(szPassword) - 1] = 0;
1001 2 : char *sz10 = strchr(szPassword, '\n');
1002 2 : if (sz10)
1003 0 : *sz10 = 0;
1004 2 : return szPassword;
1005 : }
1006 0 : 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 : bool operator()(char const *a, char const *b) const
1028 : {
1029 : return strcmp(a, b) < 0;
1030 : }
1031 : };
1032 :
1033 : static int GDALPdfiumGetBlock(void *param, unsigned long position,
1034 : unsigned char *pBuf, unsigned long size)
1035 : {
1036 : VSILFILE *fp = static_cast<VSILFILE *>(param);
1037 : VSIFSeekL(fp, position, SEEK_SET);
1038 : 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 : 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 : if (doc)
1060 : *doc = nullptr;
1061 : if (page)
1062 : *page = nullptr;
1063 : if (pnPageCount)
1064 : *pnPageCount = 0;
1065 :
1066 : // Loading document and page must be only in one thread!
1067 : CPLCreateOrAcquireMutex(&g_oPdfiumLoadDocMutex, PDFIUM_MUTEX_TIMEOUT);
1068 :
1069 : // Library can be destroyed if every PDF dataset was closed!
1070 : if (!PDFDataset::g_bPdfiumInit)
1071 : {
1072 : FPDF_InitLibrary();
1073 : PDFDataset::g_bPdfiumInit = TRUE;
1074 : }
1075 :
1076 : TMapPdfiumDatasets::iterator it;
1077 : it = g_mPdfiumDatasets.find(pszFilename);
1078 : TPdfiumDocumentStruct *poDoc = nullptr;
1079 : // Load new document if missing
1080 : if (it == g_mPdfiumDatasets.end())
1081 : {
1082 : // Try without password (if PDF not requires password it can fail)
1083 :
1084 : VSILFILE *fp = VSIFOpenL(pszFilename, "rb");
1085 : if (fp == nullptr)
1086 : {
1087 : CPLReleaseMutex(g_oPdfiumLoadDocMutex);
1088 : return FALSE;
1089 : }
1090 : VSIFSeekL(fp, 0, SEEK_END);
1091 : const auto nFileLen64 = VSIFTellL(fp);
1092 : if constexpr (LONG_MAX < std::numeric_limits<vsi_l_offset>::max())
1093 : {
1094 : if (nFileLen64 > LONG_MAX)
1095 : {
1096 : VSIFCloseL(fp);
1097 : CPLReleaseMutex(g_oPdfiumLoadDocMutex);
1098 : return FALSE;
1099 : }
1100 : }
1101 :
1102 : FPDF_FILEACCESS *psFileAccess = new FPDF_FILEACCESS;
1103 : psFileAccess->m_Param = fp;
1104 : psFileAccess->m_FileLen = static_cast<unsigned long>(nFileLen64);
1105 : psFileAccess->m_GetBlock = GDALPdfiumGetBlock;
1106 : CPDF_Document *docPdfium = CPDFDocumentFromFPDFDocument(
1107 : FPDF_LoadCustomDocument(psFileAccess, nullptr));
1108 : if (docPdfium == nullptr)
1109 : {
1110 : unsigned long err = FPDF_GetLastError();
1111 : if (err == FPDF_ERR_PASSWORD)
1112 : {
1113 : if (pszUserPwd)
1114 : {
1115 : pszUserPwd =
1116 : PDFEnterPasswordFromConsoleIfNeeded(pszUserPwd);
1117 : docPdfium = CPDFDocumentFromFPDFDocument(
1118 : FPDF_LoadCustomDocument(psFileAccess, pszUserPwd));
1119 : if (docPdfium == nullptr)
1120 : err = FPDF_GetLastError();
1121 : else
1122 : err = FPDF_ERR_SUCCESS;
1123 : }
1124 : else
1125 : {
1126 : 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 : VSIFCloseL(fp);
1133 : delete psFileAccess;
1134 : CPLReleaseMutex(g_oPdfiumLoadDocMutex);
1135 : return FALSE;
1136 : }
1137 : } // First Error Password [null password given]
1138 : if (err != FPDF_ERR_SUCCESS)
1139 : {
1140 : if (err == FPDF_ERR_PASSWORD)
1141 : CPLError(CE_Failure, CPLE_AppDefined,
1142 : "PDFium Invalid password.");
1143 : else if (err == FPDF_ERR_SECURITY)
1144 : CPLError(CE_Failure, CPLE_AppDefined,
1145 : "PDFium Unsupported security scheme.");
1146 : else if (err == FPDF_ERR_FORMAT)
1147 : CPLError(CE_Failure, CPLE_AppDefined,
1148 : "PDFium File not in PDF format or corrupted.");
1149 : else if (err == FPDF_ERR_FILE)
1150 : CPLError(CE_Failure, CPLE_AppDefined,
1151 : "PDFium File not found or could not be opened.");
1152 : else
1153 : CPLError(CE_Failure, CPLE_AppDefined,
1154 : "PDFium Unknown PDF error or invalid PDF.");
1155 :
1156 : VSIFCloseL(fp);
1157 : delete psFileAccess;
1158 : CPLReleaseMutex(g_oPdfiumLoadDocMutex);
1159 : return FALSE;
1160 : }
1161 : } // ~ wrong PDF or password required
1162 :
1163 : // Create new poDoc
1164 : poDoc = new TPdfiumDocumentStruct;
1165 : if (!poDoc)
1166 : {
1167 : CPLError(CE_Failure, CPLE_AppDefined,
1168 : "Not enough memory for Pdfium Document object");
1169 :
1170 : VSIFCloseL(fp);
1171 : delete psFileAccess;
1172 : CPLReleaseMutex(g_oPdfiumLoadDocMutex);
1173 : return FALSE;
1174 : }
1175 : poDoc->filename = CPLStrdup(pszFilename);
1176 : poDoc->doc = docPdfium;
1177 : poDoc->psFileAccess = psFileAccess;
1178 :
1179 : g_mPdfiumDatasets[poDoc->filename] = poDoc;
1180 : }
1181 : // Document already loaded
1182 : else
1183 : {
1184 : poDoc = it->second;
1185 : }
1186 :
1187 : // Check page num in document
1188 : int nPages = poDoc->doc->GetPageCount();
1189 : if (pageNum < 1 || pageNum > nPages)
1190 : {
1191 : CPLError(CE_Failure, CPLE_AppDefined,
1192 : "PDFium Invalid page number (%d/%d) for document %s", pageNum,
1193 : nPages, pszFilename);
1194 :
1195 : CPLReleaseMutex(g_oPdfiumLoadDocMutex);
1196 : return FALSE;
1197 : }
1198 :
1199 : /* Sanity check to validate page count */
1200 : if (pageNum != nPages)
1201 : {
1202 : if (poDoc->doc->GetPageDictionary(nPages - 1) == nullptr)
1203 : {
1204 : CPLError(CE_Failure, CPLE_AppDefined,
1205 : "Invalid PDF : invalid page count");
1206 : CPLReleaseMutex(g_oPdfiumLoadDocMutex);
1207 : return FALSE;
1208 : }
1209 : }
1210 :
1211 : TMapPdfiumPages::iterator itPage;
1212 : itPage = poDoc->pages.find(pageNum);
1213 : TPdfiumPageStruct *poPage = nullptr;
1214 : // Page not loaded
1215 : if (itPage == poDoc->pages.end())
1216 : {
1217 : auto pDict = poDoc->doc->GetMutablePageDictionary(pageNum - 1);
1218 : if (pDict == nullptr)
1219 : {
1220 : CPLError(CE_Failure, CPLE_AppDefined,
1221 : "Invalid PDFium : invalid page");
1222 :
1223 : CPLReleaseMutex(g_oPdfiumLoadDocMutex);
1224 : return FALSE;
1225 : }
1226 : auto pPage = pdfium::MakeRetain<CPDF_Page>(poDoc->doc, pDict);
1227 :
1228 : poPage = new TPdfiumPageStruct;
1229 : if (!poPage)
1230 : {
1231 : CPLError(CE_Failure, CPLE_AppDefined,
1232 : "Not enough memory for Pdfium Page object");
1233 :
1234 : CPLReleaseMutex(g_oPdfiumLoadDocMutex);
1235 : return FALSE;
1236 : }
1237 : poPage->pageNum = pageNum;
1238 : poPage->page = pPage.Leak();
1239 : poPage->readMutex = nullptr;
1240 : poPage->sharedNum = 0;
1241 :
1242 : poDoc->pages[pageNum] = poPage;
1243 : }
1244 : // Page already loaded
1245 : else
1246 : {
1247 : poPage = itPage->second;
1248 : }
1249 :
1250 : // Increase number of used
1251 : ++poPage->sharedNum;
1252 :
1253 : if (doc)
1254 : *doc = poDoc;
1255 : if (page)
1256 : *page = poPage;
1257 : if (pnPageCount)
1258 : *pnPageCount = nPages;
1259 :
1260 : CPLReleaseMutex(g_oPdfiumLoadDocMutex);
1261 :
1262 : return TRUE;
1263 : }
1264 :
1265 : // ~ static int LoadPdfiumDocumentPage()
1266 :
1267 : static int UnloadPdfiumDocumentPage(TPdfiumDocumentStruct **doc,
1268 : TPdfiumPageStruct **page)
1269 : {
1270 : if (!doc || !page)
1271 : return FALSE;
1272 :
1273 : TPdfiumPageStruct *pPage = *page;
1274 : TPdfiumDocumentStruct *pDoc = *doc;
1275 :
1276 : // Get mutex for loading pdfium
1277 : CPLCreateOrAcquireMutex(&g_oPdfiumLoadDocMutex, PDFIUM_MUTEX_TIMEOUT);
1278 :
1279 : // Decrease page use
1280 : --pPage->sharedNum;
1281 :
1282 : #ifdef DEBUG
1283 : CPLDebug("PDF", "PDFDataset::UnloadPdfiumDocumentPage: page shared num %d",
1284 : pPage->sharedNum);
1285 : #endif
1286 : // Page is used (also document)
1287 : if (pPage->sharedNum != 0)
1288 : {
1289 : CPLReleaseMutex(g_oPdfiumLoadDocMutex);
1290 : return TRUE;
1291 : }
1292 :
1293 : // Get mutex, release and destroy it
1294 : CPLCreateOrAcquireMutex(&(pPage->readMutex), PDFIUM_MUTEX_TIMEOUT);
1295 : CPLReleaseMutex(pPage->readMutex);
1296 : CPLDestroyMutex(pPage->readMutex);
1297 : // Close page and remove from map
1298 : FPDF_ClosePage(FPDFPageFromIPDFPage(pPage->page));
1299 :
1300 : pDoc->pages.erase(pPage->pageNum);
1301 : delete pPage;
1302 : pPage = nullptr;
1303 :
1304 : #ifdef DEBUG
1305 : CPLDebug("PDF", "PDFDataset::UnloadPdfiumDocumentPage: pages %lu",
1306 : pDoc->pages.size());
1307 : #endif
1308 : // Another page is used
1309 : if (!pDoc->pages.empty())
1310 : {
1311 : CPLReleaseMutex(g_oPdfiumLoadDocMutex);
1312 : return TRUE;
1313 : }
1314 :
1315 : // Close document and remove from map
1316 : FPDF_CloseDocument(FPDFDocumentFromCPDFDocument(pDoc->doc));
1317 : g_mPdfiumDatasets.erase(pDoc->filename);
1318 : CPLFree(pDoc->filename);
1319 : VSIFCloseL(static_cast<VSILFILE *>(pDoc->psFileAccess->m_Param));
1320 : delete pDoc->psFileAccess;
1321 : delete pDoc;
1322 : pDoc = nullptr;
1323 :
1324 : #ifdef DEBUG
1325 : CPLDebug("PDF", "PDFDataset::UnloadPdfiumDocumentPage: documents %lu",
1326 : g_mPdfiumDatasets.size());
1327 : #endif
1328 : // Another document is used
1329 : if (!g_mPdfiumDatasets.empty())
1330 : {
1331 : CPLReleaseMutex(g_oPdfiumLoadDocMutex);
1332 : return TRUE;
1333 : }
1334 :
1335 : #ifdef DEBUG
1336 : CPLDebug("PDF", "PDFDataset::UnloadPdfiumDocumentPage: Nothing loaded, "
1337 : "destroy Library");
1338 : #endif
1339 : // No document loaded, destroy pdfium
1340 : FPDF_DestroyLibrary();
1341 : PDFDataset::g_bPdfiumInit = FALSE;
1342 :
1343 : CPLReleaseMutex(g_oPdfiumLoadDocMutex);
1344 :
1345 : return TRUE;
1346 : }
1347 :
1348 : // ~ static int UnloadPdfiumDocumentPage()
1349 :
1350 : #endif // ~ HAVE_PDFIUM
1351 :
1352 : /************************************************************************/
1353 : /* GetOption() */
1354 : /************************************************************************/
1355 :
1356 1151 : const char *PDFDataset::GetOption(char **papszOpenOptionsIn,
1357 : const char *pszOptionName,
1358 : const char *pszDefaultVal)
1359 : {
1360 1151 : CPLErr eLastErrType = CPLGetLastErrorType();
1361 1151 : CPLErrorNum nLastErrno = CPLGetLastErrorNo();
1362 2302 : CPLString osLastErrorMsg(CPLGetLastErrorMsg());
1363 1151 : CPLXMLNode *psNode = CPLParseXMLString(PDFGetOpenOptionList());
1364 1151 : CPLErrorSetState(eLastErrType, nLastErrno, osLastErrorMsg);
1365 1151 : if (psNode == nullptr)
1366 0 : return pszDefaultVal;
1367 1151 : CPLXMLNode *psIter = psNode->psChild;
1368 4736 : while (psIter != nullptr)
1369 : {
1370 4736 : if (EQUAL(CPLGetXMLValue(psIter, "name", ""), pszOptionName))
1371 : {
1372 : const char *pszVal =
1373 1151 : CSLFetchNameValue(papszOpenOptionsIn, pszOptionName);
1374 1151 : if (pszVal != nullptr)
1375 : {
1376 20 : CPLDestroyXMLNode(psNode);
1377 20 : return pszVal;
1378 : }
1379 : const char *pszAltConfigOption =
1380 1131 : CPLGetXMLValue(psIter, "alt_config_option", nullptr);
1381 1131 : if (pszAltConfigOption != nullptr)
1382 : {
1383 1131 : pszVal = CPLGetConfigOption(pszAltConfigOption, pszDefaultVal);
1384 1131 : CPLDestroyXMLNode(psNode);
1385 1131 : return pszVal;
1386 : }
1387 0 : CPLDestroyXMLNode(psNode);
1388 0 : return pszDefaultVal;
1389 : }
1390 3585 : 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 final : 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 : GDALPDFiumOCContext(PDFDataset *poDS, CPDF_Document *pDoc,
1413 : CPDF_OCContext::UsageType usage)
1414 : : m_poDS(poDS),
1415 : m_DefaultOCContext(pdfium::MakeRetain<CPDF_OCContext>(pDoc, usage))
1416 : {
1417 : }
1418 :
1419 : virtual bool
1420 : CheckOCGDictVisible(const CPDF_Dictionary *pOCGDict) const override
1421 : {
1422 : // CPLDebug("PDF", "CheckOCGDictVisible(%d,%d)",
1423 : // pOCGDict->GetObjNum(), pOCGDict->GetGenNum() );
1424 : PDFDataset::VisibilityState eVisibility =
1425 : m_poDS->GetVisibilityStateForOGCPdfium(pOCGDict->GetObjNum(),
1426 : pOCGDict->GetGenNum());
1427 : if (eVisibility == PDFDataset::VISIBILITY_ON)
1428 : return true;
1429 : if (eVisibility == PDFDataset::VISIBILITY_OFF)
1430 : return false;
1431 : return m_DefaultOCContext->CheckOCGDictVisible(pOCGDict);
1432 : }
1433 : };
1434 :
1435 : /************************************************************************/
1436 : /* GDALPDFiumRenderDeviceDriver */
1437 : /************************************************************************/
1438 :
1439 : class GDALPDFiumRenderDeviceDriver final : public RenderDeviceDriverIface
1440 : {
1441 : std::unique_ptr<RenderDeviceDriverIface> m_poParent;
1442 : CFX_RenderDevice *device_;
1443 :
1444 : int bEnableVector;
1445 : int bEnableText;
1446 : int bEnableBitmap;
1447 : int bTemporaryEnableVectorForTextStroking;
1448 :
1449 : CPL_DISALLOW_COPY_ASSIGN(GDALPDFiumRenderDeviceDriver)
1450 :
1451 : public:
1452 : GDALPDFiumRenderDeviceDriver(
1453 : std::unique_ptr<RenderDeviceDriverIface> &&poParent,
1454 : CFX_RenderDevice *pDevice)
1455 : : m_poParent(std::move(poParent)), device_(pDevice),
1456 : bEnableVector(TRUE), bEnableText(TRUE), bEnableBitmap(TRUE),
1457 : bTemporaryEnableVectorForTextStroking(FALSE)
1458 : {
1459 : }
1460 :
1461 : virtual ~GDALPDFiumRenderDeviceDriver() = default;
1462 :
1463 : void SetEnableVector(int bFlag)
1464 : {
1465 : bEnableVector = bFlag;
1466 : }
1467 :
1468 : void SetEnableText(int bFlag)
1469 : {
1470 : bEnableText = bFlag;
1471 : }
1472 :
1473 : void SetEnableBitmap(int bFlag)
1474 : {
1475 : bEnableBitmap = bFlag;
1476 : }
1477 :
1478 : DeviceType GetDeviceType() const override
1479 : {
1480 : return m_poParent->GetDeviceType();
1481 : }
1482 :
1483 : int GetDeviceCaps(int caps_id) const override
1484 : {
1485 : return m_poParent->GetDeviceCaps(caps_id);
1486 : }
1487 :
1488 : void SaveState() override
1489 : {
1490 : m_poParent->SaveState();
1491 : }
1492 :
1493 : void RestoreState(bool bKeepSaved) override
1494 : {
1495 : m_poParent->RestoreState(bKeepSaved);
1496 : }
1497 :
1498 : void SetBaseClip(const FX_RECT &rect) override
1499 : {
1500 : m_poParent->SetBaseClip(rect);
1501 : }
1502 :
1503 : virtual bool
1504 : SetClip_PathFill(const CFX_Path &path, const CFX_Matrix *pObject2Device,
1505 : const CFX_FillRenderOptions &fill_options) override
1506 : {
1507 : if (!bEnableVector && !bTemporaryEnableVectorForTextStroking)
1508 : return true;
1509 : return m_poParent->SetClip_PathFill(path, pObject2Device, fill_options);
1510 : }
1511 :
1512 : virtual bool
1513 : SetClip_PathStroke(const CFX_Path &path, const CFX_Matrix *pObject2Device,
1514 : const CFX_GraphStateData *pGraphState) override
1515 : {
1516 : if (!bEnableVector && !bTemporaryEnableVectorForTextStroking)
1517 : return true;
1518 : return m_poParent->SetClip_PathStroke(path, pObject2Device,
1519 : pGraphState);
1520 : }
1521 :
1522 : 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 : if (!bEnableVector && !bTemporaryEnableVectorForTextStroking)
1529 : return true;
1530 : return m_poParent->DrawPath(path, pObject2Device, pGraphState,
1531 : fill_color, stroke_color, fill_options);
1532 : }
1533 :
1534 : bool FillRect(const FX_RECT &rect, uint32_t fill_color) override
1535 : {
1536 : return m_poParent->FillRect(rect, fill_color);
1537 : }
1538 :
1539 : virtual bool DrawCosmeticLine(const CFX_PointF &ptMoveTo,
1540 : const CFX_PointF &ptLineTo,
1541 : uint32_t color) override
1542 : {
1543 : if (!bEnableVector && !bTemporaryEnableVectorForTextStroking)
1544 : return TRUE;
1545 : return m_poParent->DrawCosmeticLine(ptMoveTo, ptLineTo, color);
1546 : }
1547 :
1548 : FX_RECT GetClipBox() const override
1549 : {
1550 : return m_poParent->GetClipBox();
1551 : }
1552 :
1553 : virtual bool GetDIBits(RetainPtr<CFX_DIBitmap> bitmap, int left,
1554 : int top) const override
1555 : {
1556 : return m_poParent->GetDIBits(std::move(bitmap), left, top);
1557 : }
1558 :
1559 : RetainPtr<const CFX_DIBitmap> GetBackDrop() const override
1560 : {
1561 : return m_poParent->GetBackDrop();
1562 : }
1563 :
1564 : 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 : if (!bEnableBitmap && !bTemporaryEnableVectorForTextStroking)
1569 : return true;
1570 : return m_poParent->SetDIBits(std::move(bitmap), color, src_rect,
1571 : dest_left, dest_top, blend_type);
1572 : }
1573 :
1574 : 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 : if (!bEnableBitmap && !bTemporaryEnableVectorForTextStroking)
1582 : return true;
1583 : return m_poParent->StretchDIBits(std::move(bitmap), color, dest_left,
1584 : dest_top, dest_width, dest_height,
1585 : pClipRect, options, blend_type);
1586 : }
1587 :
1588 : 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 : if (!bEnableBitmap && !bTemporaryEnableVectorForTextStroking)
1595 : return StartResult(Result::kSuccess, nullptr);
1596 : return m_poParent->StartDIBits(std::move(bitmap), alpha, color, matrix,
1597 : options, blend_type);
1598 : }
1599 :
1600 : virtual bool ContinueDIBits(CFX_AggImageRenderer *handle,
1601 : PauseIndicatorIface *pPause) override
1602 : {
1603 : return m_poParent->ContinueDIBits(handle, pPause);
1604 : }
1605 :
1606 : 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 : 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 : if (bTemporaryEnableVectorForTextStroking)
1619 : return FALSE; // this is the default behavior of the parent
1620 : bTemporaryEnableVectorForTextStroking = true;
1621 : bool bRet = device_->DrawNormalText(
1622 : pCharPos, pFont, font_size, mtObject2Device, color, options);
1623 : bTemporaryEnableVectorForTextStroking = FALSE;
1624 : return bRet;
1625 : }
1626 : else
1627 : return true; // pretend that we did the job
1628 : }
1629 :
1630 : int GetDriverType() const override
1631 : {
1632 : 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 : bool MultiplyAlpha(float alpha) override
1647 : {
1648 : return m_poParent->MultiplyAlpha(alpha);
1649 : }
1650 :
1651 : bool MultiplyAlphaMask(RetainPtr<const CFX_DIBitmap> mask) override
1652 : {
1653 : 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 : 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 : 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 : 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 : if (!pContext->options_)
1723 : pContext->options_ = std::make_unique<CPDF_RenderOptions>();
1724 :
1725 : auto &options = pContext->options_->GetOptions();
1726 : options.bClearType = !!(flags & FPDF_LCD_TEXT);
1727 : options.bNoNativeText = !!(flags & FPDF_NO_NATIVETEXT);
1728 : options.bLimitedImageCache = !!(flags & FPDF_RENDER_LIMITEDIMAGECACHE);
1729 : options.bForceHalftone = !!(flags & FPDF_RENDER_FORCEHALFTONE);
1730 : options.bNoTextSmooth = !!(flags & FPDF_RENDER_NO_SMOOTHTEXT);
1731 : options.bNoImageSmooth = !!(flags & FPDF_RENDER_NO_SMOOTHIMAGE);
1732 : options.bNoPathSmooth = !!(flags & FPDF_RENDER_NO_SMOOTHPATH);
1733 :
1734 : // Grayscale output
1735 : if (flags & FPDF_GRAYSCALE)
1736 : pContext->options_->SetColorMode(CPDF_RenderOptions::kGray);
1737 :
1738 : if (color_scheme)
1739 : {
1740 : pContext->options_->SetColorMode(CPDF_RenderOptions::kForcedColor);
1741 : SetColorFromScheme(color_scheme, pContext->options_.get());
1742 : options.bConvertFillToStroke = !!(flags & FPDF_CONVERT_FILL_TO_STROKE);
1743 : }
1744 :
1745 : const CPDF_OCContext::UsageType usage = (flags & FPDF_PRINTING)
1746 : ? CPDF_OCContext::kPrint
1747 : : CPDF_OCContext::kView;
1748 : pContext->options_->SetOCContext(pdfium::MakeRetain<GDALPDFiumOCContext>(
1749 : poDS, pPage->GetDocument(), usage));
1750 :
1751 : pContext->device_->SaveState();
1752 : pContext->device_->SetBaseClip(clipping_rect);
1753 : pContext->device_->SetClip_Rect(clipping_rect);
1754 : pContext->context_ = std::make_unique<CPDF_RenderContext>(
1755 : pPage->GetDocument(), pPage->GetMutablePageResources(),
1756 : pPage->GetPageImageCache());
1757 :
1758 : pContext->context_->AppendLayer(pPage, matrix);
1759 :
1760 : if (flags & FPDF_ANNOT)
1761 : {
1762 : auto pOwnedList = std::make_unique<CPDF_AnnotList>(pPage);
1763 : CPDF_AnnotList *pList = pOwnedList.get();
1764 : pContext->annots_ = std::move(pOwnedList);
1765 : bool bPrinting =
1766 : pContext->device_->GetDeviceType() != DeviceType::kDisplay;
1767 :
1768 : // TODO(https://crbug.com/pdfium/993) - maybe pass true here.
1769 : const bool bShowWidget = false;
1770 : pList->DisplayAnnots(pContext->context_.get(), bPrinting, matrix,
1771 : bShowWidget);
1772 : }
1773 :
1774 : pContext->renderer_ = std::make_unique<CPDF_ProgressiveRenderer>(
1775 : pContext->context_.get(), pContext->device_.get(),
1776 : pContext->options_.get());
1777 : pContext->renderer_->Start(pause);
1778 : if (bNeedToRestore)
1779 : pContext->device_->RestoreState(false);
1780 : }
1781 :
1782 : static void
1783 : 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 : CPDF_Page *pPage = CPDFPageFromFPDFPage(page);
1790 : if (!pPage)
1791 : return;
1792 :
1793 : const FX_RECT rect(start_x, start_y, start_x + size_x, start_y + size_y);
1794 : myRenderPageImpl(poDS, pContext, pPage,
1795 : pPage->GetDisplayMatrixForRect(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 : 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 : SetBitmap(pBitmap);
1816 :
1817 : std::unique_ptr<RenderDeviceDriverIface> driver =
1818 : std::make_unique<pdfium::CFX_AggDeviceDriver>(
1819 : pBitmap, bRgbByteOrder, pBackdropBitmap, bGroupKnockout);
1820 : if (pszRenderingOptions != nullptr)
1821 : {
1822 : int bEnableVector = FALSE;
1823 : int bEnableText = FALSE;
1824 : int bEnableBitmap = FALSE;
1825 :
1826 : char **papszTokens = CSLTokenizeString2(pszRenderingOptions, " ,", 0);
1827 : for (int i = 0; papszTokens[i] != nullptr; i++)
1828 : {
1829 : if (EQUAL(papszTokens[i], "VECTOR"))
1830 : bEnableVector = TRUE;
1831 : else if (EQUAL(papszTokens[i], "TEXT"))
1832 : bEnableText = TRUE;
1833 : else if (EQUAL(papszTokens[i], "RASTER") ||
1834 : EQUAL(papszTokens[i], "BITMAP"))
1835 : bEnableBitmap = TRUE;
1836 : else
1837 : {
1838 : CPLError(CE_Warning, CPLE_NotSupported,
1839 : "Value %s is not a valid value for "
1840 : "GDAL_PDF_RENDERING_OPTIONS",
1841 : papszTokens[i]);
1842 : }
1843 : }
1844 : CSLDestroy(papszTokens);
1845 :
1846 : if (!bEnableVector || !bEnableText || !bEnableBitmap)
1847 : {
1848 : std::unique_ptr<GDALPDFiumRenderDeviceDriver> poGDALRDDriver =
1849 : std::make_unique<GDALPDFiumRenderDeviceDriver>(
1850 : std::move(driver), this);
1851 : poGDALRDDriver->SetEnableVector(bEnableVector);
1852 : poGDALRDDriver->SetEnableText(bEnableText);
1853 : poGDALRDDriver->SetEnableBitmap(bEnableBitmap);
1854 : driver = std::move(poGDALRDDriver);
1855 : }
1856 : }
1857 :
1858 : SetDeviceDriver(std::move(driver));
1859 : return true;
1860 : }
1861 :
1862 : 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 : const int rotate = 0;
1868 : const int flags = 0;
1869 :
1870 : if (!bitmap)
1871 : return;
1872 :
1873 : CPDF_Page *pPage = CPDFPageFromFPDFPage(page);
1874 : if (!pPage)
1875 : return;
1876 :
1877 : auto pOwnedContext = std::make_unique<CPDF_PageRenderContext>();
1878 : CPDF_PageRenderContext *pContext = pOwnedContext.get();
1879 : CPDF_Page::RenderContextClearer clearer(pPage);
1880 : pPage->SetRenderContext(std::move(pOwnedContext));
1881 :
1882 : auto pOwnedDevice = std::make_unique<MyRenderDevice>();
1883 : auto pDevice = pOwnedDevice.get();
1884 : pContext->device_ = std::move(pOwnedDevice);
1885 :
1886 : RetainPtr<CFX_DIBitmap> pBitmap(CFXDIBitmapFromFPDFBitmap(bitmap));
1887 :
1888 : pDevice->Attach(pBitmap, !!(flags & FPDF_REVERSE_BYTE_ORDER), nullptr,
1889 : false, pszRenderingOptions);
1890 :
1891 : 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 56 : CPLErr PDFDataset::ReadPixels(int nReqXOff, int nReqYOff, int nReqXSize,
1909 : int nReqYSize, GSpacing nPixelSpace,
1910 : GSpacing nLineSpace, GSpacing nBandSpace,
1911 : GByte *pabyData)
1912 : {
1913 56 : CPLErr eErr = CE_None;
1914 : const char *pszRenderingOptions =
1915 56 : GetOption(papszOpenOptions, "RENDERING_OPTIONS", nullptr);
1916 :
1917 : #ifdef HAVE_POPPLER
1918 56 : if (m_bUseLib.test(PDFLIB_POPPLER))
1919 : {
1920 : SplashColor sColor;
1921 56 : sColor[0] = 255;
1922 56 : sColor[1] = 255;
1923 56 : sColor[2] = 255;
1924 : GDALPDFOutputDev *poSplashOut = new GDALPDFOutputDev(
1925 56 : (nBands < 4) ? splashModeRGB8 : splashModeXBGR8, 4, false,
1926 56 : (nBands < 4) ? sColor : nullptr);
1927 :
1928 56 : 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 56 : PDFDoc *poDoc = m_poDocPoppler;
1957 56 : 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 56 : Catalog *poCatalog = poDoc->getCatalog();
1978 56 : OCGs *poOldOCGs = poCatalog->optContent;
1979 56 : if (!m_bUseOCG)
1980 49 : poCatalog->optContent = nullptr;
1981 : #endif
1982 : try
1983 : {
1984 56 : 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 56 : poCatalog->optContent = poOldOCGs;
2004 : #endif
2005 :
2006 56 : SplashBitmap *poBitmap = poSplashOut->getBitmap();
2007 112 : if (poBitmap->getWidth() != nReqXSize ||
2008 56 : 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 56 : GByte *pabyDataR = pabyData;
2020 56 : GByte *pabyDataG = pabyData + nBandSpace;
2021 56 : GByte *pabyDataB = pabyData + 2 * nBandSpace;
2022 56 : GByte *pabyDataA = pabyData + 3 * nBandSpace;
2023 56 : GByte *pabySrc = poBitmap->getDataPtr();
2024 : GByte *pabyAlphaSrc =
2025 56 : reinterpret_cast<GByte *>(poBitmap->getAlphaPtr());
2026 : int i, j;
2027 22919 : for (j = 0; j < nReqYSize; j++)
2028 : {
2029 20751600 : for (i = 0; i < nReqXSize; i++)
2030 : {
2031 20728800 : if (nBands < 4)
2032 : {
2033 20680200 : pabyDataR[i * nPixelSpace] = pabySrc[i * 3 + 0];
2034 20680200 : pabyDataG[i * nPixelSpace] = pabySrc[i * 3 + 1];
2035 20680200 : 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 22863 : pabyDataR += nLineSpace;
2046 22863 : pabyDataG += nLineSpace;
2047 22863 : pabyDataB += nLineSpace;
2048 22863 : pabyDataA += nLineSpace;
2049 22863 : pabyAlphaSrc += poBitmap->getAlphaRowSize();
2050 22863 : pabySrc += poBitmap->getRowSize();
2051 : }
2052 56 : 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 : if (m_bUseLib.test(PDFLIB_PDFIUM))
2163 : {
2164 : if (!m_poPagePdfium)
2165 : {
2166 : return CE_Failure;
2167 : }
2168 :
2169 : // Pdfium does not support multithreading
2170 : CPLCreateOrAcquireMutex(&g_oPdfiumReadMutex, PDFIUM_MUTEX_TIMEOUT);
2171 :
2172 : 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 : m_poPagePdfium->page->ParseContent();
2178 :
2179 : FPDF_BITMAP bitmap =
2180 : FPDFBitmap_Create(nReqXSize, nReqYSize, nBands == 4 /*alpha*/);
2181 : // As coded now, FPDFBitmap_Create cannot allocate more than 1 GB
2182 : if (bitmap == nullptr)
2183 : {
2184 : // Release mutex - following code is thread-safe
2185 : CPLReleaseMutex(m_poPagePdfium->readMutex);
2186 : 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 : CPLError(CE_Failure, CPLE_AppDefined,
2232 : "FPDFBitmap_Create(%d,%d) failed", nReqXSize, nReqYSize);
2233 :
2234 : return CE_Failure;
2235 : }
2236 : // alpha is 0% which is transported to FF if not alpha
2237 : // Default background color is white
2238 : FPDF_DWORD color = 0x00FFFFFF; // A,R,G,B
2239 : FPDFBitmap_FillRect(bitmap, 0, 0, nReqXSize, nReqYSize, color);
2240 :
2241 : #ifdef DEBUG
2242 : // start_x, start_y, size_x, size_y, rotate, flags
2243 : CPLDebug("PDF",
2244 : "PDFDataset::ReadPixels(%d, %d, %d, %d, scaleFactor=%d)",
2245 : nReqXOff, nReqYOff, nReqXSize, nReqYSize,
2246 : 1 << cpl::down_cast<PDFRasterBand *>(GetRasterBand(1))
2247 : ->nResolutionLevel);
2248 :
2249 : 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 : PDFiumRenderPageBitmap(
2256 : bitmap, FPDFPageFromIPDFPage(m_poPagePdfium->page), -nReqXOff,
2257 : -nReqYOff, nRasterXSize, nRasterYSize, pszRenderingOptions);
2258 :
2259 : int stride = FPDFBitmap_GetStride(bitmap);
2260 : const GByte *buffer =
2261 : reinterpret_cast<const GByte *>(FPDFBitmap_GetBuffer(bitmap));
2262 :
2263 : // Release mutex - following code is thread-safe
2264 : CPLReleaseMutex(m_poPagePdfium->readMutex);
2265 : CPLReleaseMutex(g_oPdfiumReadMutex);
2266 :
2267 : // Source data is B, G, R, unused.
2268 : // Destination data is R, G, B (,A if is alpha)
2269 : GByte *pabyDataR = pabyData;
2270 : GByte *pabyDataG = pabyData + 1 * nBandSpace;
2271 : GByte *pabyDataB = pabyData + 2 * nBandSpace;
2272 : GByte *pabyDataA = pabyData + 3 * nBandSpace;
2273 : // Copied from Poppler
2274 : int i, j;
2275 : for (j = 0; j < nReqYSize; j++)
2276 : {
2277 : for (i = 0; i < nReqXSize; i++)
2278 : {
2279 : pabyDataR[i * nPixelSpace] = buffer[(i * 4) + 2];
2280 : pabyDataG[i * nPixelSpace] = buffer[(i * 4) + 1];
2281 : pabyDataB[i * nPixelSpace] = buffer[(i * 4) + 0];
2282 : if (nBands == 4)
2283 : {
2284 : pabyDataA[i * nPixelSpace] = buffer[(i * 4) + 3];
2285 : }
2286 : }
2287 : pabyDataR += nLineSpace;
2288 : pabyDataG += nLineSpace;
2289 : pabyDataB += nLineSpace;
2290 : pabyDataA += nLineSpace;
2291 : buffer += stride;
2292 : }
2293 : FPDFBitmap_Destroy(bitmap);
2294 : }
2295 : #endif // ~ HAVE_PDFIUM
2296 :
2297 56 : 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 : 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 214 : PDFDataset::PDFDataset(PDFDataset *poParentDSIn, int nXSize, int nYSize)
2404 214 : : m_bIsOvrDS(poParentDSIn != nullptr),
2405 : #ifdef HAVE_PDFIUM
2406 : m_poDocPdfium(poParentDSIn ? poParentDSIn->m_poDocPdfium : nullptr),
2407 : m_poPagePdfium(poParentDSIn ? poParentDSIn->m_poPagePdfium : nullptr),
2408 : #endif
2409 214 : m_bSetStyle(CPLTestBool(CPLGetConfigOption("OGR_PDF_SET_STYLE", "YES")))
2410 : {
2411 214 : m_oSRS.SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER);
2412 214 : nRasterXSize = nXSize;
2413 214 : nRasterYSize = nYSize;
2414 214 : if (poParentDSIn)
2415 0 : m_bUseLib = poParentDSIn->m_bUseLib;
2416 :
2417 214 : InitMapOperators();
2418 214 : }
2419 :
2420 : /************************************************************************/
2421 : /* IBuildOverviews() */
2422 : /************************************************************************/
2423 :
2424 1 : 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 1 : if (!m_apoOvrDS.empty())
2438 : {
2439 1 : m_apoOvrDSBackup = std::move(m_apoOvrDS);
2440 1 : m_apoOvrDS.clear();
2441 : }
2442 :
2443 : // Prevents InitOverviews() to run
2444 1 : m_apoOvrDSBackup.emplace_back(nullptr);
2445 1 : const CPLErr eErr = GDALPamDataset::IBuildOverviews(
2446 : pszResampling, nOverviews, panOverviewList, nListBands, panBandList,
2447 : pfnProgress, pProgressData, papszOptions);
2448 1 : m_apoOvrDSBackup.pop_back();
2449 1 : return eErr;
2450 : }
2451 :
2452 : /************************************************************************/
2453 : /* PDFFreeDoc() */
2454 : /************************************************************************/
2455 :
2456 : #ifdef HAVE_POPPLER
2457 228 : static void PDFFreeDoc(PDFDoc *poDoc)
2458 : {
2459 228 : 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 228 : delete poDoc->str;
2467 228 : poDoc->str = nullptr;
2468 :
2469 228 : delete poDoc;
2470 : }
2471 228 : }
2472 : #endif
2473 :
2474 : /************************************************************************/
2475 : /* GetCatalog() */
2476 : /************************************************************************/
2477 :
2478 454 : GDALPDFObject *PDFDataset::GetCatalog()
2479 : {
2480 454 : if (m_poCatalogObject)
2481 240 : return m_poCatalogObject;
2482 :
2483 : #ifdef HAVE_POPPLER
2484 214 : if (m_bUseLib.test(PDFLIB_POPPLER) && m_poDocPoppler)
2485 : {
2486 : m_poCatalogObjectPoppler =
2487 214 : std::make_unique<Object>(m_poDocPoppler->getXRef()->getCatalog());
2488 214 : if (!m_poCatalogObjectPoppler->isNull())
2489 214 : m_poCatalogObject =
2490 214 : 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 : if (m_bUseLib.test(PDFLIB_PDFIUM) && m_poDocPdfium)
2522 : {
2523 : RetainPtr<CPDF_Dictionary> catalog =
2524 : m_poDocPdfium->doc->GetMutableRoot();
2525 : if (catalog)
2526 : m_poCatalogObject = GDALPDFObjectPdfium::Build(catalog);
2527 : }
2528 : #endif // ~ HAVE_PDFIUM
2529 :
2530 214 : return m_poCatalogObject;
2531 : }
2532 :
2533 : /************************************************************************/
2534 : /* ~PDFDataset() */
2535 : /************************************************************************/
2536 :
2537 428 : PDFDataset::~PDFDataset()
2538 : {
2539 : #ifdef HAVE_PDFIUM
2540 : m_apoOvrDS.clear();
2541 : m_apoOvrDSBackup.clear();
2542 : #endif
2543 :
2544 214 : CPLFree(m_pabyCachedData);
2545 214 : m_pabyCachedData = nullptr;
2546 :
2547 214 : delete m_poNeatLine;
2548 214 : m_poNeatLine = nullptr;
2549 :
2550 : /* Collect data necessary to update */
2551 214 : int nNum = 0;
2552 214 : int nGen = 0;
2553 214 : GDALPDFDictionaryRW *poPageDictCopy = nullptr;
2554 214 : GDALPDFDictionaryRW *poCatalogDictCopy = nullptr;
2555 214 : if (m_poPageObj)
2556 : {
2557 214 : nNum = m_poPageObj->GetRefNum().toInt();
2558 214 : nGen = m_poPageObj->GetRefGen();
2559 440 : if (eAccess == GA_Update &&
2560 12 : (m_bProjDirty || m_bNeatLineDirty || m_bInfoDirty || m_bXMPDirty) &&
2561 238 : nNum != 0 && m_poPageObj != nullptr &&
2562 12 : m_poPageObj->GetType() == PDFObjectType_Dictionary)
2563 : {
2564 12 : poPageDictCopy = m_poPageObj->GetDictionary()->Clone();
2565 :
2566 12 : if (m_bXMPDirty)
2567 : {
2568 : /* We need the catalog because it points to the XMP Metadata
2569 : * object */
2570 3 : GetCatalog();
2571 6 : if (m_poCatalogObject &&
2572 3 : m_poCatalogObject->GetType() == PDFObjectType_Dictionary)
2573 : poCatalogDictCopy =
2574 3 : 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 214 : delete m_poPageObj;
2582 214 : m_poPageObj = nullptr;
2583 214 : delete m_poCatalogObject;
2584 214 : m_poCatalogObject = nullptr;
2585 : #ifdef HAVE_POPPLER
2586 214 : if (m_bUseLib.test(PDFLIB_POPPLER))
2587 : {
2588 214 : m_poCatalogObjectPoppler.reset();
2589 214 : PDFFreeDoc(m_poDocPoppler);
2590 : }
2591 214 : 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 : if (!m_bIsOvrDS)
2602 : {
2603 : if (m_bUseLib.test(PDFLIB_PDFIUM))
2604 : {
2605 : UnloadPdfiumDocumentPage(&m_poDocPdfium, &m_poPagePdfium);
2606 : }
2607 : }
2608 : m_poDocPdfium = nullptr;
2609 : m_poPagePdfium = nullptr;
2610 : #endif // ~ HAVE_PDFIUM
2611 :
2612 214 : m_bHasLoadedLayers = true;
2613 214 : m_apoLayers.clear();
2614 :
2615 : /* Now do the update */
2616 214 : if (poPageDictCopy)
2617 : {
2618 12 : VSILFILE *fp = VSIFOpenL(m_osFilename, "rb+");
2619 12 : if (fp != nullptr)
2620 : {
2621 24 : GDALPDFUpdateWriter oWriter(fp);
2622 12 : if (oWriter.ParseTrailerAndXRef())
2623 : {
2624 12 : if ((m_bProjDirty || m_bNeatLineDirty) &&
2625 : poPageDictCopy != nullptr)
2626 6 : oWriter.UpdateProj(this, m_dfDPI, poPageDictCopy,
2627 12 : GDALPDFObjectNum(nNum), nGen);
2628 :
2629 12 : if (m_bInfoDirty)
2630 3 : oWriter.UpdateInfo(this);
2631 :
2632 12 : if (m_bXMPDirty && poCatalogDictCopy != nullptr)
2633 3 : oWriter.UpdateXMP(this, poCatalogDictCopy);
2634 : }
2635 12 : 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 214 : delete poPageDictCopy;
2644 214 : poPageDictCopy = nullptr;
2645 214 : delete poCatalogDictCopy;
2646 214 : poCatalogDictCopy = nullptr;
2647 :
2648 214 : if (m_nGCPCount > 0)
2649 : {
2650 1 : GDALDeinitGCPs(m_nGCPCount, m_pasGCPList);
2651 1 : CPLFree(m_pasGCPList);
2652 1 : m_pasGCPList = nullptr;
2653 1 : m_nGCPCount = 0;
2654 : }
2655 :
2656 214 : CleanupIntermediateResources();
2657 :
2658 : // Do that only after having destroyed Poppler objects
2659 214 : m_fp.reset();
2660 428 : }
2661 :
2662 : /************************************************************************/
2663 : /* IRasterIO() */
2664 : /************************************************************************/
2665 :
2666 1671 : 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 1671 : 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 1671 : int bReadPixels = FALSE;
2688 1671 : GetRasterBand(1)->GetBlockSize(&nBandBlockXSize, &nBandBlockYSize);
2689 3342 : if (m_aiTiles.empty() && eRWFlag == GF_Read && nXSize == nBufXSize &&
2690 1671 : nYSize == nBufYSize &&
2691 1671 : (nBufXSize > nBandBlockXSize || nBufYSize > nBandBlockYSize) &&
2692 3343 : eBufType == GDT_Byte && nBandCount == nBands &&
2693 1 : IsAllBands(nBandCount, panBandMap))
2694 : {
2695 1 : 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 1671 : if (bReadPixels)
2705 1 : return ReadPixels(nXOff, nYOff, nXSize, nYSize, nPixelSpace, nLineSpace,
2706 1 : nBandSpace, static_cast<GByte *>(pData));
2707 :
2708 1670 : if (nBufXSize != nXSize || nBufYSize != nYSize || eBufType != GDT_Byte)
2709 : {
2710 0 : m_bCacheBlocksForOtherBands = true;
2711 : }
2712 1670 : CPLErr eErr = GDALPamDataset::IRasterIO(
2713 : eRWFlag, nXOff, nYOff, nXSize, nYSize, pData, nBufXSize, nBufYSize,
2714 : eBufType, nBandCount, panBandMap, nPixelSpace, nLineSpace, nBandSpace,
2715 : psExtraArg);
2716 1670 : m_bCacheBlocksForOtherBands = false;
2717 1670 : return eErr;
2718 : }
2719 :
2720 : /************************************************************************/
2721 : /* IRasterIO() */
2722 : /************************************************************************/
2723 :
2724 25684 : 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 25684 : PDFDataset *poGDS = cpl::down_cast<PDFDataset *>(poDS);
2732 :
2733 : // Try to pass the request to the most appropriate overview dataset.
2734 25684 : 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 25684 : if (nBufXSize != nXSize || nBufYSize != nYSize || eBufType != GDT_Byte)
2745 : {
2746 20674 : poGDS->m_bCacheBlocksForOtherBands = true;
2747 : }
2748 25684 : CPLErr eErr = GDALPamRasterBand::IRasterIO(
2749 : eRWFlag, nXOff, nYOff, nXSize, nYSize, pData, nBufXSize, nBufYSize,
2750 : eBufType, nPixelSpace, nLineSpace, psExtraArg);
2751 25684 : poGDS->m_bCacheBlocksForOtherBands = false;
2752 25684 : return eErr;
2753 : }
2754 :
2755 : /************************************************************************/
2756 : /* PDFDatasetErrorFunction() */
2757 : /************************************************************************/
2758 :
2759 : #ifdef HAVE_POPPLER
2760 :
2761 29 : static void PDFDatasetErrorFunctionCommon(const CPLString &osError)
2762 : {
2763 29 : if (strcmp(osError.c_str(), "Incorrect password") == 0)
2764 5 : return;
2765 : /* Reported on newer USGS GeoPDF */
2766 24 : if (strcmp(osError.c_str(),
2767 24 : "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 24 : 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 29 : static void PDFDatasetErrorFunction(ErrorCategory /* eErrCategory */,
2780 : Goffset nPos, const char *pszMsg)
2781 : {
2782 29 : 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 29 : g_nPopplerErrors++;
2793 58 : CPLString osError;
2794 :
2795 29 : if (nPos >= 0)
2796 : osError.Printf("Pos = " CPL_FRMT_GUIB ", ",
2797 0 : static_cast<GUIntBig>(nPos));
2798 29 : osError += pszMsg;
2799 29 : PDFDatasetErrorFunctionCommon(osError);
2800 : }
2801 : #endif
2802 :
2803 : /************************************************************************/
2804 : /* GDALPDFParseStreamContentOnlyDrawForm() */
2805 : /************************************************************************/
2806 :
2807 197 : static CPLString GDALPDFParseStreamContentOnlyDrawForm(const char *pszContent)
2808 : {
2809 394 : CPLString osToken;
2810 : char ch;
2811 197 : int nCurIdx = 0;
2812 394 : CPLString osCurrentForm;
2813 :
2814 : // CPLDebug("PDF", "content = %s", pszContent);
2815 :
2816 722 : while ((ch = *pszContent) != '\0')
2817 : {
2818 722 : 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 722 : else if (ch == ' ' || ch == '\r' || ch == '\n')
2831 : {
2832 234 : if (!osToken.empty())
2833 : {
2834 234 : if (nCurIdx == 0 && osToken[0] == '/')
2835 : {
2836 37 : osCurrentForm = osToken.substr(1);
2837 37 : nCurIdx++;
2838 : }
2839 197 : else if (nCurIdx == 1 && osToken == "Do")
2840 : {
2841 0 : nCurIdx++;
2842 : }
2843 : else
2844 : {
2845 197 : return "";
2846 : }
2847 : }
2848 37 : osToken = "";
2849 : }
2850 : else
2851 488 : osToken += ch;
2852 525 : 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 197 : 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 394 : CPLString osToken;
2890 : char ch;
2891 197 : PDFStreamState nState = STATE_INIT;
2892 197 : int nCurIdx = 0;
2893 : double adfVals[6];
2894 394 : CPLString osCurrentImage;
2895 :
2896 197 : double dfDPI = DEFAULT_DPI;
2897 197 : *pbDPISet = FALSE;
2898 :
2899 11224 : while ((ch = *pszContent) != '\0')
2900 : {
2901 11080 : 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 11080 : else if (ch == ' ' || ch == '\t' || ch == '\r' || ch == '\n')
2914 : {
2915 3342 : if (!osToken.empty())
2916 : {
2917 3342 : if (nState == STATE_INIT)
2918 : {
2919 352 : if (osToken == "q")
2920 : {
2921 299 : nState = STATE_AFTER_q;
2922 299 : nCurIdx = 0;
2923 : }
2924 53 : else if (osToken != "Q")
2925 53 : return FALSE;
2926 : }
2927 2990 : else if (nState == STATE_AFTER_q)
2928 : {
2929 2093 : if (osToken == "q")
2930 : {
2931 : // ignore
2932 : }
2933 2093 : else if (nCurIdx < 6)
2934 : {
2935 1794 : adfVals[nCurIdx++] = CPLAtof(osToken);
2936 : }
2937 299 : else if (nCurIdx == 6 && osToken == "cm")
2938 : {
2939 299 : nState = STATE_AFTER_cm;
2940 299 : nCurIdx = 0;
2941 : }
2942 : else
2943 0 : return FALSE;
2944 : }
2945 897 : else if (nState == STATE_AFTER_cm)
2946 : {
2947 598 : if (nCurIdx == 0 && osToken[0] == '/')
2948 : {
2949 299 : osCurrentImage = osToken.substr(1);
2950 : }
2951 299 : else if (osToken == "Do")
2952 : {
2953 299 : nState = STATE_AFTER_Do;
2954 : }
2955 : else
2956 0 : return FALSE;
2957 : }
2958 299 : else if (nState == STATE_AFTER_Do)
2959 : {
2960 299 : if (osToken == "Q")
2961 : {
2962 : GDALPDFObject *poImage =
2963 299 : poXObjectDict->Get(osCurrentImage);
2964 598 : if (poImage != nullptr &&
2965 299 : poImage->GetType() == PDFObjectType_Dictionary)
2966 : {
2967 : GDALPDFTileDesc sTile;
2968 : GDALPDFDictionary *poImageDict =
2969 299 : poImage->GetDictionary();
2970 299 : GDALPDFObject *poWidth = poImageDict->Get("Width");
2971 : GDALPDFObject *poHeight =
2972 299 : poImageDict->Get("Height");
2973 : GDALPDFObject *poColorSpace =
2974 299 : poImageDict->Get("ColorSpace");
2975 299 : GDALPDFObject *poSMask = poImageDict->Get("SMask");
2976 598 : if (poColorSpace &&
2977 299 : poColorSpace->GetType() == PDFObjectType_Name)
2978 : {
2979 296 : if (poColorSpace->GetName() == "DeviceRGB")
2980 : {
2981 113 : sTile.nBands = 3;
2982 113 : if (*pnBands < 3)
2983 26 : *pnBands = 3;
2984 : }
2985 183 : else if (poColorSpace->GetName() ==
2986 : "DeviceGray")
2987 : {
2988 183 : sTile.nBands = 1;
2989 183 : if (*pnBands < 1)
2990 129 : *pnBands = 1;
2991 : }
2992 : else
2993 0 : sTile.nBands = 0;
2994 : }
2995 299 : if (poSMask != nullptr)
2996 94 : *pnBands = 4;
2997 :
2998 299 : if (poWidth && poHeight &&
2999 0 : ((bAcceptRotationTerms &&
3000 299 : adfVals[1] == -adfVals[2]) ||
3001 299 : (!bAcceptRotationTerms && adfVals[1] == 0.0 &&
3002 299 : adfVals[2] == 0.0)))
3003 : {
3004 299 : double dfWidth = Get(poWidth);
3005 299 : double dfHeight = Get(poHeight);
3006 299 : double dfScaleX = adfVals[0];
3007 299 : double dfScaleY = adfVals[3];
3008 299 : if (dfWidth > 0 && dfHeight > 0 &&
3009 299 : dfScaleX > 0 && dfScaleY > 0 &&
3010 299 : dfWidth / dfScaleX * DEFAULT_DPI <
3011 299 : INT_MAX &&
3012 299 : dfHeight / dfScaleY * DEFAULT_DPI < INT_MAX)
3013 : {
3014 598 : double dfDPI_X = ROUND_IF_CLOSE(
3015 299 : dfWidth / dfScaleX * DEFAULT_DPI, 1e-3);
3016 598 : double dfDPI_Y = ROUND_IF_CLOSE(
3017 299 : 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 299 : if (dfDPI_X > dfDPI)
3027 20 : dfDPI = dfDPI_X;
3028 299 : if (dfDPI_Y > dfDPI)
3029 0 : dfDPI = dfDPI_Y;
3030 :
3031 299 : memcpy(&(sTile.adfCM), adfVals,
3032 : 6 * sizeof(double));
3033 299 : sTile.poImage = poImage;
3034 299 : sTile.dfWidth = dfWidth;
3035 299 : sTile.dfHeight = dfHeight;
3036 299 : asTiles.push_back(sTile);
3037 :
3038 299 : *pbDPISet = TRUE;
3039 299 : *pdfDPI = dfDPI;
3040 : }
3041 : }
3042 : }
3043 299 : nState = STATE_INIT;
3044 : }
3045 : else
3046 0 : return FALSE;
3047 : }
3048 : }
3049 3289 : osToken = "";
3050 : }
3051 : else
3052 7738 : osToken += ch;
3053 11027 : pszContent++;
3054 : }
3055 :
3056 144 : return TRUE;
3057 : }
3058 :
3059 : /************************************************************************/
3060 : /* CheckTiledRaster() */
3061 : /************************************************************************/
3062 :
3063 158 : int PDFDataset::CheckTiledRaster()
3064 : {
3065 : size_t i;
3066 158 : int l_nBlockXSize = 0;
3067 158 : int l_nBlockYSize = 0;
3068 158 : 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 454 : for (i = 0; i < m_asTiles.size(); i++)
3074 : {
3075 299 : double dfDrawWidth = m_asTiles[i].adfCM[0] * dfUserUnit;
3076 299 : double dfDrawHeight = m_asTiles[i].adfCM[3] * dfUserUnit;
3077 299 : double dfX = m_asTiles[i].adfCM[4] * dfUserUnit;
3078 299 : double dfY = m_asTiles[i].adfCM[5] * dfUserUnit;
3079 299 : int nX = static_cast<int>(dfX + 0.1);
3080 299 : int nY = static_cast<int>(dfY + 0.1);
3081 299 : int nWidth = static_cast<int>(m_asTiles[i].dfWidth + 1e-8);
3082 299 : int nHeight = static_cast<int>(m_asTiles[i].dfHeight + 1e-8);
3083 :
3084 299 : GDALPDFDictionary *poImageDict = m_asTiles[i].poImage->GetDictionary();
3085 : GDALPDFObject *poBitsPerComponent =
3086 299 : poImageDict->Get("BitsPerComponent");
3087 299 : GDALPDFObject *poColorSpace = poImageDict->Get("ColorSpace");
3088 299 : GDALPDFObject *poFilter = poImageDict->Get("Filter");
3089 :
3090 : /* Podofo cannot uncompress JPEG2000 streams */
3091 299 : if (m_bUseLib.test(PDFLIB_PODOFO) && poFilter != nullptr &&
3092 299 : 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 299 : if (poBitsPerComponent == nullptr || Get(poBitsPerComponent) != 8 ||
3101 299 : poColorSpace == nullptr ||
3102 1077 : poColorSpace->GetType() != PDFObjectType_Name ||
3103 479 : (poColorSpace->GetName() != "DeviceRGB" &&
3104 183 : poColorSpace->GetName() != "DeviceGray"))
3105 : {
3106 3 : CPLDebug("PDF", "Tile %d : Incompatible image for tiled reading",
3107 : static_cast<int>(i));
3108 3 : return FALSE;
3109 : }
3110 :
3111 296 : if (fabs(dfDrawWidth - m_asTiles[i].dfWidth) > 1e-2 ||
3112 296 : fabs(dfDrawHeight - m_asTiles[i].dfHeight) > 1e-2 ||
3113 296 : fabs(nWidth - m_asTiles[i].dfWidth) > 1e-8 ||
3114 296 : fabs(nHeight - m_asTiles[i].dfHeight) > 1e-8 ||
3115 296 : fabs(nX - dfX) > 1e-1 || fabs(nY - dfY) > 1e-1 || nX < 0 ||
3116 592 : 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 296 : if (l_nBlockXSize == 0 && l_nBlockYSize == 0 && nX == 0 && nY != 0)
3124 : {
3125 9 : l_nBlockXSize = nWidth;
3126 9 : l_nBlockYSize = nHeight;
3127 : }
3128 : }
3129 155 : if (l_nBlockXSize <= 0 || l_nBlockYSize <= 0 || l_nBlockXSize > 2048 ||
3130 : l_nBlockYSize > 2048)
3131 146 : return FALSE;
3132 :
3133 9 : int nXBlocks = DIV_ROUND_UP(nRasterXSize, l_nBlockXSize);
3134 9 : 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 159 : for (i = 0; i < m_asTiles.size(); i++)
3139 : {
3140 150 : double dfX = m_asTiles[i].adfCM[4] * dfUserUnit;
3141 150 : double dfY = m_asTiles[i].adfCM[5] * dfUserUnit;
3142 150 : int nX = static_cast<int>(dfX + 0.1);
3143 150 : int nY = static_cast<int>(dfY + 0.1);
3144 150 : int nWidth = static_cast<int>(m_asTiles[i].dfWidth + 1e-8);
3145 150 : int nHeight = static_cast<int>(m_asTiles[i].dfHeight + 1e-8);
3146 150 : int bOK = TRUE;
3147 150 : int nBlockXOff = nX / l_nBlockXSize;
3148 150 : if ((nX % l_nBlockXSize) != 0)
3149 0 : bOK = FALSE;
3150 150 : if (nBlockXOff < nXBlocks - 1 && nWidth != l_nBlockXSize)
3151 0 : bOK = FALSE;
3152 150 : if (nBlockXOff == nXBlocks - 1 && nX + nWidth != nRasterXSize)
3153 0 : bOK = FALSE;
3154 :
3155 150 : if (nY > 0 && nHeight != l_nBlockYSize)
3156 0 : bOK = FALSE;
3157 150 : if (nY == 0 && nHeight != nRasterYSize - (nYBlocks - 1) * l_nBlockYSize)
3158 0 : bOK = FALSE;
3159 :
3160 150 : 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 9 : m_aiTiles.resize(static_cast<size_t>(nXBlocks) * nYBlocks, -1);
3170 159 : for (i = 0; i < m_asTiles.size(); i++)
3171 : {
3172 150 : double dfX = m_asTiles[i].adfCM[4] * dfUserUnit;
3173 150 : double dfY = m_asTiles[i].adfCM[5] * dfUserUnit;
3174 150 : int nHeight = static_cast<int>(m_asTiles[i].dfHeight + 1e-8);
3175 150 : int nX = static_cast<int>(dfX + 0.1);
3176 150 : int nY = nRasterYSize - (static_cast<int>(dfY + 0.1) + nHeight);
3177 150 : int nBlockXOff = nX / l_nBlockXSize;
3178 150 : int nBlockYOff = nY / l_nBlockYSize;
3179 150 : m_aiTiles[nBlockYOff * nXBlocks + nBlockXOff] = static_cast<int>(i);
3180 : }
3181 :
3182 9 : this->m_nBlockXSize = l_nBlockXSize;
3183 9 : this->m_nBlockYSize = l_nBlockYSize;
3184 :
3185 9 : return TRUE;
3186 : }
3187 :
3188 : /************************************************************************/
3189 : /* GuessDPI() */
3190 : /************************************************************************/
3191 :
3192 214 : void PDFDataset::GuessDPI(GDALPDFDictionary *poPageDict, int *pnBands)
3193 : {
3194 214 : const char *pszDPI = GetOption(papszOpenOptions, "DPI", nullptr);
3195 214 : if (pszDPI != nullptr)
3196 : {
3197 : // coverity[tainted_data]
3198 3 : 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 211 : GDALPDFObject *poContents = poPageDict->Get("Contents");
3206 421 : if (poContents != nullptr &&
3207 210 : 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 211 : poPageDict->LookupObject("Resources.XObject");
3218 421 : if (poContents != nullptr &&
3219 210 : poContents->GetType() == PDFObjectType_Dictionary &&
3220 421 : poXObject != nullptr &&
3221 198 : poXObject->GetType() == PDFObjectType_Dictionary)
3222 : {
3223 198 : GDALPDFDictionary *poXObjectDict = poXObject->GetDictionary();
3224 198 : GDALPDFDictionary *poContentDict = poXObjectDict;
3225 198 : GDALPDFStream *poPageStream = poContents->GetStream();
3226 198 : if (poPageStream != nullptr)
3227 : {
3228 197 : char *pszContent = nullptr;
3229 197 : const int64_t MAX_LENGTH = 10 * 1000 * 1000;
3230 197 : int64_t nLength = poPageStream->GetLength(MAX_LENGTH);
3231 197 : int bResetTiles = FALSE;
3232 197 : double dfScaleDPI = 1.0;
3233 :
3234 197 : if (nLength < MAX_LENGTH)
3235 : {
3236 394 : CPLString osForm;
3237 197 : pszContent = poPageStream->GetBytes();
3238 197 : if (pszContent != nullptr)
3239 : {
3240 : #ifdef DEBUG
3241 : const char *pszDumpStream =
3242 197 : CPLGetConfigOption("PDF_DUMP_STREAM", nullptr);
3243 197 : 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 197 : GDALPDFParseStreamContentOnlyDrawForm(pszContent);
3256 197 : if (osForm.empty())
3257 : {
3258 : /* Special case for USGS Topo PDF, like
3259 : * CA_Hollywood_20090811_OM_geo.pdf */
3260 : const char *pszOGCDo =
3261 197 : strstr(pszContent, " /XO1 Do");
3262 197 : 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 394 : FindLayerOCG(poPageDict, "Orthoimage");
3320 197 : 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 197 : 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 197 : if (pszContent != nullptr)
3400 : {
3401 197 : int bDPISet = FALSE;
3402 :
3403 197 : const char *pszContentToParse = pszContent;
3404 197 : 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 197 : GDALPDFParseStreamContent(pszContentToParse, poContentDict,
3426 : &(m_dfDPI), &bDPISet, pnBands,
3427 197 : m_asTiles, bResetTiles);
3428 197 : CPLFree(pszContent);
3429 197 : if (bDPISet)
3430 : {
3431 158 : m_dfDPI *= dfScaleDPI;
3432 :
3433 158 : CPLDebug("PDF",
3434 : "DPI guessed from contents stream = %.16g",
3435 : m_dfDPI);
3436 158 : SetMetadataItem("DPI", CPLSPrintf("%.16g", m_dfDPI));
3437 158 : if (bResetTiles)
3438 0 : m_asTiles.resize(0);
3439 : }
3440 : else
3441 39 : m_asTiles.resize(0);
3442 : }
3443 : }
3444 : }
3445 :
3446 211 : GDALPDFObject *poUserUnit = nullptr;
3447 387 : if ((poUserUnit = poPageDict->Get("UserUnit")) != nullptr &&
3448 176 : (poUserUnit->GetType() == PDFObjectType_Int ||
3449 12 : poUserUnit->GetType() == PDFObjectType_Real))
3450 : {
3451 176 : m_dfDPI = ROUND_IF_CLOSE(Get(poUserUnit) * DEFAULT_DPI, 1e-5);
3452 176 : CPLDebug("PDF", "Found UserUnit in Page --> DPI = %.16g", m_dfDPI);
3453 176 : SetMetadataItem("DPI", CPLSPrintf("%.16g", m_dfDPI));
3454 : }
3455 : }
3456 :
3457 214 : 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 214 : }
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 214 : void PDFDataset::ParseInfo(GDALPDFObject *poInfoObj)
3507 : {
3508 214 : if (poInfoObj->GetType() != PDFObjectType_Dictionary)
3509 175 : return;
3510 :
3511 39 : GDALPDFDictionary *poInfoObjDict = poInfoObj->GetDictionary();
3512 39 : GDALPDFObject *poItem = nullptr;
3513 39 : int bOneMDISet = FALSE;
3514 48 : if ((poItem = poInfoObjDict->Get("Author")) != nullptr &&
3515 9 : poItem->GetType() == PDFObjectType_String)
3516 : {
3517 9 : SetMetadataItem("AUTHOR", poItem->GetString().c_str());
3518 9 : bOneMDISet = TRUE;
3519 : }
3520 66 : if ((poItem = poInfoObjDict->Get("Creator")) != nullptr &&
3521 27 : poItem->GetType() == PDFObjectType_String)
3522 : {
3523 27 : SetMetadataItem("CREATOR", poItem->GetString().c_str());
3524 27 : bOneMDISet = TRUE;
3525 : }
3526 43 : if ((poItem = poInfoObjDict->Get("Keywords")) != nullptr &&
3527 4 : poItem->GetType() == PDFObjectType_String)
3528 : {
3529 4 : SetMetadataItem("KEYWORDS", poItem->GetString().c_str());
3530 4 : bOneMDISet = TRUE;
3531 : }
3532 45 : if ((poItem = poInfoObjDict->Get("Subject")) != nullptr &&
3533 6 : poItem->GetType() == PDFObjectType_String)
3534 : {
3535 6 : SetMetadataItem("SUBJECT", poItem->GetString().c_str());
3536 6 : bOneMDISet = TRUE;
3537 : }
3538 46 : if ((poItem = poInfoObjDict->Get("Title")) != nullptr &&
3539 7 : poItem->GetType() == PDFObjectType_String)
3540 : {
3541 7 : SetMetadataItem("TITLE", poItem->GetString().c_str());
3542 7 : bOneMDISet = TRUE;
3543 : }
3544 52 : if ((poItem = poInfoObjDict->Get("Producer")) != nullptr &&
3545 13 : poItem->GetType() == PDFObjectType_String)
3546 : {
3547 19 : if (bOneMDISet ||
3548 6 : poItem->GetString() != "PoDoFo - http://podofo.sf.net")
3549 : {
3550 7 : SetMetadataItem("PRODUCER", poItem->GetString().c_str());
3551 7 : bOneMDISet = TRUE;
3552 : }
3553 : }
3554 68 : if ((poItem = poInfoObjDict->Get("CreationDate")) != nullptr &&
3555 29 : poItem->GetType() == PDFObjectType_String)
3556 : {
3557 29 : if (bOneMDISet)
3558 23 : 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 368 : void PDFDataset::AddLayer(const std::string &osName, int iPage)
3569 : {
3570 736 : LayerStruct layerStruct;
3571 368 : layerStruct.osName = osName;
3572 368 : layerStruct.nInsertIdx = static_cast<int>(m_oLayerNameSet.size());
3573 368 : layerStruct.iPage = iPage;
3574 368 : m_oLayerNameSet.emplace_back(std::move(layerStruct));
3575 368 : }
3576 :
3577 : /************************************************************************/
3578 : /* CreateLayerList() */
3579 : /************************************************************************/
3580 :
3581 63 : void PDFDataset::CreateLayerList()
3582 : {
3583 : // Sort layers by prioritizing page number and then insertion index
3584 63 : std::sort(m_oLayerNameSet.begin(), m_oLayerNameSet.end(),
3585 1777 : [](const LayerStruct &a, const LayerStruct &b)
3586 : {
3587 1777 : if (a.iPage < b.iPage)
3588 39 : return true;
3589 1738 : if (a.iPage > b.iPage)
3590 0 : return false;
3591 1738 : return a.nInsertIdx < b.nInsertIdx;
3592 : });
3593 :
3594 63 : if (m_oLayerNameSet.size() >= 100)
3595 : {
3596 199 : for (const auto &oLayerStruct : m_oLayerNameSet)
3597 : {
3598 : m_aosLayerNames.AddNameValue(
3599 : CPLSPrintf("LAYER_%03d_NAME", m_aosLayerNames.size()),
3600 198 : oLayerStruct.osName.c_str());
3601 : }
3602 : }
3603 : else
3604 : {
3605 232 : for (const auto &oLayerStruct : m_oLayerNameSet)
3606 : {
3607 : m_aosLayerNames.AddNameValue(
3608 : CPLSPrintf("LAYER_%02d_NAME", m_aosLayerNames.size()),
3609 170 : oLayerStruct.osName.c_str());
3610 : }
3611 : }
3612 63 : }
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 440 : std::string PDFDataset::BuildPostfixedLayerNameAndAddLayer(
3624 : const std::string &osName, const std::pair<int, int> &oOCGRef,
3625 : int iPageOfInterest, int nPageCount)
3626 : {
3627 880 : std::string osPostfixedName = osName;
3628 440 : int iLayerPage = 0;
3629 440 : if (nPageCount > 1 && !m_oMapOCGNumGenToPages.empty())
3630 : {
3631 108 : const auto oIterToPages = m_oMapOCGNumGenToPages.find(oOCGRef);
3632 108 : if (oIterToPages != m_oMapOCGNumGenToPages.end())
3633 : {
3634 108 : const auto &anPages = oIterToPages->second;
3635 108 : if (iPageOfInterest > 0)
3636 : {
3637 96 : if (std::find(anPages.begin(), anPages.end(),
3638 96 : iPageOfInterest) == anPages.end())
3639 : {
3640 72 : return std::string();
3641 : }
3642 : }
3643 12 : else if (anPages.size() == 1)
3644 : {
3645 12 : iLayerPage = anPages.front();
3646 12 : 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 368 : AddLayer(osPostfixedName, iLayerPage);
3663 :
3664 368 : return osPostfixedName;
3665 : }
3666 :
3667 : #endif // defined(HAVE_POPPLER) || defined(HAVE_PDFIUM)
3668 :
3669 : #ifdef HAVE_POPPLER
3670 :
3671 : /************************************************************************/
3672 : /* ExploreLayersPoppler() */
3673 : /************************************************************************/
3674 :
3675 215 : void PDFDataset::ExploreLayersPoppler(GDALPDFArray *poArray,
3676 : int iPageOfInterest, int nPageCount,
3677 : CPLString osTopLayer, int nRecLevel,
3678 : int &nVisited, bool &bStop)
3679 : {
3680 215 : 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 215 : if (bStop)
3689 0 : return;
3690 :
3691 215 : int nLength = poArray->GetLength();
3692 215 : CPLString osCurLayer;
3693 807 : for (int i = 0; i < nLength; i++)
3694 : {
3695 592 : nVisited++;
3696 592 : GDALPDFObject *poObj = poArray->Get(i);
3697 592 : if (poObj == nullptr)
3698 0 : continue;
3699 592 : 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 592 : else if (poObj->GetType() == PDFObjectType_Array)
3714 : {
3715 152 : ExploreLayersPoppler(poObj->GetArray(), iPageOfInterest, nPageCount,
3716 : osCurLayer, nRecLevel + 1, nVisited, bStop);
3717 152 : if (bStop)
3718 0 : return;
3719 152 : osCurLayer = "";
3720 : }
3721 440 : else if (poObj->GetType() == PDFObjectType_Dictionary)
3722 : {
3723 440 : GDALPDFDictionary *poDict = poObj->GetDictionary();
3724 440 : GDALPDFObject *poName = poDict->Get("Name");
3725 440 : if (poName != nullptr && poName->GetType() == PDFObjectType_String)
3726 : {
3727 : std::string osName =
3728 440 : PDFSanitizeLayerName(poName->GetString().c_str());
3729 : /* coverity[copy_paste_error] */
3730 440 : if (!osTopLayer.empty())
3731 : {
3732 310 : osCurLayer = osTopLayer;
3733 310 : osCurLayer += '.';
3734 310 : osCurLayer += osName;
3735 : }
3736 : else
3737 130 : 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 440 : m_poDocPoppler->getOptContentConfig();
3746 : struct Ref r;
3747 440 : r.num = poObj->GetRefNum().toInt();
3748 440 : r.gen = poObj->GetRefGen();
3749 440 : OptionalContentGroup *ocg = optContentConfig->findOcgByRef(r);
3750 440 : if (ocg)
3751 : {
3752 440 : const auto oRefPair = std::pair(poObj->GetRefNum().toInt(),
3753 880 : poObj->GetRefGen());
3754 : const std::string osPostfixedName =
3755 : BuildPostfixedLayerNameAndAddLayer(
3756 440 : osCurLayer, oRefPair, iPageOfInterest, nPageCount);
3757 440 : if (osPostfixedName.empty())
3758 72 : continue;
3759 :
3760 368 : m_oLayerOCGListPoppler.push_back(
3761 736 : std::make_pair(osPostfixedName, ocg));
3762 368 : m_aoLayerWithRef.emplace_back(osPostfixedName.c_str(),
3763 736 : poObj->GetRefNum(), r.gen);
3764 : }
3765 : }
3766 : }
3767 : }
3768 : }
3769 :
3770 : /************************************************************************/
3771 : /* FindLayersPoppler() */
3772 : /************************************************************************/
3773 :
3774 214 : void PDFDataset::FindLayersPoppler(int iPageOfInterest)
3775 : {
3776 214 : int nPageCount = 0;
3777 214 : const auto poPages = GetPagesKids();
3778 214 : if (poPages)
3779 214 : nPageCount = poPages->GetLength();
3780 :
3781 : #if POPPLER_MAJOR_VERSION > 25 || \
3782 : (POPPLER_MAJOR_VERSION == 25 && POPPLER_MINOR_VERSION >= 2)
3783 : const
3784 : #endif
3785 214 : OCGs *optContentConfig = m_poDocPoppler->getOptContentConfig();
3786 214 : if (optContentConfig == nullptr || !optContentConfig->isOk())
3787 151 : return;
3788 :
3789 : #if POPPLER_MAJOR_VERSION > 25 || \
3790 : (POPPLER_MAJOR_VERSION == 25 && POPPLER_MINOR_VERSION >= 2)
3791 : const
3792 : #endif
3793 63 : Array *array = optContentConfig->getOrderArray();
3794 63 : if (array)
3795 : {
3796 63 : GDALPDFArray *poArray = GDALPDFCreateArray(array);
3797 63 : int nVisited = 0;
3798 63 : bool bStop = false;
3799 63 : ExploreLayersPoppler(poArray, iPageOfInterest, nPageCount, CPLString(),
3800 : 0, nVisited, bStop);
3801 63 : 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 63 : CreateLayerList();
3820 63 : m_oMDMD_PDF.SetMetadata(m_aosLayerNames.List(), "LAYERS");
3821 : }
3822 :
3823 : /************************************************************************/
3824 : /* TurnLayersOnOffPoppler() */
3825 : /************************************************************************/
3826 :
3827 214 : void PDFDataset::TurnLayersOnOffPoppler()
3828 : {
3829 : #if POPPLER_MAJOR_VERSION > 25 || \
3830 : (POPPLER_MAJOR_VERSION == 25 && POPPLER_MINOR_VERSION >= 2)
3831 : const
3832 : #endif
3833 214 : OCGs *optContentConfig = m_poDocPoppler->getOptContentConfig();
3834 214 : if (optContentConfig == nullptr || !optContentConfig->isOk())
3835 151 : return;
3836 :
3837 : // Which layers to turn ON ?
3838 63 : const char *pszLayers = GetOption(papszOpenOptions, "LAYERS", nullptr);
3839 63 : 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 63 : GetOption(papszOpenOptions, "LAYERS_OFF", nullptr);
3949 63 : 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 : void PDFDataset::ExploreLayersPdfium(GDALPDFArray *poArray, int iPageOfInterest,
4009 : int nPageCount, int nRecLevel,
4010 : CPLString osTopLayer)
4011 : {
4012 : if (nRecLevel == 16)
4013 : return;
4014 :
4015 : const int nLength = poArray->GetLength();
4016 : std::string osCurLayer;
4017 : for (int i = 0; i < nLength; i++)
4018 : {
4019 : GDALPDFObject *poObj = poArray->Get(i);
4020 : if (poObj == nullptr)
4021 : continue;
4022 : if (i == 0 && poObj->GetType() == PDFObjectType_String)
4023 : {
4024 : const std::string osName =
4025 : PDFSanitizeLayerName(poObj->GetString().c_str());
4026 : if (!osTopLayer.empty())
4027 : osTopLayer = std::string(osTopLayer).append(".").append(osName);
4028 : else
4029 : osTopLayer = osName;
4030 : AddLayer(osTopLayer, 0);
4031 : m_oMapLayerNameToOCGNumGenPdfium[osTopLayer] = std::pair(-1, -1);
4032 : }
4033 : else if (poObj->GetType() == PDFObjectType_Array)
4034 : {
4035 : ExploreLayersPdfium(poObj->GetArray(), iPageOfInterest, nPageCount,
4036 : nRecLevel + 1, osCurLayer);
4037 : osCurLayer.clear();
4038 : }
4039 : else if (poObj->GetType() == PDFObjectType_Dictionary)
4040 : {
4041 : GDALPDFDictionary *poDict = poObj->GetDictionary();
4042 : GDALPDFObject *poName = poDict->Get("Name");
4043 : if (poName != nullptr && poName->GetType() == PDFObjectType_String)
4044 : {
4045 : std::string osName =
4046 : PDFSanitizeLayerName(poName->GetString().c_str());
4047 : // coverity[copy_paste_error]
4048 : if (!osTopLayer.empty())
4049 : {
4050 : osCurLayer =
4051 : std::string(osTopLayer).append(".").append(osName);
4052 : }
4053 : else
4054 : osCurLayer = std::move(osName);
4055 : // CPLDebug("PDF", "Layer %s", osCurLayer.c_str());
4056 :
4057 : const auto oRefPair =
4058 : std::pair(poObj->GetRefNum().toInt(), poObj->GetRefGen());
4059 : const std::string osPostfixedName =
4060 : BuildPostfixedLayerNameAndAddLayer(
4061 : osCurLayer, oRefPair, iPageOfInterest, nPageCount);
4062 : if (osPostfixedName.empty())
4063 : continue;
4064 :
4065 : m_aoLayerWithRef.emplace_back(
4066 : osPostfixedName, poObj->GetRefNum(), poObj->GetRefGen());
4067 : m_oMapLayerNameToOCGNumGenPdfium[osPostfixedName] = oRefPair;
4068 : }
4069 : }
4070 : }
4071 : }
4072 :
4073 : /************************************************************************/
4074 : /* FindLayersPdfium() */
4075 : /************************************************************************/
4076 :
4077 : void PDFDataset::FindLayersPdfium(int iPageOfInterest)
4078 : {
4079 : int nPageCount = 0;
4080 : const auto poPages = GetPagesKids();
4081 : if (poPages)
4082 : nPageCount = poPages->GetLength();
4083 :
4084 : GDALPDFObject *poCatalog = GetCatalog();
4085 : if (poCatalog == nullptr ||
4086 : poCatalog->GetType() != PDFObjectType_Dictionary)
4087 : return;
4088 : GDALPDFObject *poOrder = poCatalog->LookupObject("OCProperties.D.Order");
4089 : if (poOrder != nullptr && poOrder->GetType() == PDFObjectType_Array)
4090 : {
4091 : 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 : CreateLayerList();
4115 : m_oMDMD_PDF.SetMetadata(m_aosLayerNames.List(), "LAYERS");
4116 : }
4117 :
4118 : /************************************************************************/
4119 : /* TurnLayersOnOffPdfium() */
4120 : /************************************************************************/
4121 :
4122 : void PDFDataset::TurnLayersOnOffPdfium()
4123 : {
4124 : GDALPDFObject *poCatalog = GetCatalog();
4125 : if (poCatalog == nullptr ||
4126 : poCatalog->GetType() != PDFObjectType_Dictionary)
4127 : return;
4128 : GDALPDFObject *poOCGs = poCatalog->LookupObject("OCProperties.OCGs");
4129 : if (poOCGs == nullptr || poOCGs->GetType() != PDFObjectType_Array)
4130 : return;
4131 :
4132 : // Which layers to turn ON ?
4133 : const char *pszLayers = GetOption(papszOpenOptions, "LAYERS", nullptr);
4134 : if (pszLayers)
4135 : {
4136 : int i;
4137 : int bAll = EQUAL(pszLayers, "ALL");
4138 :
4139 : GDALPDFArray *poOCGsArray = poOCGs->GetArray();
4140 : int nLength = poOCGsArray->GetLength();
4141 : for (i = 0; i < nLength; i++)
4142 : {
4143 : GDALPDFObject *poOCG = poOCGsArray->Get(i);
4144 : m_oMapOCGNumGenToVisibilityStatePdfium[std::pair(
4145 : poOCG->GetRefNum().toInt(), poOCG->GetRefGen())] =
4146 : (bAll) ? VISIBILITY_ON : VISIBILITY_OFF;
4147 : }
4148 :
4149 : char **papszLayers = CSLTokenizeString2(pszLayers, ",", 0);
4150 : for (i = 0; !bAll && papszLayers[i] != nullptr; i++)
4151 : {
4152 : auto oIter = m_oMapLayerNameToOCGNumGenPdfium.find(papszLayers[i]);
4153 : if (oIter != m_oMapLayerNameToOCGNumGenPdfium.end())
4154 : {
4155 : if (oIter->second.first >= 0)
4156 : {
4157 : // CPLDebug("PDF", "Turn '%s' on", papszLayers[i]);
4158 : 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 : size_t nLen = strlen(papszLayers[i]);
4165 : int bFoundChildLayer = FALSE;
4166 : oIter = m_oMapLayerNameToOCGNumGenPdfium.begin();
4167 : for (; oIter != m_oMapLayerNameToOCGNumGenPdfium.end() &&
4168 : !bFoundChildLayer;
4169 : oIter++)
4170 : {
4171 : if (oIter->first.size() > nLen &&
4172 : strncmp(oIter->first.c_str(), papszLayers[i], nLen) ==
4173 : 0 &&
4174 : oIter->first[nLen] == '.')
4175 : {
4176 : for (int j = 0; papszLayers[j] != nullptr; j++)
4177 : {
4178 : if (strcmp(papszLayers[j], oIter->first.c_str()) ==
4179 : 0)
4180 : bFoundChildLayer = TRUE;
4181 : }
4182 : }
4183 : }
4184 :
4185 : if (!bFoundChildLayer)
4186 : {
4187 : oIter = m_oMapLayerNameToOCGNumGenPdfium.begin();
4188 : for (; oIter != m_oMapLayerNameToOCGNumGenPdfium.end() &&
4189 : !bFoundChildLayer;
4190 : oIter++)
4191 : {
4192 : if (oIter->first.size() > nLen &&
4193 : strncmp(oIter->first.c_str(), papszLayers[i],
4194 : nLen) == 0 &&
4195 : oIter->first[nLen] == '.')
4196 : {
4197 : if (oIter->second.first >= 0)
4198 : {
4199 : // CPLDebug("PDF", "Turn '%s' on too",
4200 : // oIter->first.c_str());
4201 : m_oMapOCGNumGenToVisibilityStatePdfium
4202 : [oIter->second] = VISIBILITY_ON;
4203 : }
4204 : }
4205 : }
4206 : }
4207 :
4208 : // Turn parent layers on too
4209 : char *pszLastDot = nullptr;
4210 : while ((pszLastDot = strrchr(papszLayers[i], '.')) != nullptr)
4211 : {
4212 : *pszLastDot = '\0';
4213 : oIter =
4214 : m_oMapLayerNameToOCGNumGenPdfium.find(papszLayers[i]);
4215 : if (oIter != m_oMapLayerNameToOCGNumGenPdfium.end())
4216 : {
4217 : if (oIter->second.first >= 0)
4218 : {
4219 : // CPLDebug("PDF", "Turn '%s' on too",
4220 : // papszLayers[i]);
4221 : m_oMapOCGNumGenToVisibilityStatePdfium
4222 : [oIter->second] = VISIBILITY_ON;
4223 : }
4224 : }
4225 : }
4226 : }
4227 : else
4228 : {
4229 : CPLError(CE_Warning, CPLE_AppDefined, "Unknown layer '%s'",
4230 : papszLayers[i]);
4231 : }
4232 : }
4233 : CSLDestroy(papszLayers);
4234 :
4235 : m_bUseOCG = true;
4236 : }
4237 :
4238 : // Which layers to turn OFF ?
4239 : const char *pszLayersOFF =
4240 : GetOption(papszOpenOptions, "LAYERS_OFF", nullptr);
4241 : if (pszLayersOFF)
4242 : {
4243 : char **papszLayersOFF = CSLTokenizeString2(pszLayersOFF, ",", 0);
4244 : for (int i = 0; papszLayersOFF[i] != nullptr; i++)
4245 : {
4246 : auto oIter =
4247 : m_oMapLayerNameToOCGNumGenPdfium.find(papszLayersOFF[i]);
4248 : if (oIter != m_oMapLayerNameToOCGNumGenPdfium.end())
4249 : {
4250 : 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 : m_oMapOCGNumGenToVisibilityStatePdfium[oIter->second] =
4256 : VISIBILITY_OFF;
4257 : }
4258 :
4259 : // Turn child layers off too
4260 : size_t nLen = strlen(papszLayersOFF[i]);
4261 : oIter = m_oMapLayerNameToOCGNumGenPdfium.begin();
4262 : for (; oIter != m_oMapLayerNameToOCGNumGenPdfium.end(); oIter++)
4263 : {
4264 : if (oIter->first.size() > nLen &&
4265 : strncmp(oIter->first.c_str(), papszLayersOFF[i],
4266 : nLen) == 0 &&
4267 : oIter->first[nLen] == '.')
4268 : {
4269 : if (oIter->second.first >= 0)
4270 : {
4271 : // CPLDebug("PDF", "Turn '%s' off too",
4272 : // oIter->first.c_str());
4273 : m_oMapOCGNumGenToVisibilityStatePdfium
4274 : [oIter->second] = VISIBILITY_OFF;
4275 : }
4276 : }
4277 : }
4278 : }
4279 : else
4280 : {
4281 : CPLError(CE_Warning, CPLE_AppDefined, "Unknown layer '%s'",
4282 : papszLayersOFF[i]);
4283 : }
4284 : }
4285 : CSLDestroy(papszLayersOFF);
4286 :
4287 : m_bUseOCG = true;
4288 : }
4289 : }
4290 :
4291 : /************************************************************************/
4292 : /* GetVisibilityStateForOGCPdfium() */
4293 : /************************************************************************/
4294 :
4295 : PDFDataset::VisibilityState PDFDataset::GetVisibilityStateForOGCPdfium(int nNum,
4296 : int nGen)
4297 : {
4298 : auto oIter =
4299 : m_oMapOCGNumGenToVisibilityStatePdfium.find(std::pair(nNum, nGen));
4300 : if (oIter == m_oMapOCGNumGenToVisibilityStatePdfium.end())
4301 : return VISIBILITY_DEFAULT;
4302 : return oIter->second;
4303 : }
4304 :
4305 : #endif /* HAVE_PDFIUM */
4306 :
4307 : /************************************************************************/
4308 : /* GetPagesKids() */
4309 : /************************************************************************/
4310 :
4311 428 : GDALPDFArray *PDFDataset::GetPagesKids()
4312 : {
4313 428 : const auto poCatalog = GetCatalog();
4314 428 : if (!poCatalog || poCatalog->GetType() != PDFObjectType_Dictionary)
4315 : {
4316 0 : return nullptr;
4317 : }
4318 428 : const auto poKids = poCatalog->LookupObject("Pages.Kids");
4319 428 : if (!poKids || poKids->GetType() != PDFObjectType_Array)
4320 : {
4321 0 : return nullptr;
4322 : }
4323 428 : return poKids->GetArray();
4324 : }
4325 :
4326 : /************************************************************************/
4327 : /* MapOCGsToPages() */
4328 : /************************************************************************/
4329 :
4330 214 : void PDFDataset::MapOCGsToPages()
4331 : {
4332 214 : const auto poKidsArray = GetPagesKids();
4333 214 : if (!poKidsArray)
4334 : {
4335 0 : return;
4336 : }
4337 214 : const int nKidsArrayLength = poKidsArray->GetLength();
4338 460 : for (int iPage = 0; iPage < nKidsArrayLength; ++iPage)
4339 : {
4340 246 : const auto poPage = poKidsArray->Get(iPage);
4341 246 : if (poPage && poPage->GetType() == PDFObjectType_Dictionary)
4342 : {
4343 246 : const auto poXObject = poPage->LookupObject("Resources.XObject");
4344 246 : if (poXObject && poXObject->GetType() == PDFObjectType_Dictionary)
4345 : {
4346 530 : for (const auto &oNameObjectPair :
4347 1293 : poXObject->GetDictionary()->GetValues())
4348 : {
4349 : const auto poProperties =
4350 530 : oNameObjectPair.second->LookupObject(
4351 : "Resources.Properties");
4352 567 : if (poProperties &&
4353 37 : poProperties->GetType() == PDFObjectType_Dictionary)
4354 : {
4355 : const auto &oMap =
4356 37 : poProperties->GetDictionary()->GetValues();
4357 282 : for (const auto &[osKey, poObj] : oMap)
4358 : {
4359 490 : if (poObj->GetRefNum().toBool() &&
4360 245 : poObj->GetType() == PDFObjectType_Dictionary)
4361 : {
4362 : GDALPDFObject *poType =
4363 245 : poObj->GetDictionary()->Get("Type");
4364 : GDALPDFObject *poName =
4365 245 : poObj->GetDictionary()->Get("Name");
4366 490 : if (poType &&
4367 490 : poType->GetType() == PDFObjectType_Name &&
4368 980 : poType->GetName() == "OCG" && poName &&
4369 245 : poName->GetType() == PDFObjectType_String)
4370 : {
4371 : m_oMapOCGNumGenToPages
4372 245 : [std::pair(poObj->GetRefNum().toInt(),
4373 490 : poObj->GetRefGen())]
4374 245 : .push_back(iPage + 1);
4375 : }
4376 : }
4377 : }
4378 : }
4379 : }
4380 : }
4381 : }
4382 : }
4383 : }
4384 :
4385 : /************************************************************************/
4386 : /* FindLayerOCG() */
4387 : /************************************************************************/
4388 :
4389 197 : CPLString PDFDataset::FindLayerOCG(GDALPDFDictionary *poPageDict,
4390 : const char *pszLayerName)
4391 : {
4392 : GDALPDFObject *poProperties =
4393 197 : poPageDict->LookupObject("Resources.Properties");
4394 240 : if (poProperties != nullptr &&
4395 43 : poProperties->GetType() == PDFObjectType_Dictionary)
4396 : {
4397 43 : const auto &oMap = poProperties->GetDictionary()->GetValues();
4398 122 : for (const auto &[osKey, poObj] : oMap)
4399 : {
4400 157 : if (poObj->GetRefNum().toBool() &&
4401 78 : poObj->GetType() == PDFObjectType_Dictionary)
4402 : {
4403 78 : GDALPDFObject *poType = poObj->GetDictionary()->Get("Type");
4404 78 : GDALPDFObject *poName = poObj->GetDictionary()->Get("Name");
4405 156 : if (poType != nullptr &&
4406 156 : poType->GetType() == PDFObjectType_Name &&
4407 312 : poType->GetName() == "OCG" && poName != nullptr &&
4408 78 : poName->GetType() == PDFObjectType_String)
4409 : {
4410 78 : if (poName->GetString() == pszLayerName)
4411 0 : return osKey;
4412 : }
4413 : }
4414 : }
4415 : }
4416 197 : 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 229 : PDFDataset *PDFDataset::Open(GDALOpenInfo *poOpenInfo)
4458 :
4459 : {
4460 229 : if (!PDFDatasetIdentify(poOpenInfo))
4461 1 : return nullptr;
4462 :
4463 : const char *pszUserPwd =
4464 228 : GetOption(poOpenInfo->papszOpenOptions, "USER_PWD", nullptr);
4465 :
4466 228 : const bool bOpenSubdataset = STARTS_WITH(poOpenInfo->pszFilename, "PDF:");
4467 228 : const bool bOpenSubdatasetImage =
4468 228 : STARTS_WITH(poOpenInfo->pszFilename, "PDF_IMAGE:");
4469 228 : int iPage = -1;
4470 228 : int nImageNum = -1;
4471 456 : std::string osSubdatasetName;
4472 228 : const char *pszFilename = poOpenInfo->pszFilename;
4473 :
4474 228 : if (bOpenSubdataset)
4475 : {
4476 15 : iPage = atoi(pszFilename + 4);
4477 15 : if (iPage <= 0)
4478 1 : return nullptr;
4479 14 : pszFilename = strchr(pszFilename + 4, ':');
4480 14 : if (pszFilename == nullptr)
4481 0 : return nullptr;
4482 14 : pszFilename++;
4483 14 : osSubdatasetName = CPLSPrintf("Page %d", iPage);
4484 : }
4485 213 : 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 213 : iPage = 1;
4504 :
4505 227 : std::bitset<PDFLIB_COUNT> bHasLib;
4506 227 : bHasLib.reset();
4507 : // Each library set their flag
4508 : #if defined(HAVE_POPPLER)
4509 227 : 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 : bHasLib.set(PDFLIB_PDFIUM);
4516 : #endif // HAVE_PDFIUM
4517 :
4518 227 : std::bitset<PDFLIB_COUNT> bUseLib;
4519 :
4520 : // More than one library available
4521 : // Detect which one
4522 227 : if (bHasLib.count() != 1)
4523 : {
4524 0 : const char *pszDefaultLib = bHasLib.test(PDFLIB_PDFIUM) ? "PDFIUM"
4525 0 : : bHasLib.test(PDFLIB_POPPLER) ? "POPPLER"
4526 0 : : "PODOFO";
4527 : const char *pszPDFLib =
4528 0 : GetOption(poOpenInfo->papszOpenOptions, "PDF_LIB", pszDefaultLib);
4529 : while (true)
4530 : {
4531 0 : if (EQUAL(pszPDFLib, "POPPLER"))
4532 0 : bUseLib.set(PDFLIB_POPPLER);
4533 0 : else if (EQUAL(pszPDFLib, "PODOFO"))
4534 0 : bUseLib.set(PDFLIB_PODOFO);
4535 0 : else if (EQUAL(pszPDFLib, "PDFIUM"))
4536 0 : bUseLib.set(PDFLIB_PDFIUM);
4537 :
4538 0 : 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 0 : break;
4549 : }
4550 : }
4551 : else
4552 227 : bUseLib = bHasLib;
4553 :
4554 227 : GDALPDFObject *poPageObj = nullptr;
4555 : #ifdef HAVE_POPPLER
4556 227 : PDFDoc *poDocPoppler = nullptr;
4557 227 : Page *poPagePoppler = nullptr;
4558 227 : 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 : TPdfiumDocumentStruct *poDocPdfium = nullptr;
4566 : TPdfiumPageStruct *poPagePdfium = nullptr;
4567 : #endif
4568 227 : int nPages = 0;
4569 227 : VSIVirtualHandleUniquePtr fp;
4570 :
4571 : #ifdef HAVE_POPPLER
4572 227 : if (bUseLib.test(PDFLIB_POPPLER))
4573 : {
4574 : static bool globalParamsCreatedByGDAL = false;
4575 : {
4576 454 : CPLMutexHolderD(&hGlobalParamsMutex);
4577 : /* poppler global variable */
4578 227 : if (globalParams == nullptr)
4579 : {
4580 6 : globalParamsCreatedByGDAL = true;
4581 6 : globalParams.reset(new GlobalParams());
4582 : }
4583 :
4584 227 : globalParams->setPrintCommands(CPLTestBool(
4585 : CPLGetConfigOption("GDAL_PDF_PRINT_COMMANDS", "FALSE")));
4586 : }
4587 :
4588 456 : const auto registerErrorCallback = []()
4589 : {
4590 : /* Set custom error handler for poppler errors */
4591 456 : setErrorCallback(PDFDatasetErrorFunction);
4592 456 : assert(globalParams); // avoid CSA false positive
4593 456 : globalParams->setErrQuiet(false);
4594 456 : };
4595 :
4596 227 : fp.reset(VSIFOpenL(pszFilename, "rb"));
4597 227 : if (!fp)
4598 13 : 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 226 : fp.reset(VSICreateBufferedReaderHandle(fp.release()));
4631 : while (true)
4632 : {
4633 228 : fp->Seek(0, SEEK_SET);
4634 228 : g_nPopplerErrors = 0;
4635 228 : if (globalParamsCreatedByGDAL)
4636 228 : registerErrorCallback();
4637 228 : Object oObj;
4638 : auto poStream =
4639 228 : 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 228 : GooString *poUserPwd = nullptr;
4658 228 : if (pszUserPwd)
4659 6 : poUserPwd = new GooString(pszUserPwd);
4660 228 : poDocPoppler = new PDFDoc(poStream, nullptr, poUserPwd);
4661 228 : delete poUserPwd;
4662 : #endif
4663 228 : if (globalParamsCreatedByGDAL)
4664 228 : registerErrorCallback();
4665 228 : if (g_nPopplerErrors >= MAX_POPPLER_ERRORS)
4666 : {
4667 0 : PDFFreeDoc(poDocPoppler);
4668 0 : return nullptr;
4669 : }
4670 :
4671 228 : if (!poDocPoppler->isOk() || poDocPoppler->getNumPages() == 0)
4672 : {
4673 13 : if (poDocPoppler->getErrorCode() == errEncrypted)
4674 : {
4675 5 : if (pszUserPwd && EQUAL(pszUserPwd, "ASK_INTERACTIVE"))
4676 : {
4677 : pszUserPwd =
4678 2 : PDFEnterPasswordFromConsoleIfNeeded(pszUserPwd);
4679 2 : 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 2 : CPLErrorReset();
4685 :
4686 2 : continue;
4687 : }
4688 3 : 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 2 : CPLError(CE_Failure, CPLE_AppDefined,
4699 : "Invalid password");
4700 : }
4701 : }
4702 : else
4703 : {
4704 8 : CPLError(CE_Failure, CPLE_AppDefined, "Invalid PDF");
4705 : }
4706 :
4707 11 : PDFFreeDoc(poDocPoppler);
4708 11 : return nullptr;
4709 : }
4710 215 : 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 215 : break;
4728 : }
4729 2 : }
4730 :
4731 215 : poCatalogPoppler = poDocPoppler->getCatalog();
4732 215 : 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 215 : nPages = poDocPoppler->getNumPages();
4741 :
4742 215 : 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 215 : 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 214 : 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 214 : poPagePoppler = poCatalogPoppler->getPage(iPage);
4776 214 : 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 214 : const Object &oPageObj = poPagePoppler->pageObj;
4790 : #endif
4791 214 : 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 214 : poPageObj = new GDALPDFObjectPoppler(&oPageObj);
4800 214 : Ref *poPageRef = poCatalogPoppler->getPageRef(iPage);
4801 214 : if (poPageRef != nullptr)
4802 : {
4803 428 : cpl::down_cast<GDALPDFObjectPoppler *>(poPageObj)->SetRefNumAndGen(
4804 428 : 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 : if (bUseLib.test(PDFLIB_PDFIUM) && poPageObj == nullptr)
4959 : {
4960 : if (!LoadPdfiumDocumentPage(pszFilename, pszUserPwd, iPage,
4961 : &poDocPdfium, &poPagePdfium, &nPages))
4962 : {
4963 : // CPLError is called inside function
4964 : return nullptr;
4965 : }
4966 :
4967 : const auto pageObj = poPagePdfium->page->GetDict();
4968 : if (pageObj == nullptr)
4969 : {
4970 : CPLError(CE_Failure, CPLE_AppDefined,
4971 : "Invalid PDF : invalid page object");
4972 : UnloadPdfiumDocumentPage(&poDocPdfium, &poPagePdfium);
4973 : return nullptr;
4974 : }
4975 : poPageObj = GDALPDFObjectPdfium::Build(pageObj);
4976 : }
4977 : #endif // ~ HAVE_PDFIUM
4978 :
4979 214 : if (poPageObj == nullptr)
4980 0 : return nullptr;
4981 214 : GDALPDFDictionary *poPageDict = poPageObj->GetDictionary();
4982 214 : 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 : if (bUseLib.test(PDFLIB_PDFIUM))
4994 : {
4995 : UnloadPdfiumDocumentPage(&poDocPdfium, &poPagePdfium);
4996 : }
4997 : #endif
4998 0 : return nullptr;
4999 : }
5000 :
5001 214 : const char *pszDumpObject = CPLGetConfigOption("PDF_DUMP_OBJECT", nullptr);
5002 214 : if (pszDumpObject != nullptr)
5003 : {
5004 2 : GDALPDFDumper oDumper(pszFilename, pszDumpObject);
5005 1 : oDumper.Dump(poPageObj);
5006 : }
5007 :
5008 214 : PDFDataset *poDS = new PDFDataset();
5009 214 : poDS->m_fp = std::move(fp);
5010 214 : poDS->papszOpenOptions = CSLDuplicate(poOpenInfo->papszOpenOptions);
5011 214 : poDS->m_bUseLib = bUseLib;
5012 214 : poDS->m_osFilename = pszFilename;
5013 214 : poDS->eAccess = poOpenInfo->eAccess;
5014 :
5015 214 : if (nPages > 1 && !bOpenSubdataset)
5016 : {
5017 : int i;
5018 4 : CPLStringList aosList;
5019 8 : for (i = 0; i < nPages; i++)
5020 : {
5021 : char szKey[32];
5022 6 : snprintf(szKey, sizeof(szKey), "SUBDATASET_%d_NAME", i + 1);
5023 : aosList.AddNameValue(
5024 6 : szKey, CPLSPrintf("PDF:%d:%s", i + 1, poOpenInfo->pszFilename));
5025 6 : snprintf(szKey, sizeof(szKey), "SUBDATASET_%d_DESC", i + 1);
5026 : aosList.AddNameValue(szKey, CPLSPrintf("Page %d of %s", i + 1,
5027 6 : poOpenInfo->pszFilename));
5028 : }
5029 2 : poDS->SetMetadata(aosList.List(), "SUBDATASETS");
5030 : }
5031 :
5032 : #ifdef HAVE_POPPLER
5033 214 : poDS->m_poDocPoppler = poDocPoppler;
5034 : #endif
5035 : #ifdef HAVE_PODOFO
5036 : poDS->m_poDocPodofo = poDocPodofo.release();
5037 : #endif
5038 : #ifdef HAVE_PDFIUM
5039 : poDS->m_poDocPdfium = poDocPdfium;
5040 : poDS->m_poPagePdfium = poPagePdfium;
5041 : #endif
5042 214 : poDS->m_poPageObj = poPageObj;
5043 214 : poDS->m_osUserPwd = pszUserPwd ? pszUserPwd : "";
5044 214 : poDS->m_iPage = iPage;
5045 :
5046 : const char *pszDumpCatalog =
5047 214 : CPLGetConfigOption("PDF_DUMP_CATALOG", nullptr);
5048 214 : 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 214 : int nBandsGuessed = 0;
5057 214 : if (nImageNum < 0)
5058 : {
5059 214 : poDS->GuessDPI(poPageDict, &nBandsGuessed);
5060 214 : if (nBandsGuessed < 4)
5061 207 : 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 214 : double dfX1 = 0.0;
5075 214 : double dfY1 = 0.0;
5076 214 : double dfX2 = 0.0;
5077 214 : double dfY2 = 0.0;
5078 :
5079 : #ifdef HAVE_POPPLER
5080 214 : if (bUseLib.test(PDFLIB_POPPLER))
5081 : {
5082 214 : const auto *psMediaBox = poPagePoppler->getMediaBox();
5083 214 : dfX1 = psMediaBox->x1;
5084 214 : dfY1 = psMediaBox->y1;
5085 214 : dfX2 = psMediaBox->x2;
5086 214 : 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 : if (bUseLib.test(PDFLIB_PDFIUM))
5110 : {
5111 : CPLAssert(poPagePdfium);
5112 : CFX_FloatRect rect = poPagePdfium->page->GetBBox();
5113 : dfX1 = rect.left;
5114 : dfX2 = rect.right;
5115 : dfY1 = rect.bottom;
5116 : dfY2 = rect.top;
5117 : }
5118 : #endif // ~ HAVE_PDFIUM
5119 :
5120 214 : double dfUserUnit = poDS->m_dfDPI * USER_UNIT_IN_INCH;
5121 214 : poDS->m_dfPageWidth = dfX2 - dfX1;
5122 214 : poDS->m_dfPageHeight = dfY2 - dfY1;
5123 : // CPLDebug("PDF", "left=%f right=%f bottom=%f top=%f", dfX1, dfX2, dfY1,
5124 : // dfY2);
5125 214 : const double dfXSize = floor((dfX2 - dfX1) * dfUserUnit + 0.5);
5126 214 : const double dfYSize = floor((dfY2 - dfY1) * dfUserUnit + 0.5);
5127 214 : if (!(dfXSize >= 0 && dfXSize <= INT_MAX && dfYSize >= 0 &&
5128 214 : dfYSize <= INT_MAX))
5129 : {
5130 0 : delete poDS;
5131 0 : return nullptr;
5132 : }
5133 214 : poDS->nRasterXSize = static_cast<int>(dfXSize);
5134 214 : poDS->nRasterYSize = static_cast<int>(dfYSize);
5135 :
5136 214 : if (!GDALCheckDatasetDimensions(poDS->nRasterXSize, poDS->nRasterYSize))
5137 : {
5138 0 : delete poDS;
5139 0 : return nullptr;
5140 : }
5141 :
5142 214 : double dfRotation = 0;
5143 : #ifdef HAVE_POPPLER
5144 214 : if (bUseLib.test(PDFLIB_POPPLER))
5145 214 : 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 >= 1
5153 : poPagePodofo->TryGetRotationRaw(dfRotation);
5154 : #elif (PODOFO_VERSION_MAJOR == 0 && PODOFO_VERSION_MINOR >= 10)
5155 : dfRotation = poPagePodofo->GetRotationRaw();
5156 : #else
5157 : dfRotation = poPagePodofo->GetRotation();
5158 : #endif
5159 : }
5160 : #endif
5161 :
5162 : #ifdef HAVE_PDFIUM
5163 : if (bUseLib.test(PDFLIB_PDFIUM))
5164 : {
5165 : CPLAssert(poPagePdfium);
5166 : dfRotation = poPagePdfium->page->GetPageRotation() * 90;
5167 : }
5168 : #endif
5169 :
5170 214 : if (dfRotation == 90 || dfRotation == -90 || dfRotation == 270)
5171 : {
5172 : /* FIXME: the podofo case should be implemented. This needs to rotate */
5173 : /* the output of pdftoppm */
5174 : #if defined(HAVE_POPPLER) || defined(HAVE_PDFIUM)
5175 0 : if (bUseLib.test(PDFLIB_POPPLER) || bUseLib.test(PDFLIB_PDFIUM))
5176 : {
5177 0 : int nTmp = poDS->nRasterXSize;
5178 0 : poDS->nRasterXSize = poDS->nRasterYSize;
5179 0 : poDS->nRasterYSize = nTmp;
5180 : }
5181 : #endif
5182 : }
5183 :
5184 214 : if (CSLFetchNameValue(poOpenInfo->papszOpenOptions, "@OPEN_FOR_OVERVIEW"))
5185 : {
5186 2 : poDS->m_nBlockXSize = 512;
5187 2 : poDS->m_nBlockYSize = 512;
5188 : }
5189 : /* Check if the PDF is only made of regularly tiled images */
5190 : /* (like some USGS GeoPDF production) */
5191 370 : else if (dfRotation == 0.0 && !poDS->m_asTiles.empty() &&
5192 158 : EQUAL(GetOption(poOpenInfo->papszOpenOptions, "LAYERS", "ALL"),
5193 : "ALL"))
5194 : {
5195 158 : poDS->CheckTiledRaster();
5196 158 : if (!poDS->m_aiTiles.empty())
5197 9 : poDS->SetMetadataItem("INTERLEAVE", "PIXEL", "IMAGE_STRUCTURE");
5198 : }
5199 :
5200 214 : GDALPDFObject *poLGIDict = nullptr;
5201 214 : GDALPDFObject *poVP = nullptr;
5202 214 : int bIsOGCBP = FALSE;
5203 214 : if ((poLGIDict = poPageDict->Get("LGIDict")) != nullptr && nImageNum < 0)
5204 : {
5205 : /* Cf 08-139r3_GeoPDF_Encoding_Best_Practice_Version_2.2.pdf */
5206 0 : CPLDebug("PDF", "OGC Encoding Best Practice style detected");
5207 0 : if (poDS->ParseLGIDictObject(poLGIDict))
5208 : {
5209 0 : if (poDS->m_bHasCTM)
5210 : {
5211 0 : if (dfRotation == 90)
5212 : {
5213 0 : poDS->m_gt[0] = poDS->m_adfCTM[4];
5214 0 : poDS->m_gt[1] = poDS->m_adfCTM[2] / dfUserUnit;
5215 0 : poDS->m_gt[2] = poDS->m_adfCTM[0] / dfUserUnit;
5216 0 : poDS->m_gt[3] = poDS->m_adfCTM[5];
5217 0 : poDS->m_gt[4] = poDS->m_adfCTM[3] / dfUserUnit;
5218 0 : poDS->m_gt[5] = poDS->m_adfCTM[1] / dfUserUnit;
5219 : }
5220 0 : else if (dfRotation == -90 || dfRotation == 270)
5221 : {
5222 0 : poDS->m_gt[0] = poDS->m_adfCTM[4] +
5223 0 : poDS->m_adfCTM[2] * poDS->m_dfPageHeight +
5224 0 : poDS->m_adfCTM[0] * poDS->m_dfPageWidth;
5225 0 : poDS->m_gt[1] = -poDS->m_adfCTM[2] / dfUserUnit;
5226 0 : poDS->m_gt[2] = -poDS->m_adfCTM[0] / dfUserUnit;
5227 0 : poDS->m_gt[3] = poDS->m_adfCTM[5] +
5228 0 : poDS->m_adfCTM[3] * poDS->m_dfPageHeight +
5229 0 : poDS->m_adfCTM[1] * poDS->m_dfPageWidth;
5230 0 : poDS->m_gt[4] = -poDS->m_adfCTM[3] / dfUserUnit;
5231 0 : poDS->m_gt[5] = -poDS->m_adfCTM[1] / dfUserUnit;
5232 : }
5233 : else
5234 : {
5235 0 : poDS->m_gt[0] = poDS->m_adfCTM[4] +
5236 0 : poDS->m_adfCTM[2] * dfY2 +
5237 0 : poDS->m_adfCTM[0] * dfX1;
5238 0 : poDS->m_gt[1] = poDS->m_adfCTM[0] / dfUserUnit;
5239 0 : poDS->m_gt[2] = -poDS->m_adfCTM[2] / dfUserUnit;
5240 0 : poDS->m_gt[3] = poDS->m_adfCTM[5] +
5241 0 : poDS->m_adfCTM[3] * dfY2 +
5242 0 : poDS->m_adfCTM[1] * dfX1;
5243 0 : poDS->m_gt[4] = poDS->m_adfCTM[1] / dfUserUnit;
5244 0 : poDS->m_gt[5] = -poDS->m_adfCTM[3] / dfUserUnit;
5245 : }
5246 :
5247 0 : poDS->m_bGeoTransformValid = true;
5248 : }
5249 :
5250 0 : bIsOGCBP = TRUE;
5251 :
5252 : int i;
5253 0 : for (i = 0; i < poDS->m_nGCPCount; i++)
5254 : {
5255 0 : if (dfRotation == 90)
5256 : {
5257 0 : double dfPixel =
5258 0 : poDS->m_pasGCPList[i].dfGCPPixel * dfUserUnit;
5259 0 : double dfLine =
5260 0 : poDS->m_pasGCPList[i].dfGCPLine * dfUserUnit;
5261 0 : poDS->m_pasGCPList[i].dfGCPPixel = dfLine;
5262 0 : poDS->m_pasGCPList[i].dfGCPLine = dfPixel;
5263 : }
5264 0 : else if (dfRotation == -90 || dfRotation == 270)
5265 : {
5266 0 : double dfPixel =
5267 0 : poDS->m_pasGCPList[i].dfGCPPixel * dfUserUnit;
5268 0 : double dfLine =
5269 0 : poDS->m_pasGCPList[i].dfGCPLine * dfUserUnit;
5270 0 : poDS->m_pasGCPList[i].dfGCPPixel =
5271 0 : poDS->nRasterXSize - dfLine;
5272 0 : poDS->m_pasGCPList[i].dfGCPLine =
5273 0 : poDS->nRasterYSize - dfPixel;
5274 : }
5275 : else
5276 : {
5277 0 : poDS->m_pasGCPList[i].dfGCPPixel =
5278 0 : (-dfX1 + poDS->m_pasGCPList[i].dfGCPPixel) * dfUserUnit;
5279 0 : poDS->m_pasGCPList[i].dfGCPLine =
5280 0 : (dfY2 - poDS->m_pasGCPList[i].dfGCPLine) * dfUserUnit;
5281 : }
5282 : }
5283 : }
5284 : }
5285 214 : else if ((poVP = poPageDict->Get("VP")) != nullptr && nImageNum < 0)
5286 : {
5287 : /* Cf adobe_supplement_iso32000.pdf */
5288 155 : CPLDebug("PDF", "Adobe ISO32000 style Geospatial PDF perhaps ?");
5289 155 : if (dfX1 != 0 || dfY1 != 0)
5290 : {
5291 0 : CPLDebug("PDF", "non null dfX1 or dfY1 values. untested case...");
5292 : }
5293 155 : poDS->ParseVP(poVP, dfX2 - dfX1, dfY2 - dfY1);
5294 : }
5295 : else
5296 : {
5297 : GDALPDFObject *poXObject =
5298 59 : poPageDict->LookupObject("Resources.XObject");
5299 :
5300 116 : if (poXObject != nullptr &&
5301 57 : poXObject->GetType() == PDFObjectType_Dictionary)
5302 : {
5303 57 : GDALPDFDictionary *poXObjectDict = poXObject->GetDictionary();
5304 57 : const auto &oMap = poXObjectDict->GetValues();
5305 57 : int nSubDataset = 0;
5306 231 : for (const auto &[osKey, poObj] : oMap)
5307 : {
5308 174 : if (poObj->GetType() == PDFObjectType_Dictionary)
5309 : {
5310 174 : GDALPDFDictionary *poDict = poObj->GetDictionary();
5311 174 : GDALPDFObject *poSubtype = nullptr;
5312 174 : GDALPDFObject *poMeasure = nullptr;
5313 174 : GDALPDFObject *poWidth = nullptr;
5314 174 : GDALPDFObject *poHeight = nullptr;
5315 174 : int nW = 0;
5316 174 : int nH = 0;
5317 174 : if ((poSubtype = poDict->Get("Subtype")) != nullptr &&
5318 348 : poSubtype->GetType() == PDFObjectType_Name &&
5319 174 : poSubtype->GetName() == "Image" &&
5320 129 : (poMeasure = poDict->Get("Measure")) != nullptr &&
5321 0 : poMeasure->GetType() == PDFObjectType_Dictionary &&
5322 0 : (poWidth = poDict->Get("Width")) != nullptr &&
5323 0 : poWidth->GetType() == PDFObjectType_Int &&
5324 0 : (nW = poWidth->GetInt()) > 0 &&
5325 0 : (poHeight = poDict->Get("Height")) != nullptr &&
5326 348 : poHeight->GetType() == PDFObjectType_Int &&
5327 0 : (nH = poHeight->GetInt()) > 0)
5328 : {
5329 0 : if (nImageNum < 0)
5330 0 : CPLDebug("PDF",
5331 : "Measure found on Image object (%d)",
5332 0 : poObj->GetRefNum().toInt());
5333 :
5334 0 : GDALPDFObject *poColorSpace = poDict->Get("ColorSpace");
5335 : GDALPDFObject *poBitsPerComponent =
5336 0 : poDict->Get("BitsPerComponent");
5337 0 : if (poObj->GetRefNum().toBool() &&
5338 0 : poObj->GetRefGen() == 0 &&
5339 0 : poColorSpace != nullptr &&
5340 0 : poColorSpace->GetType() == PDFObjectType_Name &&
5341 0 : (poColorSpace->GetName() == "DeviceGray" ||
5342 0 : poColorSpace->GetName() == "DeviceRGB") &&
5343 0 : (poBitsPerComponent == nullptr ||
5344 0 : (poBitsPerComponent->GetType() ==
5345 0 : PDFObjectType_Int &&
5346 0 : poBitsPerComponent->GetInt() == 8)))
5347 : {
5348 0 : if (nImageNum < 0)
5349 : {
5350 0 : nSubDataset++;
5351 0 : poDS->SetMetadataItem(
5352 : CPLSPrintf("SUBDATASET_%d_NAME",
5353 : nSubDataset),
5354 : CPLSPrintf("PDF_IMAGE:%d:%d:%s", iPage,
5355 0 : poObj->GetRefNum().toInt(),
5356 : pszFilename),
5357 : "SUBDATASETS");
5358 0 : poDS->SetMetadataItem(
5359 : CPLSPrintf("SUBDATASET_%d_DESC",
5360 : nSubDataset),
5361 : CPLSPrintf("Georeferenced image of size "
5362 : "%dx%d of page %d of %s",
5363 : nW, nH, iPage, pszFilename),
5364 : "SUBDATASETS");
5365 : }
5366 0 : else if (poObj->GetRefNum().toInt() == nImageNum)
5367 : {
5368 0 : poDS->nRasterXSize = nW;
5369 0 : poDS->nRasterYSize = nH;
5370 0 : poDS->ParseMeasure(poMeasure, nW, nH, 0, nH, nW,
5371 : 0);
5372 0 : poDS->m_poImageObj = poObj;
5373 0 : if (poColorSpace->GetName() == "DeviceGray")
5374 0 : nBandsGuessed = 1;
5375 0 : break;
5376 : }
5377 : }
5378 : }
5379 : }
5380 : }
5381 : }
5382 :
5383 59 : if (nImageNum >= 0 && poDS->m_poImageObj == nullptr)
5384 : {
5385 0 : CPLError(CE_Failure, CPLE_AppDefined, "Cannot find image %d",
5386 : nImageNum);
5387 0 : delete poDS;
5388 0 : return nullptr;
5389 : }
5390 :
5391 : /* Not a geospatial PDF doc */
5392 : }
5393 :
5394 : /* If pixel size or top left coordinates are very close to an int, round
5395 : * them to the int */
5396 : double dfEps =
5397 214 : (fabs(poDS->m_gt[0]) > 1e5 && fabs(poDS->m_gt[3]) > 1e5) ? 1e-5 : 1e-8;
5398 214 : poDS->m_gt[0] = ROUND_IF_CLOSE(poDS->m_gt[0], dfEps);
5399 214 : poDS->m_gt[1] = ROUND_IF_CLOSE(poDS->m_gt[1]);
5400 214 : poDS->m_gt[3] = ROUND_IF_CLOSE(poDS->m_gt[3], dfEps);
5401 214 : poDS->m_gt[5] = ROUND_IF_CLOSE(poDS->m_gt[5]);
5402 :
5403 214 : if (bUseLib.test(PDFLIB_PDFIUM))
5404 : {
5405 : // Attempt to "fix" the loss of precision due to the use of float32 for
5406 : // numbers by pdfium
5407 0 : if ((fabs(poDS->m_gt[0]) > 1e5 || fabs(poDS->m_gt[3]) > 1e5) &&
5408 0 : fabs(poDS->m_gt[0] - std::round(poDS->m_gt[0])) <
5409 0 : 1e-6 * fabs(poDS->m_gt[0]) &&
5410 0 : fabs(poDS->m_gt[1] - std::round(poDS->m_gt[1])) <
5411 0 : 1e-3 * fabs(poDS->m_gt[1]) &&
5412 0 : fabs(poDS->m_gt[3] - std::round(poDS->m_gt[3])) <
5413 0 : 1e-6 * fabs(poDS->m_gt[3]) &&
5414 0 : fabs(poDS->m_gt[5] - std::round(poDS->m_gt[5])) <
5415 0 : 1e-3 * fabs(poDS->m_gt[5]))
5416 : {
5417 0 : for (int i = 0; i < 6; i++)
5418 : {
5419 0 : poDS->m_gt[i] = std::round(poDS->m_gt[i]);
5420 : }
5421 : }
5422 : }
5423 :
5424 214 : if (poDS->m_poNeatLine)
5425 : {
5426 154 : char *pszNeatLineWkt = nullptr;
5427 154 : OGRLinearRing *poRing = poDS->m_poNeatLine->getExteriorRing();
5428 : /* Adobe style is already in target SRS units */
5429 154 : if (bIsOGCBP)
5430 : {
5431 0 : int nPoints = poRing->getNumPoints();
5432 : int i;
5433 :
5434 0 : for (i = 0; i < nPoints; i++)
5435 : {
5436 : double x, y;
5437 0 : if (dfRotation == 90.0)
5438 : {
5439 0 : x = poRing->getY(i) * dfUserUnit;
5440 0 : y = poRing->getX(i) * dfUserUnit;
5441 : }
5442 0 : else if (dfRotation == -90.0 || dfRotation == 270.0)
5443 : {
5444 0 : x = poDS->nRasterXSize - poRing->getY(i) * dfUserUnit;
5445 0 : y = poDS->nRasterYSize - poRing->getX(i) * dfUserUnit;
5446 : }
5447 : else
5448 : {
5449 0 : x = (-dfX1 + poRing->getX(i)) * dfUserUnit;
5450 0 : y = (dfY2 - poRing->getY(i)) * dfUserUnit;
5451 : }
5452 : double X =
5453 0 : poDS->m_gt[0] + x * poDS->m_gt[1] + y * poDS->m_gt[2];
5454 : double Y =
5455 0 : poDS->m_gt[3] + x * poDS->m_gt[4] + y * poDS->m_gt[5];
5456 0 : poRing->setPoint(i, X, Y);
5457 : }
5458 : }
5459 154 : poRing->closeRings();
5460 :
5461 154 : poDS->m_poNeatLine->exportToWkt(&pszNeatLineWkt);
5462 154 : if (nImageNum < 0)
5463 154 : poDS->SetMetadataItem("NEATLINE", pszNeatLineWkt);
5464 154 : CPLFree(pszNeatLineWkt);
5465 : }
5466 :
5467 214 : poDS->MapOCGsToPages();
5468 :
5469 : #ifdef HAVE_POPPLER
5470 214 : if (bUseLib.test(PDFLIB_POPPLER))
5471 : {
5472 214 : auto poMetadata = poCatalogPoppler->readMetadata();
5473 214 : if (poMetadata)
5474 : {
5475 19 : const char *pszContent = poMetadata->c_str();
5476 19 : if (pszContent != nullptr &&
5477 19 : STARTS_WITH(pszContent, "<?xpacket begin="))
5478 : {
5479 19 : const char *const apszMDList[2] = {pszContent, nullptr};
5480 19 : poDS->SetMetadata(const_cast<char **>(apszMDList), "xml:XMP");
5481 : }
5482 : #if (POPPLER_MAJOR_VERSION < 21 || \
5483 : (POPPLER_MAJOR_VERSION == 21 && POPPLER_MINOR_VERSION < 10))
5484 19 : delete poMetadata;
5485 : #endif
5486 : }
5487 :
5488 : /* Read Info object */
5489 : /* The test is necessary since with some corrupted PDFs
5490 : * poDocPoppler->getDocInfo() */
5491 : /* might abort() */
5492 214 : if (poDocPoppler->getXRef()->isOk())
5493 : {
5494 428 : Object oInfo = poDocPoppler->getDocInfo();
5495 428 : GDALPDFObjectPoppler oInfoObjPoppler(&oInfo, FALSE);
5496 214 : poDS->ParseInfo(&oInfoObjPoppler);
5497 : }
5498 :
5499 : /* Find layers */
5500 416 : poDS->FindLayersPoppler(
5501 202 : (bOpenSubdataset || bOpenSubdatasetImage) ? iPage : 0);
5502 :
5503 : /* Turn user specified layers on or off */
5504 214 : poDS->TurnLayersOnOffPoppler();
5505 : }
5506 : #endif
5507 :
5508 : #ifdef HAVE_PODOFO
5509 : if (bUseLib.test(PDFLIB_PODOFO))
5510 : {
5511 : for (const auto &obj : poDS->m_poDocPodofo->GetObjects())
5512 : {
5513 : GDALPDFObjectPodofo oObjPodofo(obj,
5514 : poDS->m_poDocPodofo->GetObjects());
5515 : poDS->FindXMP(&oObjPodofo);
5516 : }
5517 :
5518 : /* Find layers */
5519 : poDS->FindLayersGeneric(poPageDict);
5520 :
5521 : /* Read Info object */
5522 : const PoDoFo::PdfInfo *poInfo = poDS->m_poDocPodofo->GetInfo();
5523 : if (poInfo != nullptr)
5524 : {
5525 : GDALPDFObjectPodofo oInfoObjPodofo(
5526 : #if PODOFO_VERSION_MAJOR > 0 || \
5527 : (PODOFO_VERSION_MAJOR == 0 && PODOFO_VERSION_MINOR >= 10)
5528 : &(poInfo->GetObject()),
5529 : #else
5530 : poInfo->GetObject(),
5531 : #endif
5532 : poDS->m_poDocPodofo->GetObjects());
5533 : poDS->ParseInfo(&oInfoObjPodofo);
5534 : }
5535 : }
5536 : #endif
5537 : #ifdef HAVE_PDFIUM
5538 : if (bUseLib.test(PDFLIB_PDFIUM))
5539 : {
5540 : // coverity is confused by WrapRetain(), believing that multiple
5541 : // smart pointers manage the same raw pointer. Which is actually
5542 : // true, but a RetainPtr holds a reference counted object. It is
5543 : // thus safe to have several RetainPtr holding it.
5544 : // coverity[multiple_init_smart_ptr]
5545 : GDALPDFObjectPdfium *poRoot = GDALPDFObjectPdfium::Build(
5546 : pdfium::WrapRetain(poDocPdfium->doc->GetRoot()));
5547 : if (poRoot->GetType() == PDFObjectType_Dictionary)
5548 : {
5549 : GDALPDFDictionary *poDict = poRoot->GetDictionary();
5550 : GDALPDFObject *poMetadata(poDict->Get("Metadata"));
5551 : if (poMetadata != nullptr)
5552 : {
5553 : GDALPDFStream *poStream = poMetadata->GetStream();
5554 : if (poStream != nullptr)
5555 : {
5556 : char *pszContent = poStream->GetBytes();
5557 : const auto nLength = poStream->GetLength();
5558 : if (pszContent != nullptr && nLength > 15 &&
5559 : STARTS_WITH(pszContent, "<?xpacket begin="))
5560 : {
5561 : char *apszMDList[2];
5562 : apszMDList[0] = pszContent;
5563 : apszMDList[1] = nullptr;
5564 : poDS->SetMetadata(apszMDList, "xml:XMP");
5565 : }
5566 : CPLFree(pszContent);
5567 : }
5568 : }
5569 : }
5570 : delete poRoot;
5571 :
5572 : /* Find layers */
5573 : poDS->FindLayersPdfium((bOpenSubdataset || bOpenSubdatasetImage) ? iPage
5574 : : 0);
5575 :
5576 : /* Turn user specified layers on or off */
5577 : poDS->TurnLayersOnOffPdfium();
5578 :
5579 : GDALPDFObjectPdfium *poInfo =
5580 : GDALPDFObjectPdfium::Build(poDocPdfium->doc->GetInfo());
5581 : if (poInfo)
5582 : {
5583 : /* Read Info object */
5584 : poDS->ParseInfo(poInfo);
5585 : delete poInfo;
5586 : }
5587 : }
5588 : #endif // ~ HAVE_PDFIUM
5589 :
5590 214 : int nBands = 3;
5591 : #ifdef HAVE_PDFIUM
5592 : // Use Alpha channel for PDFIUM as default format RGBA
5593 : if (bUseLib.test(PDFLIB_PDFIUM))
5594 : nBands = 4;
5595 : #endif
5596 214 : if (nBandsGuessed)
5597 7 : nBands = nBandsGuessed;
5598 : const char *pszPDFBands =
5599 214 : GetOption(poOpenInfo->papszOpenOptions, "BANDS", nullptr);
5600 214 : if (pszPDFBands)
5601 : {
5602 2 : nBands = atoi(pszPDFBands);
5603 2 : if (nBands != 3 && nBands != 4)
5604 : {
5605 0 : CPLError(CE_Warning, CPLE_NotSupported,
5606 : "Invalid value for GDAL_PDF_BANDS. Using 3 as a fallback");
5607 0 : nBands = 3;
5608 : }
5609 : }
5610 : #ifdef HAVE_PODOFO
5611 : if (bUseLib.test(PDFLIB_PODOFO) && nBands == 4 && poDS->m_aiTiles.empty())
5612 : {
5613 : CPLError(CE_Warning, CPLE_NotSupported,
5614 : "GDAL_PDF_BANDS=4 not supported when PDF driver is compiled "
5615 : "against Podofo. "
5616 : "Using 3 as a fallback");
5617 : nBands = 3;
5618 : }
5619 : #endif
5620 :
5621 : int iBand;
5622 863 : for (iBand = 1; iBand <= nBands; iBand++)
5623 : {
5624 649 : if (poDS->m_poImageObj != nullptr)
5625 0 : poDS->SetBand(iBand, new PDFImageRasterBand(poDS, iBand));
5626 : else
5627 649 : poDS->SetBand(iBand, new PDFRasterBand(poDS, iBand, 0));
5628 : }
5629 :
5630 : /* Check if this is a raster-only PDF file and that we are */
5631 : /* opened in vector-only mode */
5632 492 : if ((poOpenInfo->nOpenFlags & GDAL_OF_RASTER) == 0 &&
5633 227 : (poOpenInfo->nOpenFlags & GDAL_OF_VECTOR) != 0 &&
5634 13 : !poDS->OpenVectorLayers(poPageDict))
5635 : {
5636 0 : CPLDebug("PDF", "This is a raster-only PDF dataset, "
5637 : "but it has been opened in vector-only mode");
5638 : /* Clear dirty flag */
5639 0 : poDS->m_bProjDirty = false;
5640 0 : poDS->m_bNeatLineDirty = false;
5641 0 : poDS->m_bInfoDirty = false;
5642 0 : poDS->m_bXMPDirty = false;
5643 0 : delete poDS;
5644 0 : return nullptr;
5645 : }
5646 :
5647 : /* -------------------------------------------------------------------- */
5648 : /* Initialize any PAM information. */
5649 : /* -------------------------------------------------------------------- */
5650 214 : if (bOpenSubdataset || bOpenSubdatasetImage)
5651 : {
5652 12 : poDS->SetPhysicalFilename(pszFilename);
5653 12 : poDS->SetSubdatasetName(osSubdatasetName.c_str());
5654 : }
5655 : else
5656 : {
5657 202 : poDS->SetDescription(poOpenInfo->pszFilename);
5658 : }
5659 :
5660 214 : poDS->TryLoadXML();
5661 :
5662 : /* -------------------------------------------------------------------- */
5663 : /* Support overviews. */
5664 : /* -------------------------------------------------------------------- */
5665 214 : if (!CSLFetchNameValue(poOpenInfo->papszOpenOptions, "@OPEN_FOR_OVERVIEW"))
5666 : {
5667 212 : poDS->oOvManager.Initialize(poDS, poOpenInfo->pszFilename);
5668 : }
5669 :
5670 : /* Clear dirty flag */
5671 214 : poDS->m_bProjDirty = false;
5672 214 : poDS->m_bNeatLineDirty = false;
5673 214 : poDS->m_bInfoDirty = false;
5674 214 : poDS->m_bXMPDirty = false;
5675 :
5676 214 : return (poDS);
5677 : }
5678 :
5679 : /************************************************************************/
5680 : /* ParseLGIDictObject() */
5681 : /************************************************************************/
5682 :
5683 0 : int PDFDataset::ParseLGIDictObject(GDALPDFObject *poLGIDict)
5684 : {
5685 0 : bool bOK = false;
5686 0 : if (poLGIDict->GetType() == PDFObjectType_Array)
5687 : {
5688 0 : GDALPDFArray *poArray = poLGIDict->GetArray();
5689 0 : int nArrayLength = poArray->GetLength();
5690 0 : int iMax = -1;
5691 0 : GDALPDFObject *poArrayElt = nullptr;
5692 0 : for (int i = 0; i < nArrayLength; i++)
5693 : {
5694 0 : if ((poArrayElt = poArray->Get(i)) == nullptr ||
5695 0 : poArrayElt->GetType() != PDFObjectType_Dictionary)
5696 : {
5697 0 : CPLError(CE_Failure, CPLE_AppDefined,
5698 : "LGIDict[%d] is not a dictionary", i);
5699 0 : return FALSE;
5700 : }
5701 :
5702 0 : int bIsBestCandidate = FALSE;
5703 0 : if (ParseLGIDictDictFirstPass(poArrayElt->GetDictionary(),
5704 0 : &bIsBestCandidate))
5705 : {
5706 0 : if (bIsBestCandidate || iMax < 0)
5707 0 : iMax = i;
5708 : }
5709 : }
5710 :
5711 0 : if (iMax < 0)
5712 0 : return FALSE;
5713 :
5714 0 : poArrayElt = poArray->Get(iMax);
5715 0 : bOK = CPL_TO_BOOL(
5716 0 : ParseLGIDictDictSecondPass(poArrayElt->GetDictionary()));
5717 : }
5718 0 : else if (poLGIDict->GetType() == PDFObjectType_Dictionary)
5719 : {
5720 0 : bOK = ParseLGIDictDictFirstPass(poLGIDict->GetDictionary()) &&
5721 0 : ParseLGIDictDictSecondPass(poLGIDict->GetDictionary());
5722 : }
5723 : else
5724 : {
5725 0 : CPLError(CE_Failure, CPLE_AppDefined, "LGIDict is of type %s",
5726 0 : poLGIDict->GetTypeName());
5727 : }
5728 :
5729 0 : return bOK;
5730 : }
5731 :
5732 : /************************************************************************/
5733 : /* Get() */
5734 : /************************************************************************/
5735 :
5736 10995 : static double Get(GDALPDFObject *poObj, int nIndice)
5737 : {
5738 10995 : if (poObj->GetType() == PDFObjectType_Array && nIndice >= 0)
5739 : {
5740 4916 : poObj = poObj->GetArray()->Get(nIndice);
5741 4916 : if (poObj == nullptr)
5742 0 : return 0;
5743 4916 : return Get(poObj);
5744 : }
5745 6079 : else if (poObj->GetType() == PDFObjectType_Int)
5746 4871 : return poObj->GetInt();
5747 1208 : else if (poObj->GetType() == PDFObjectType_Real)
5748 1208 : return poObj->GetReal();
5749 0 : else if (poObj->GetType() == PDFObjectType_String)
5750 : {
5751 0 : const char *pszStr = poObj->GetString().c_str();
5752 0 : size_t nLen = strlen(pszStr);
5753 0 : if (nLen == 0)
5754 0 : return 0;
5755 : /* cf Military_Installations_2008.pdf that has values like "96 0 0.0W"
5756 : */
5757 0 : char chLast = pszStr[nLen - 1];
5758 0 : if (chLast == 'W' || chLast == 'E' || chLast == 'N' || chLast == 'S')
5759 : {
5760 0 : double dfDeg = CPLAtof(pszStr);
5761 0 : double dfMin = 0.0;
5762 0 : double dfSec = 0.0;
5763 0 : const char *pszNext = strchr(pszStr, ' ');
5764 0 : if (pszNext)
5765 0 : pszNext++;
5766 0 : if (pszNext)
5767 0 : dfMin = CPLAtof(pszNext);
5768 0 : if (pszNext)
5769 0 : pszNext = strchr(pszNext, ' ');
5770 0 : if (pszNext)
5771 0 : pszNext++;
5772 0 : if (pszNext)
5773 0 : dfSec = CPLAtof(pszNext);
5774 0 : double dfVal = dfDeg + dfMin / 60 + dfSec / 3600;
5775 0 : if (chLast == 'W' || chLast == 'S')
5776 0 : return -dfVal;
5777 : else
5778 0 : return dfVal;
5779 : }
5780 0 : return CPLAtof(pszStr);
5781 : }
5782 : else
5783 : {
5784 0 : CPLError(CE_Warning, CPLE_AppDefined, "Unexpected type : %s",
5785 0 : poObj->GetTypeName());
5786 0 : return 0;
5787 : }
5788 : }
5789 :
5790 : /************************************************************************/
5791 : /* Get() */
5792 : /************************************************************************/
5793 :
5794 0 : static double Get(GDALPDFDictionary *poDict, const char *pszName)
5795 : {
5796 0 : GDALPDFObject *poObj = poDict->Get(pszName);
5797 0 : if (poObj != nullptr)
5798 0 : return Get(poObj);
5799 0 : CPLError(CE_Failure, CPLE_AppDefined, "Cannot find parameter %s", pszName);
5800 0 : return 0;
5801 : }
5802 :
5803 : /************************************************************************/
5804 : /* ParseLGIDictDictFirstPass() */
5805 : /************************************************************************/
5806 :
5807 0 : int PDFDataset::ParseLGIDictDictFirstPass(GDALPDFDictionary *poLGIDict,
5808 : int *pbIsBestCandidate)
5809 : {
5810 0 : if (pbIsBestCandidate)
5811 0 : *pbIsBestCandidate = FALSE;
5812 :
5813 0 : if (poLGIDict == nullptr)
5814 0 : return FALSE;
5815 :
5816 : /* -------------------------------------------------------------------- */
5817 : /* Extract Type attribute */
5818 : /* -------------------------------------------------------------------- */
5819 0 : GDALPDFObject *poType = poLGIDict->Get("Type");
5820 0 : if (poType == nullptr)
5821 : {
5822 0 : CPLError(CE_Failure, CPLE_AppDefined,
5823 : "Cannot find Type of LGIDict object");
5824 0 : return FALSE;
5825 : }
5826 :
5827 0 : if (poType->GetType() != PDFObjectType_Name)
5828 : {
5829 0 : CPLError(CE_Failure, CPLE_AppDefined,
5830 : "Invalid type for Type of LGIDict object");
5831 0 : return FALSE;
5832 : }
5833 :
5834 0 : if (strcmp(poType->GetName().c_str(), "LGIDict") != 0)
5835 : {
5836 0 : CPLError(CE_Failure, CPLE_AppDefined,
5837 : "Invalid value for Type of LGIDict object : %s",
5838 0 : poType->GetName().c_str());
5839 0 : return FALSE;
5840 : }
5841 :
5842 : /* -------------------------------------------------------------------- */
5843 : /* Extract Version attribute */
5844 : /* -------------------------------------------------------------------- */
5845 0 : GDALPDFObject *poVersion = poLGIDict->Get("Version");
5846 0 : if (poVersion == nullptr)
5847 : {
5848 0 : CPLError(CE_Failure, CPLE_AppDefined,
5849 : "Cannot find Version of LGIDict object");
5850 0 : return FALSE;
5851 : }
5852 :
5853 0 : if (poVersion->GetType() == PDFObjectType_String)
5854 : {
5855 : /* OGC best practice is 2.1 */
5856 0 : CPLDebug("PDF", "LGIDict Version : %s", poVersion->GetString().c_str());
5857 : }
5858 0 : else if (poVersion->GetType() == PDFObjectType_Int)
5859 : {
5860 : /* Old TerraGo is 2 */
5861 0 : CPLDebug("PDF", "LGIDict Version : %d", poVersion->GetInt());
5862 : }
5863 :
5864 : /* USGS PDF maps have several LGIDict. Keep the one whose description */
5865 : /* is "Map Layers" by default */
5866 : const char *pszNeatlineToSelect =
5867 0 : GetOption(papszOpenOptions, "NEATLINE", "Map Layers");
5868 :
5869 : /* -------------------------------------------------------------------- */
5870 : /* Extract Neatline attribute */
5871 : /* -------------------------------------------------------------------- */
5872 0 : GDALPDFObject *poNeatline = poLGIDict->Get("Neatline");
5873 0 : if (poNeatline != nullptr && poNeatline->GetType() == PDFObjectType_Array)
5874 : {
5875 0 : int nLength = poNeatline->GetArray()->GetLength();
5876 0 : if ((nLength % 2) != 0 || nLength < 4)
5877 : {
5878 0 : CPLError(CE_Failure, CPLE_AppDefined,
5879 : "Invalid length for Neatline");
5880 0 : return FALSE;
5881 : }
5882 :
5883 0 : GDALPDFObject *poDescription = poLGIDict->Get("Description");
5884 0 : bool bIsAskedNeatline = false;
5885 0 : if (poDescription != nullptr &&
5886 0 : poDescription->GetType() == PDFObjectType_String)
5887 : {
5888 0 : CPLDebug("PDF", "Description = %s",
5889 0 : poDescription->GetString().c_str());
5890 :
5891 0 : if (EQUAL(poDescription->GetString().c_str(), pszNeatlineToSelect))
5892 : {
5893 0 : m_dfMaxArea = 1e300;
5894 0 : bIsAskedNeatline = true;
5895 : }
5896 : }
5897 :
5898 0 : if (!bIsAskedNeatline)
5899 : {
5900 0 : double dfMinX = 0.0;
5901 0 : double dfMinY = 0.0;
5902 0 : double dfMaxX = 0.0;
5903 0 : double dfMaxY = 0.0;
5904 0 : for (int i = 0; i < nLength; i += 2)
5905 : {
5906 0 : double dfX = Get(poNeatline, i);
5907 0 : double dfY = Get(poNeatline, i + 1);
5908 0 : if (i == 0 || dfX < dfMinX)
5909 0 : dfMinX = dfX;
5910 0 : if (i == 0 || dfY < dfMinY)
5911 0 : dfMinY = dfY;
5912 0 : if (i == 0 || dfX > dfMaxX)
5913 0 : dfMaxX = dfX;
5914 0 : if (i == 0 || dfY > dfMaxY)
5915 0 : dfMaxY = dfY;
5916 : }
5917 0 : double dfArea = (dfMaxX - dfMinX) * (dfMaxY - dfMinY);
5918 0 : if (dfArea < m_dfMaxArea)
5919 : {
5920 0 : CPLDebug("PDF", "Not the largest neatline. Skipping it");
5921 0 : return TRUE;
5922 : }
5923 :
5924 0 : CPLDebug("PDF", "This is the largest neatline for now");
5925 0 : m_dfMaxArea = dfArea;
5926 : }
5927 : else
5928 0 : CPLDebug("PDF", "The \"%s\" registration will be selected",
5929 : pszNeatlineToSelect);
5930 :
5931 0 : if (pbIsBestCandidate)
5932 0 : *pbIsBestCandidate = TRUE;
5933 :
5934 0 : delete m_poNeatLine;
5935 0 : m_poNeatLine = new OGRPolygon();
5936 0 : OGRLinearRing *poRing = new OGRLinearRing();
5937 0 : if (nLength == 4)
5938 : {
5939 : /* 2 points only ? They are the bounding box */
5940 0 : double dfX1 = Get(poNeatline, 0);
5941 0 : double dfY1 = Get(poNeatline, 1);
5942 0 : double dfX2 = Get(poNeatline, 2);
5943 0 : double dfY2 = Get(poNeatline, 3);
5944 0 : poRing->addPoint(dfX1, dfY1);
5945 0 : poRing->addPoint(dfX2, dfY1);
5946 0 : poRing->addPoint(dfX2, dfY2);
5947 0 : poRing->addPoint(dfX1, dfY2);
5948 : }
5949 : else
5950 : {
5951 0 : for (int i = 0; i < nLength; i += 2)
5952 : {
5953 0 : double dfX = Get(poNeatline, i);
5954 0 : double dfY = Get(poNeatline, i + 1);
5955 0 : poRing->addPoint(dfX, dfY);
5956 : }
5957 : }
5958 0 : poRing->closeRings();
5959 0 : m_poNeatLine->addRingDirectly(poRing);
5960 : }
5961 :
5962 0 : return TRUE;
5963 : }
5964 :
5965 : /************************************************************************/
5966 : /* ParseLGIDictDictSecondPass() */
5967 : /************************************************************************/
5968 :
5969 0 : int PDFDataset::ParseLGIDictDictSecondPass(GDALPDFDictionary *poLGIDict)
5970 : {
5971 : int i;
5972 :
5973 : /* -------------------------------------------------------------------- */
5974 : /* Extract Description attribute */
5975 : /* -------------------------------------------------------------------- */
5976 0 : GDALPDFObject *poDescription = poLGIDict->Get("Description");
5977 0 : if (poDescription != nullptr &&
5978 0 : poDescription->GetType() == PDFObjectType_String)
5979 : {
5980 0 : CPLDebug("PDF", "Description = %s", poDescription->GetString().c_str());
5981 : }
5982 :
5983 : /* -------------------------------------------------------------------- */
5984 : /* Extract CTM attribute */
5985 : /* -------------------------------------------------------------------- */
5986 0 : GDALPDFObject *poCTM = poLGIDict->Get("CTM");
5987 0 : m_bHasCTM = false;
5988 0 : if (poCTM != nullptr && poCTM->GetType() == PDFObjectType_Array &&
5989 0 : CPLTestBool(CPLGetConfigOption("PDF_USE_CTM", "YES")))
5990 : {
5991 0 : int nLength = poCTM->GetArray()->GetLength();
5992 0 : if (nLength != 6)
5993 : {
5994 0 : CPLError(CE_Failure, CPLE_AppDefined, "Invalid length for CTM");
5995 0 : return FALSE;
5996 : }
5997 :
5998 0 : m_bHasCTM = true;
5999 0 : for (i = 0; i < nLength; i++)
6000 : {
6001 0 : m_adfCTM[i] = Get(poCTM, i);
6002 : /* Nullify rotation terms that are significantly smaller than */
6003 : /* scaling terms. */
6004 0 : if ((i == 1 || i == 2) &&
6005 0 : fabs(m_adfCTM[i]) < fabs(m_adfCTM[0]) * 1e-10)
6006 0 : m_adfCTM[i] = 0;
6007 0 : CPLDebug("PDF", "CTM[%d] = %.16g", i, m_adfCTM[i]);
6008 : }
6009 : }
6010 :
6011 : /* -------------------------------------------------------------------- */
6012 : /* Extract Registration attribute */
6013 : /* -------------------------------------------------------------------- */
6014 0 : GDALPDFObject *poRegistration = poLGIDict->Get("Registration");
6015 0 : if (poRegistration != nullptr &&
6016 0 : poRegistration->GetType() == PDFObjectType_Array)
6017 : {
6018 0 : GDALPDFArray *poRegistrationArray = poRegistration->GetArray();
6019 0 : int nLength = poRegistrationArray->GetLength();
6020 0 : if (nLength > 4 || (!m_bHasCTM && nLength >= 2) ||
6021 0 : CPLTestBool(CPLGetConfigOption("PDF_REPORT_GCPS", "NO")))
6022 : {
6023 0 : m_nGCPCount = 0;
6024 0 : m_pasGCPList =
6025 0 : static_cast<GDAL_GCP *>(CPLCalloc(sizeof(GDAL_GCP), nLength));
6026 :
6027 0 : for (i = 0; i < nLength; i++)
6028 : {
6029 0 : GDALPDFObject *poGCP = poRegistrationArray->Get(i);
6030 0 : if (poGCP != nullptr &&
6031 0 : poGCP->GetType() == PDFObjectType_Array &&
6032 0 : poGCP->GetArray()->GetLength() == 4)
6033 : {
6034 0 : double dfUserX = Get(poGCP, 0);
6035 0 : double dfUserY = Get(poGCP, 1);
6036 0 : double dfX = Get(poGCP, 2);
6037 0 : double dfY = Get(poGCP, 3);
6038 0 : CPLDebug("PDF", "GCP[%d].userX = %.16g", i, dfUserX);
6039 0 : CPLDebug("PDF", "GCP[%d].userY = %.16g", i, dfUserY);
6040 0 : CPLDebug("PDF", "GCP[%d].x = %.16g", i, dfX);
6041 0 : CPLDebug("PDF", "GCP[%d].y = %.16g", i, dfY);
6042 :
6043 : char szID[32];
6044 0 : snprintf(szID, sizeof(szID), "%d", m_nGCPCount + 1);
6045 0 : m_pasGCPList[m_nGCPCount].pszId = CPLStrdup(szID);
6046 0 : m_pasGCPList[m_nGCPCount].pszInfo = CPLStrdup("");
6047 0 : m_pasGCPList[m_nGCPCount].dfGCPPixel = dfUserX;
6048 0 : m_pasGCPList[m_nGCPCount].dfGCPLine = dfUserY;
6049 0 : m_pasGCPList[m_nGCPCount].dfGCPX = dfX;
6050 0 : m_pasGCPList[m_nGCPCount].dfGCPY = dfY;
6051 0 : m_nGCPCount++;
6052 : }
6053 : }
6054 :
6055 0 : if (m_nGCPCount == 0)
6056 : {
6057 0 : CPLFree(m_pasGCPList);
6058 0 : m_pasGCPList = nullptr;
6059 : }
6060 : }
6061 : }
6062 :
6063 0 : if (!m_bHasCTM && m_nGCPCount == 0)
6064 : {
6065 0 : CPLDebug("PDF", "Neither CTM nor Registration found");
6066 0 : return FALSE;
6067 : }
6068 :
6069 : /* -------------------------------------------------------------------- */
6070 : /* Extract Projection attribute */
6071 : /* -------------------------------------------------------------------- */
6072 0 : GDALPDFObject *poProjection = poLGIDict->Get("Projection");
6073 0 : if (poProjection == nullptr ||
6074 0 : poProjection->GetType() != PDFObjectType_Dictionary)
6075 : {
6076 0 : CPLError(CE_Failure, CPLE_AppDefined, "Could not find Projection");
6077 0 : return FALSE;
6078 : }
6079 :
6080 0 : return ParseProjDict(poProjection->GetDictionary());
6081 : }
6082 :
6083 : /************************************************************************/
6084 : /* ParseProjDict() */
6085 : /************************************************************************/
6086 :
6087 0 : int PDFDataset::ParseProjDict(GDALPDFDictionary *poProjDict)
6088 : {
6089 0 : if (poProjDict == nullptr)
6090 0 : return FALSE;
6091 0 : OGRSpatialReference oSRS;
6092 0 : oSRS.SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER);
6093 :
6094 : /* -------------------------------------------------------------------- */
6095 : /* Extract WKT attribute (GDAL extension) */
6096 : /* -------------------------------------------------------------------- */
6097 0 : GDALPDFObject *poWKT = poProjDict->Get("WKT");
6098 0 : if (poWKT != nullptr && poWKT->GetType() == PDFObjectType_String &&
6099 0 : CPLTestBool(CPLGetConfigOption("GDAL_PDF_OGC_BP_READ_WKT", "TRUE")))
6100 : {
6101 0 : CPLDebug("PDF", "Found WKT attribute (GDAL extension). Using it");
6102 0 : const char *pszWKTRead = poWKT->GetString().c_str();
6103 0 : if (pszWKTRead[0] != 0)
6104 0 : m_oSRS.importFromWkt(pszWKTRead);
6105 0 : return TRUE;
6106 : }
6107 :
6108 : /* -------------------------------------------------------------------- */
6109 : /* Extract Type attribute */
6110 : /* -------------------------------------------------------------------- */
6111 0 : GDALPDFObject *poType = poProjDict->Get("Type");
6112 0 : if (poType == nullptr)
6113 : {
6114 0 : CPLError(CE_Failure, CPLE_AppDefined,
6115 : "Cannot find Type of Projection object");
6116 0 : return FALSE;
6117 : }
6118 :
6119 0 : if (poType->GetType() != PDFObjectType_Name)
6120 : {
6121 0 : CPLError(CE_Failure, CPLE_AppDefined,
6122 : "Invalid type for Type of Projection object");
6123 0 : return FALSE;
6124 : }
6125 :
6126 0 : if (strcmp(poType->GetName().c_str(), "Projection") != 0)
6127 : {
6128 0 : CPLError(CE_Failure, CPLE_AppDefined,
6129 : "Invalid value for Type of Projection object : %s",
6130 0 : poType->GetName().c_str());
6131 0 : return FALSE;
6132 : }
6133 :
6134 : /* -------------------------------------------------------------------- */
6135 : /* Extract Datum attribute */
6136 : /* -------------------------------------------------------------------- */
6137 0 : int bIsWGS84 = FALSE;
6138 0 : int bIsNAD83 = FALSE;
6139 : /* int bIsNAD27 = FALSE; */
6140 :
6141 0 : GDALPDFObject *poDatum = poProjDict->Get("Datum");
6142 0 : if (poDatum != nullptr)
6143 : {
6144 0 : if (poDatum->GetType() == PDFObjectType_String)
6145 : {
6146 : /* Using Annex A of
6147 : * http://portal.opengeospatial.org/files/?artifact_id=40537 */
6148 0 : const char *pszDatum = poDatum->GetString().c_str();
6149 0 : CPLDebug("PDF", "Datum = %s", pszDatum);
6150 0 : if (EQUAL(pszDatum, "WE") || EQUAL(pszDatum, "WGE"))
6151 : {
6152 0 : bIsWGS84 = TRUE;
6153 0 : oSRS.SetWellKnownGeogCS("WGS84");
6154 : }
6155 0 : else if (EQUAL(pszDatum, "NAR") || STARTS_WITH_CI(pszDatum, "NAR-"))
6156 : {
6157 0 : bIsNAD83 = TRUE;
6158 0 : oSRS.SetWellKnownGeogCS("NAD83");
6159 : }
6160 0 : else if (EQUAL(pszDatum, "NAS") || STARTS_WITH_CI(pszDatum, "NAS-"))
6161 : {
6162 : /* bIsNAD27 = TRUE; */
6163 0 : oSRS.SetWellKnownGeogCS("NAD27");
6164 : }
6165 0 : else if (EQUAL(pszDatum, "HEN")) /* HERAT North, Afghanistan */
6166 : {
6167 0 : oSRS.SetGeogCS("unknown" /*const char * pszGeogName*/,
6168 : "unknown" /*const char * pszDatumName */,
6169 : "International 1924", 6378388, 297);
6170 0 : oSRS.SetTOWGS84(-333, -222, 114);
6171 : }
6172 0 : else if (EQUAL(pszDatum, "ING-A")) /* INDIAN 1960, Vietnam 16N */
6173 : {
6174 0 : oSRS.importFromEPSG(4131);
6175 : }
6176 0 : else if (EQUAL(pszDatum, "GDS")) /* Geocentric Datum of Australia */
6177 : {
6178 0 : oSRS.importFromEPSG(4283);
6179 : }
6180 0 : else if (STARTS_WITH_CI(pszDatum, "OHA-")) /* Old Hawaiian */
6181 : {
6182 0 : oSRS.importFromEPSG(4135); /* matches OHA-M (Mean) */
6183 0 : if (!EQUAL(pszDatum, "OHA-M"))
6184 : {
6185 0 : CPLError(CE_Warning, CPLE_AppDefined,
6186 : "Using OHA-M (Old Hawaiian Mean) definition for "
6187 : "%s. Potential issue with datum shift parameters",
6188 : pszDatum);
6189 0 : OGR_SRSNode *poNode = oSRS.GetRoot();
6190 0 : int iChild = poNode->FindChild("AUTHORITY");
6191 0 : if (iChild != -1)
6192 0 : poNode->DestroyChild(iChild);
6193 0 : iChild = poNode->FindChild("DATUM");
6194 0 : if (iChild != -1)
6195 : {
6196 0 : poNode = poNode->GetChild(iChild);
6197 0 : iChild = poNode->FindChild("AUTHORITY");
6198 0 : if (iChild != -1)
6199 0 : poNode->DestroyChild(iChild);
6200 : }
6201 : }
6202 : }
6203 : else
6204 : {
6205 0 : CPLError(CE_Warning, CPLE_AppDefined,
6206 : "Unhandled (yet) value for Datum : %s. Defaulting to "
6207 : "WGS84...",
6208 : pszDatum);
6209 0 : oSRS.SetGeogCS("unknown" /*const char * pszGeogName*/,
6210 : "unknown" /*const char * pszDatumName */,
6211 : "unknown", 6378137, 298.257223563);
6212 : }
6213 : }
6214 0 : else if (poDatum->GetType() == PDFObjectType_Dictionary)
6215 : {
6216 0 : GDALPDFDictionary *poDatumDict = poDatum->GetDictionary();
6217 :
6218 0 : GDALPDFObject *poDatumDescription = poDatumDict->Get("Description");
6219 0 : const char *pszDatumDescription = "unknown";
6220 0 : if (poDatumDescription != nullptr &&
6221 0 : poDatumDescription->GetType() == PDFObjectType_String)
6222 0 : pszDatumDescription = poDatumDescription->GetString().c_str();
6223 0 : CPLDebug("PDF", "Datum.Description = %s", pszDatumDescription);
6224 :
6225 0 : GDALPDFObject *poEllipsoid = poDatumDict->Get("Ellipsoid");
6226 0 : if (poEllipsoid == nullptr ||
6227 0 : !(poEllipsoid->GetType() == PDFObjectType_String ||
6228 0 : poEllipsoid->GetType() == PDFObjectType_Dictionary))
6229 : {
6230 0 : CPLError(
6231 : CE_Warning, CPLE_AppDefined,
6232 : "Cannot find Ellipsoid in Datum. Defaulting to WGS84...");
6233 0 : oSRS.SetGeogCS("unknown", pszDatumDescription, "unknown",
6234 : 6378137, 298.257223563);
6235 : }
6236 0 : else if (poEllipsoid->GetType() == PDFObjectType_String)
6237 : {
6238 0 : const char *pszEllipsoid = poEllipsoid->GetString().c_str();
6239 0 : CPLDebug("PDF", "Datum.Ellipsoid = %s", pszEllipsoid);
6240 0 : if (EQUAL(pszEllipsoid, "WE"))
6241 : {
6242 0 : oSRS.SetGeogCS("unknown", pszDatumDescription, "WGS 84",
6243 : 6378137, 298.257223563);
6244 : }
6245 : else
6246 : {
6247 0 : CPLError(CE_Warning, CPLE_AppDefined,
6248 : "Unhandled (yet) value for Ellipsoid : %s. "
6249 : "Defaulting to WGS84...",
6250 : pszEllipsoid);
6251 0 : oSRS.SetGeogCS("unknown", pszDatumDescription, pszEllipsoid,
6252 : 6378137, 298.257223563);
6253 : }
6254 : }
6255 : else // if (poEllipsoid->GetType() == PDFObjectType_Dictionary)
6256 : {
6257 : GDALPDFDictionary *poEllipsoidDict =
6258 0 : poEllipsoid->GetDictionary();
6259 :
6260 : GDALPDFObject *poEllipsoidDescription =
6261 0 : poEllipsoidDict->Get("Description");
6262 0 : const char *pszEllipsoidDescription = "unknown";
6263 0 : if (poEllipsoidDescription != nullptr &&
6264 0 : poEllipsoidDescription->GetType() == PDFObjectType_String)
6265 : pszEllipsoidDescription =
6266 0 : poEllipsoidDescription->GetString().c_str();
6267 0 : CPLDebug("PDF", "Datum.Ellipsoid.Description = %s",
6268 : pszEllipsoidDescription);
6269 :
6270 0 : double dfSemiMajor = Get(poEllipsoidDict, "SemiMajorAxis");
6271 0 : CPLDebug("PDF", "Datum.Ellipsoid.SemiMajorAxis = %.16g",
6272 : dfSemiMajor);
6273 0 : double dfInvFlattening = -1.0;
6274 :
6275 0 : if (poEllipsoidDict->Get("InvFlattening"))
6276 : {
6277 0 : dfInvFlattening = Get(poEllipsoidDict, "InvFlattening");
6278 0 : CPLDebug("PDF", "Datum.Ellipsoid.InvFlattening = %.16g",
6279 : dfInvFlattening);
6280 : }
6281 0 : else if (poEllipsoidDict->Get("SemiMinorAxis"))
6282 : {
6283 0 : double dfSemiMinor = Get(poEllipsoidDict, "SemiMinorAxis");
6284 0 : CPLDebug("PDF", "Datum.Ellipsoid.SemiMinorAxis = %.16g",
6285 : dfSemiMinor);
6286 : dfInvFlattening =
6287 0 : OSRCalcInvFlattening(dfSemiMajor, dfSemiMinor);
6288 : }
6289 :
6290 0 : if (dfSemiMajor != 0.0 && dfInvFlattening != -1.0)
6291 : {
6292 0 : oSRS.SetGeogCS("unknown", pszDatumDescription,
6293 : pszEllipsoidDescription, dfSemiMajor,
6294 : dfInvFlattening);
6295 : }
6296 : else
6297 : {
6298 0 : CPLError(
6299 : CE_Warning, CPLE_AppDefined,
6300 : "Invalid Ellipsoid object. Defaulting to WGS84...");
6301 0 : oSRS.SetGeogCS("unknown", pszDatumDescription,
6302 : pszEllipsoidDescription, 6378137,
6303 : 298.257223563);
6304 : }
6305 : }
6306 :
6307 0 : GDALPDFObject *poTOWGS84 = poDatumDict->Get("ToWGS84");
6308 0 : if (poTOWGS84 != nullptr &&
6309 0 : poTOWGS84->GetType() == PDFObjectType_Dictionary)
6310 : {
6311 0 : GDALPDFDictionary *poTOWGS84Dict = poTOWGS84->GetDictionary();
6312 0 : double dx = Get(poTOWGS84Dict, "dx");
6313 0 : double dy = Get(poTOWGS84Dict, "dy");
6314 0 : double dz = Get(poTOWGS84Dict, "dz");
6315 0 : if (poTOWGS84Dict->Get("rx") && poTOWGS84Dict->Get("ry") &&
6316 0 : poTOWGS84Dict->Get("rz") && poTOWGS84Dict->Get("sf"))
6317 : {
6318 0 : double rx = Get(poTOWGS84Dict, "rx");
6319 0 : double ry = Get(poTOWGS84Dict, "ry");
6320 0 : double rz = Get(poTOWGS84Dict, "rz");
6321 0 : double sf = Get(poTOWGS84Dict, "sf");
6322 0 : oSRS.SetTOWGS84(dx, dy, dz, rx, ry, rz, sf);
6323 : }
6324 : else
6325 : {
6326 0 : oSRS.SetTOWGS84(dx, dy, dz);
6327 : }
6328 : }
6329 : }
6330 : }
6331 :
6332 : /* -------------------------------------------------------------------- */
6333 : /* Extract Hemisphere attribute */
6334 : /* -------------------------------------------------------------------- */
6335 0 : CPLString osHemisphere;
6336 0 : GDALPDFObject *poHemisphere = poProjDict->Get("Hemisphere");
6337 0 : if (poHemisphere != nullptr &&
6338 0 : poHemisphere->GetType() == PDFObjectType_String)
6339 : {
6340 0 : osHemisphere = poHemisphere->GetString();
6341 : }
6342 :
6343 : /* -------------------------------------------------------------------- */
6344 : /* Extract ProjectionType attribute */
6345 : /* -------------------------------------------------------------------- */
6346 0 : GDALPDFObject *poProjectionType = poProjDict->Get("ProjectionType");
6347 0 : if (poProjectionType == nullptr ||
6348 0 : poProjectionType->GetType() != PDFObjectType_String)
6349 : {
6350 0 : CPLError(CE_Failure, CPLE_AppDefined,
6351 : "Cannot find ProjectionType of Projection object");
6352 0 : return FALSE;
6353 : }
6354 0 : CPLString osProjectionType(poProjectionType->GetString());
6355 0 : CPLDebug("PDF", "Projection.ProjectionType = %s", osProjectionType.c_str());
6356 :
6357 : /* Unhandled: NONE, GEODETIC */
6358 :
6359 0 : if (EQUAL(osProjectionType, "GEOGRAPHIC"))
6360 : {
6361 : /* Nothing to do */
6362 : }
6363 :
6364 : /* Unhandled: LOCAL CARTESIAN, MG (MGRS) */
6365 :
6366 0 : else if (EQUAL(osProjectionType, "UT")) /* UTM */
6367 : {
6368 0 : const double dfZone = Get(poProjDict, "Zone");
6369 0 : if (dfZone >= 1 && dfZone <= 60)
6370 : {
6371 0 : int nZone = static_cast<int>(dfZone);
6372 0 : int bNorth = EQUAL(osHemisphere, "N");
6373 0 : if (bIsWGS84)
6374 0 : oSRS.importFromEPSG(((bNorth) ? 32600 : 32700) + nZone);
6375 : else
6376 0 : oSRS.SetUTM(nZone, bNorth);
6377 : }
6378 : }
6379 :
6380 0 : else if (EQUAL(osProjectionType,
6381 : "UP")) /* Universal Polar Stereographic (UPS) */
6382 : {
6383 0 : int bNorth = EQUAL(osHemisphere, "N");
6384 0 : if (bIsWGS84)
6385 0 : oSRS.importFromEPSG((bNorth) ? 32661 : 32761);
6386 : else
6387 0 : oSRS.SetPS((bNorth) ? 90 : -90, 0, 0.994, 200000, 200000);
6388 : }
6389 :
6390 0 : else if (EQUAL(osProjectionType, "SPCS")) /* State Plane */
6391 : {
6392 0 : const double dfZone = Get(poProjDict, "Zone");
6393 0 : if (dfZone >= 0 && dfZone <= INT_MAX)
6394 : {
6395 0 : int nZone = static_cast<int>(dfZone);
6396 0 : oSRS.SetStatePlane(nZone, bIsNAD83);
6397 : }
6398 : }
6399 :
6400 0 : else if (EQUAL(osProjectionType, "AC")) /* Albers Equal Area Conic */
6401 : {
6402 0 : double dfStdP1 = Get(poProjDict, "StandardParallelOne");
6403 0 : double dfStdP2 = Get(poProjDict, "StandardParallelTwo");
6404 0 : double dfCenterLat = Get(poProjDict, "OriginLatitude");
6405 0 : double dfCenterLong = Get(poProjDict, "CentralMeridian");
6406 0 : double dfFalseEasting = Get(poProjDict, "FalseEasting");
6407 0 : double dfFalseNorthing = Get(poProjDict, "FalseNorthing");
6408 0 : oSRS.SetACEA(dfStdP1, dfStdP2, dfCenterLat, dfCenterLong,
6409 : dfFalseEasting, dfFalseNorthing);
6410 : }
6411 :
6412 0 : else if (EQUAL(osProjectionType, "AL")) /* Azimuthal Equidistant */
6413 : {
6414 0 : double dfCenterLat = Get(poProjDict, "OriginLatitude");
6415 0 : double dfCenterLong = Get(poProjDict, "CentralMeridian");
6416 0 : double dfFalseEasting = Get(poProjDict, "FalseEasting");
6417 0 : double dfFalseNorthing = Get(poProjDict, "FalseNorthing");
6418 0 : oSRS.SetAE(dfCenterLat, dfCenterLong, dfFalseEasting, dfFalseNorthing);
6419 : }
6420 :
6421 0 : else if (EQUAL(osProjectionType, "BF")) /* Bonne */
6422 : {
6423 0 : double dfStdP1 = Get(poProjDict, "OriginLatitude");
6424 0 : double dfCentralMeridian = Get(poProjDict, "CentralMeridian");
6425 0 : double dfFalseEasting = Get(poProjDict, "FalseEasting");
6426 0 : double dfFalseNorthing = Get(poProjDict, "FalseNorthing");
6427 0 : oSRS.SetBonne(dfStdP1, dfCentralMeridian, dfFalseEasting,
6428 : dfFalseNorthing);
6429 : }
6430 :
6431 0 : else if (EQUAL(osProjectionType, "CS")) /* Cassini */
6432 : {
6433 0 : double dfCenterLat = Get(poProjDict, "OriginLatitude");
6434 0 : double dfCenterLong = Get(poProjDict, "CentralMeridian");
6435 0 : double dfFalseEasting = Get(poProjDict, "FalseEasting");
6436 0 : double dfFalseNorthing = Get(poProjDict, "FalseNorthing");
6437 0 : oSRS.SetCS(dfCenterLat, dfCenterLong, dfFalseEasting, dfFalseNorthing);
6438 : }
6439 :
6440 0 : else if (EQUAL(osProjectionType, "LI")) /* Cylindrical Equal Area */
6441 : {
6442 0 : double dfStdP1 = Get(poProjDict, "OriginLatitude");
6443 0 : double dfCentralMeridian = Get(poProjDict, "CentralMeridian");
6444 0 : double dfFalseEasting = Get(poProjDict, "FalseEasting");
6445 0 : double dfFalseNorthing = Get(poProjDict, "FalseNorthing");
6446 0 : oSRS.SetCEA(dfStdP1, dfCentralMeridian, dfFalseEasting,
6447 : dfFalseNorthing);
6448 : }
6449 :
6450 0 : else if (EQUAL(osProjectionType, "EF")) /* Eckert IV */
6451 : {
6452 0 : double dfCentralMeridian = Get(poProjDict, "CentralMeridian");
6453 0 : double dfFalseEasting = Get(poProjDict, "FalseEasting");
6454 0 : double dfFalseNorthing = Get(poProjDict, "FalseNorthing");
6455 0 : oSRS.SetEckertIV(dfCentralMeridian, dfFalseEasting, dfFalseNorthing);
6456 : }
6457 :
6458 0 : else if (EQUAL(osProjectionType, "ED")) /* Eckert VI */
6459 : {
6460 0 : double dfCentralMeridian = Get(poProjDict, "CentralMeridian");
6461 0 : double dfFalseEasting = Get(poProjDict, "FalseEasting");
6462 0 : double dfFalseNorthing = Get(poProjDict, "FalseNorthing");
6463 0 : oSRS.SetEckertVI(dfCentralMeridian, dfFalseEasting, dfFalseNorthing);
6464 : }
6465 :
6466 0 : else if (EQUAL(osProjectionType, "CP")) /* Equidistant Cylindrical */
6467 : {
6468 0 : double dfCenterLat = Get(poProjDict, "StandardParallel");
6469 0 : double dfCenterLong = Get(poProjDict, "CentralMeridian");
6470 0 : double dfFalseEasting = Get(poProjDict, "FalseEasting");
6471 0 : double dfFalseNorthing = Get(poProjDict, "FalseNorthing");
6472 0 : oSRS.SetEquirectangular(dfCenterLat, dfCenterLong, dfFalseEasting,
6473 : dfFalseNorthing);
6474 : }
6475 :
6476 0 : else if (EQUAL(osProjectionType, "GN")) /* Gnomonic */
6477 : {
6478 0 : double dfCenterLat = Get(poProjDict, "OriginLatitude");
6479 0 : double dfCenterLong = Get(poProjDict, "CentralMeridian");
6480 0 : double dfFalseEasting = Get(poProjDict, "FalseEasting");
6481 0 : double dfFalseNorthing = Get(poProjDict, "FalseNorthing");
6482 0 : oSRS.SetGnomonic(dfCenterLat, dfCenterLong, dfFalseEasting,
6483 : dfFalseNorthing);
6484 : }
6485 :
6486 0 : else if (EQUAL(osProjectionType, "LE")) /* Lambert Conformal Conic */
6487 : {
6488 0 : double dfStdP1 = Get(poProjDict, "StandardParallelOne");
6489 0 : double dfStdP2 = Get(poProjDict, "StandardParallelTwo");
6490 0 : double dfCenterLat = Get(poProjDict, "OriginLatitude");
6491 0 : double dfCenterLong = Get(poProjDict, "CentralMeridian");
6492 0 : double dfFalseEasting = Get(poProjDict, "FalseEasting");
6493 0 : double dfFalseNorthing = Get(poProjDict, "FalseNorthing");
6494 0 : oSRS.SetLCC(dfStdP1, dfStdP2, dfCenterLat, dfCenterLong, dfFalseEasting,
6495 : dfFalseNorthing);
6496 : }
6497 :
6498 0 : else if (EQUAL(osProjectionType, "MC")) /* Mercator */
6499 : {
6500 : #ifdef not_supported
6501 : if (poProjDict->Get("StandardParallelOne") == nullptr)
6502 : #endif
6503 : {
6504 0 : double dfCenterLat = Get(poProjDict, "OriginLatitude");
6505 0 : double dfCenterLong = Get(poProjDict, "CentralMeridian");
6506 0 : double dfScale = Get(poProjDict, "ScaleFactor");
6507 0 : double dfFalseEasting = Get(poProjDict, "FalseEasting");
6508 0 : double dfFalseNorthing = Get(poProjDict, "FalseNorthing");
6509 0 : oSRS.SetMercator(dfCenterLat, dfCenterLong, dfScale, dfFalseEasting,
6510 : dfFalseNorthing);
6511 : }
6512 : #ifdef not_supported
6513 : else
6514 : {
6515 : double dfStdP1 = Get(poProjDict, "StandardParallelOne");
6516 : double dfCenterLat = poProjDict->Get("OriginLatitude")
6517 : ? Get(poProjDict, "OriginLatitude")
6518 : : 0;
6519 : double dfCenterLong = Get(poProjDict, "CentralMeridian");
6520 : double dfFalseEasting = Get(poProjDict, "FalseEasting");
6521 : double dfFalseNorthing = Get(poProjDict, "FalseNorthing");
6522 : oSRS.SetMercator2SP(dfStdP1, dfCenterLat, dfCenterLong,
6523 : dfFalseEasting, dfFalseNorthing);
6524 : }
6525 : #endif
6526 : }
6527 :
6528 0 : else if (EQUAL(osProjectionType, "MH")) /* Miller Cylindrical */
6529 : {
6530 0 : double dfCenterLat = 0 /* ? */;
6531 0 : double dfCenterLong = Get(poProjDict, "CentralMeridian");
6532 0 : double dfFalseEasting = Get(poProjDict, "FalseEasting");
6533 0 : double dfFalseNorthing = Get(poProjDict, "FalseNorthing");
6534 0 : oSRS.SetMC(dfCenterLat, dfCenterLong, dfFalseEasting, dfFalseNorthing);
6535 : }
6536 :
6537 0 : else if (EQUAL(osProjectionType, "MP")) /* Mollweide */
6538 : {
6539 0 : double dfCentralMeridian = Get(poProjDict, "CentralMeridian");
6540 0 : double dfFalseEasting = Get(poProjDict, "FalseEasting");
6541 0 : double dfFalseNorthing = Get(poProjDict, "FalseNorthing");
6542 0 : oSRS.SetMollweide(dfCentralMeridian, dfFalseEasting, dfFalseNorthing);
6543 : }
6544 :
6545 : /* Unhandled: "NY" : Ney's (Modified Lambert Conformal Conic) */
6546 :
6547 0 : else if (EQUAL(osProjectionType, "NT")) /* New Zealand Map Grid */
6548 : {
6549 : /* No parameter specified in the PDF, so let's take the ones of
6550 : * EPSG:27200 */
6551 0 : double dfCenterLat = -41;
6552 0 : double dfCenterLong = 173;
6553 0 : double dfFalseEasting = 2510000;
6554 0 : double dfFalseNorthing = 6023150;
6555 0 : oSRS.SetNZMG(dfCenterLat, dfCenterLong, dfFalseEasting,
6556 : dfFalseNorthing);
6557 : }
6558 :
6559 0 : else if (EQUAL(osProjectionType, "OC")) /* Oblique Mercator */
6560 : {
6561 0 : double dfCenterLat = Get(poProjDict, "OriginLatitude");
6562 0 : double dfLat1 = Get(poProjDict, "LatitudeOne");
6563 0 : double dfLong1 = Get(poProjDict, "LongitudeOne");
6564 0 : double dfLat2 = Get(poProjDict, "LatitudeTwo");
6565 0 : double dfLong2 = Get(poProjDict, "LongitudeTwo");
6566 0 : double dfScale = Get(poProjDict, "ScaleFactor");
6567 0 : double dfFalseEasting = Get(poProjDict, "FalseEasting");
6568 0 : double dfFalseNorthing = Get(poProjDict, "FalseNorthing");
6569 0 : oSRS.SetHOM2PNO(dfCenterLat, dfLat1, dfLong1, dfLat2, dfLong2, dfScale,
6570 : dfFalseEasting, dfFalseNorthing);
6571 : }
6572 :
6573 0 : else if (EQUAL(osProjectionType, "OD")) /* Orthographic */
6574 : {
6575 0 : double dfCenterLat = Get(poProjDict, "OriginLatitude");
6576 0 : double dfCenterLong = Get(poProjDict, "CentralMeridian");
6577 0 : double dfFalseEasting = Get(poProjDict, "FalseEasting");
6578 0 : double dfFalseNorthing = Get(poProjDict, "FalseNorthing");
6579 0 : oSRS.SetOrthographic(dfCenterLat, dfCenterLong, dfFalseEasting,
6580 : dfFalseNorthing);
6581 : }
6582 :
6583 0 : else if (EQUAL(osProjectionType, "PG")) /* Polar Stereographic */
6584 : {
6585 0 : double dfCenterLat = Get(poProjDict, "LatitudeTrueScale");
6586 0 : double dfCenterLong = Get(poProjDict, "LongitudeDownFromPole");
6587 0 : double dfScale = 1.0;
6588 0 : double dfFalseEasting = Get(poProjDict, "FalseEasting");
6589 0 : double dfFalseNorthing = Get(poProjDict, "FalseNorthing");
6590 0 : oSRS.SetPS(dfCenterLat, dfCenterLong, dfScale, dfFalseEasting,
6591 : dfFalseNorthing);
6592 : }
6593 :
6594 0 : else if (EQUAL(osProjectionType, "PH")) /* Polyconic */
6595 : {
6596 0 : double dfCenterLat = Get(poProjDict, "OriginLatitude");
6597 0 : double dfCenterLong = Get(poProjDict, "CentralMeridian");
6598 0 : double dfFalseEasting = Get(poProjDict, "FalseEasting");
6599 0 : double dfFalseNorthing = Get(poProjDict, "FalseNorthing");
6600 0 : oSRS.SetPolyconic(dfCenterLat, dfCenterLong, dfFalseEasting,
6601 : dfFalseNorthing);
6602 : }
6603 :
6604 0 : else if (EQUAL(osProjectionType, "SA")) /* Sinusoidal */
6605 : {
6606 0 : double dfCenterLong = Get(poProjDict, "CentralMeridian");
6607 0 : double dfFalseEasting = Get(poProjDict, "FalseEasting");
6608 0 : double dfFalseNorthing = Get(poProjDict, "FalseNorthing");
6609 0 : oSRS.SetSinusoidal(dfCenterLong, dfFalseEasting, dfFalseNorthing);
6610 : }
6611 :
6612 0 : else if (EQUAL(osProjectionType, "SD")) /* Stereographic */
6613 : {
6614 0 : double dfCenterLat = Get(poProjDict, "OriginLatitude");
6615 0 : double dfCenterLong = Get(poProjDict, "CentralMeridian");
6616 0 : double dfScale = 1.0;
6617 0 : double dfFalseEasting = Get(poProjDict, "FalseEasting");
6618 0 : double dfFalseNorthing = Get(poProjDict, "FalseNorthing");
6619 0 : oSRS.SetStereographic(dfCenterLat, dfCenterLong, dfScale,
6620 : dfFalseEasting, dfFalseNorthing);
6621 : }
6622 :
6623 0 : else if (EQUAL(osProjectionType, "TC")) /* Transverse Mercator */
6624 : {
6625 0 : double dfCenterLat = Get(poProjDict, "OriginLatitude");
6626 0 : double dfCenterLong = Get(poProjDict, "CentralMeridian");
6627 0 : double dfScale = Get(poProjDict, "ScaleFactor");
6628 0 : double dfFalseEasting = Get(poProjDict, "FalseEasting");
6629 0 : double dfFalseNorthing = Get(poProjDict, "FalseNorthing");
6630 0 : if (dfCenterLat == 0.0 && dfScale == 0.9996 && dfCenterLong >= -180 &&
6631 0 : dfCenterLong <= 180 && dfFalseEasting == 500000 &&
6632 0 : (dfFalseNorthing == 0.0 || dfFalseNorthing == 10000000.0))
6633 : {
6634 0 : const int nZone =
6635 0 : static_cast<int>(floor((dfCenterLong + 180.0) / 6.0) + 1);
6636 0 : int bNorth = dfFalseNorthing == 0;
6637 0 : if (bIsWGS84)
6638 0 : oSRS.importFromEPSG(((bNorth) ? 32600 : 32700) + nZone);
6639 0 : else if (bIsNAD83 && bNorth)
6640 0 : oSRS.importFromEPSG(26900 + nZone);
6641 : else
6642 0 : oSRS.SetUTM(nZone, bNorth);
6643 : }
6644 : else
6645 : {
6646 0 : oSRS.SetTM(dfCenterLat, dfCenterLong, dfScale, dfFalseEasting,
6647 : dfFalseNorthing);
6648 : }
6649 : }
6650 :
6651 : /* Unhandled TX : Transverse Cylindrical Equal Area */
6652 :
6653 0 : else if (EQUAL(osProjectionType, "VA")) /* Van der Grinten */
6654 : {
6655 0 : double dfCenterLong = Get(poProjDict, "CentralMeridian");
6656 0 : double dfFalseEasting = Get(poProjDict, "FalseEasting");
6657 0 : double dfFalseNorthing = Get(poProjDict, "FalseNorthing");
6658 0 : oSRS.SetVDG(dfCenterLong, dfFalseEasting, dfFalseNorthing);
6659 : }
6660 :
6661 : else
6662 : {
6663 0 : CPLError(CE_Failure, CPLE_AppDefined,
6664 : "Unhandled (yet) value for ProjectionType : %s",
6665 : osProjectionType.c_str());
6666 0 : return FALSE;
6667 : }
6668 :
6669 : /* -------------------------------------------------------------------- */
6670 : /* Extract Units attribute */
6671 : /* -------------------------------------------------------------------- */
6672 0 : CPLString osUnits;
6673 0 : GDALPDFObject *poUnits = poProjDict->Get("Units");
6674 0 : if (poUnits != nullptr && poUnits->GetType() == PDFObjectType_String &&
6675 0 : !EQUAL(osProjectionType, "GEOGRAPHIC"))
6676 : {
6677 0 : osUnits = poUnits->GetString();
6678 0 : CPLDebug("PDF", "Projection.Units = %s", osUnits.c_str());
6679 :
6680 : // This is super weird. The false easting/northing of the SRS
6681 : // are expressed in the unit, but the geotransform is expressed in
6682 : // meters. Hence this hack to have an equivalent SRS definition, but
6683 : // with linear units converted in meters.
6684 0 : if (EQUAL(osUnits, "M"))
6685 0 : oSRS.SetLinearUnits("Meter", 1.0);
6686 0 : else if (EQUAL(osUnits, "FT"))
6687 : {
6688 0 : oSRS.SetLinearUnits("foot", 0.3048);
6689 0 : oSRS.SetLinearUnitsAndUpdateParameters("Meter", 1.0);
6690 : }
6691 0 : else if (EQUAL(osUnits, "USSF"))
6692 : {
6693 0 : oSRS.SetLinearUnits(SRS_UL_US_FOOT, CPLAtof(SRS_UL_US_FOOT_CONV));
6694 0 : oSRS.SetLinearUnitsAndUpdateParameters("Meter", 1.0);
6695 : }
6696 : else
6697 0 : CPLError(CE_Warning, CPLE_AppDefined, "Unhandled unit: %s",
6698 : osUnits.c_str());
6699 : }
6700 :
6701 : /* -------------------------------------------------------------------- */
6702 : /* Export SpatialRef */
6703 : /* -------------------------------------------------------------------- */
6704 0 : m_oSRS = std::move(oSRS);
6705 :
6706 0 : return TRUE;
6707 : }
6708 :
6709 : /************************************************************************/
6710 : /* ParseVP() */
6711 : /************************************************************************/
6712 :
6713 155 : int PDFDataset::ParseVP(GDALPDFObject *poVP, double dfMediaBoxWidth,
6714 : double dfMediaBoxHeight)
6715 : {
6716 : int i;
6717 :
6718 155 : if (poVP->GetType() != PDFObjectType_Array)
6719 0 : return FALSE;
6720 :
6721 155 : GDALPDFArray *poVPArray = poVP->GetArray();
6722 :
6723 155 : int nLength = poVPArray->GetLength();
6724 155 : CPLDebug("PDF", "VP length = %d", nLength);
6725 155 : if (nLength < 1)
6726 0 : return FALSE;
6727 :
6728 : /* -------------------------------------------------------------------- */
6729 : /* Find the largest BBox */
6730 : /* -------------------------------------------------------------------- */
6731 : const char *pszNeatlineToSelect =
6732 155 : GetOption(papszOpenOptions, "NEATLINE", "Map Layers");
6733 :
6734 155 : int iLargest = 0;
6735 155 : int iRequestedVP = -1;
6736 155 : double dfLargestArea = 0;
6737 :
6738 321 : for (i = 0; i < nLength; i++)
6739 : {
6740 166 : GDALPDFObject *poVPElt = poVPArray->Get(i);
6741 332 : if (poVPElt == nullptr ||
6742 166 : poVPElt->GetType() != PDFObjectType_Dictionary)
6743 : {
6744 0 : return FALSE;
6745 : }
6746 :
6747 166 : GDALPDFDictionary *poVPEltDict = poVPElt->GetDictionary();
6748 :
6749 166 : GDALPDFObject *poMeasure = poVPEltDict->Get("Measure");
6750 332 : if (poMeasure == nullptr ||
6751 166 : poMeasure->GetType() != PDFObjectType_Dictionary)
6752 : {
6753 0 : continue;
6754 : }
6755 : /* --------------------------------------------------------------------
6756 : */
6757 : /* Extract Subtype attribute */
6758 : /* --------------------------------------------------------------------
6759 : */
6760 166 : GDALPDFDictionary *poMeasureDict = poMeasure->GetDictionary();
6761 166 : GDALPDFObject *poSubtype = poMeasureDict->Get("Subtype");
6762 166 : if (poSubtype == nullptr || poSubtype->GetType() != PDFObjectType_Name)
6763 : {
6764 0 : continue;
6765 : }
6766 :
6767 166 : CPLDebug("PDF", "Subtype = %s", poSubtype->GetName().c_str());
6768 166 : if (!EQUAL(poSubtype->GetName().c_str(), "GEO"))
6769 : {
6770 0 : continue;
6771 : }
6772 :
6773 166 : GDALPDFObject *poName = poVPEltDict->Get("Name");
6774 166 : if (poName != nullptr && poName->GetType() == PDFObjectType_String)
6775 : {
6776 164 : CPLDebug("PDF", "Name = %s", poName->GetString().c_str());
6777 164 : if (EQUAL(poName->GetString().c_str(), pszNeatlineToSelect))
6778 : {
6779 0 : iRequestedVP = i;
6780 : }
6781 : }
6782 :
6783 166 : GDALPDFObject *poBBox = poVPEltDict->Get("BBox");
6784 166 : if (poBBox == nullptr || poBBox->GetType() != PDFObjectType_Array)
6785 : {
6786 0 : CPLError(CE_Failure, CPLE_AppDefined, "Cannot find Bbox object");
6787 0 : return FALSE;
6788 : }
6789 :
6790 166 : int nBboxLength = poBBox->GetArray()->GetLength();
6791 166 : if (nBboxLength != 4)
6792 : {
6793 0 : CPLError(CE_Failure, CPLE_AppDefined,
6794 : "Invalid length for Bbox object");
6795 0 : return FALSE;
6796 : }
6797 :
6798 : double adfBBox[4];
6799 166 : adfBBox[0] = Get(poBBox, 0);
6800 166 : adfBBox[1] = Get(poBBox, 1);
6801 166 : adfBBox[2] = Get(poBBox, 2);
6802 166 : adfBBox[3] = Get(poBBox, 3);
6803 166 : double dfArea =
6804 166 : fabs(adfBBox[2] - adfBBox[0]) * fabs(adfBBox[3] - adfBBox[1]);
6805 166 : if (dfArea > dfLargestArea)
6806 : {
6807 155 : iLargest = i;
6808 155 : dfLargestArea = dfArea;
6809 : }
6810 : }
6811 :
6812 155 : if (nLength > 1)
6813 : {
6814 11 : CPLDebug("PDF", "Largest BBox in VP array is element %d", iLargest);
6815 : }
6816 :
6817 155 : GDALPDFObject *poVPElt = nullptr;
6818 :
6819 155 : if (iRequestedVP > -1)
6820 : {
6821 0 : CPLDebug("PDF", "Requested NEATLINE BBox in VP array is element %d",
6822 : iRequestedVP);
6823 0 : poVPElt = poVPArray->Get(iRequestedVP);
6824 : }
6825 : else
6826 : {
6827 155 : poVPElt = poVPArray->Get(iLargest);
6828 : }
6829 :
6830 155 : if (poVPElt == nullptr || poVPElt->GetType() != PDFObjectType_Dictionary)
6831 : {
6832 0 : return FALSE;
6833 : }
6834 :
6835 155 : GDALPDFDictionary *poVPEltDict = poVPElt->GetDictionary();
6836 :
6837 155 : GDALPDFObject *poBBox = poVPEltDict->Get("BBox");
6838 155 : if (poBBox == nullptr || poBBox->GetType() != PDFObjectType_Array)
6839 : {
6840 0 : CPLError(CE_Failure, CPLE_AppDefined, "Cannot find Bbox object");
6841 0 : return FALSE;
6842 : }
6843 :
6844 155 : int nBboxLength = poBBox->GetArray()->GetLength();
6845 155 : if (nBboxLength != 4)
6846 : {
6847 0 : CPLError(CE_Failure, CPLE_AppDefined, "Invalid length for Bbox object");
6848 0 : return FALSE;
6849 : }
6850 :
6851 155 : double dfULX = Get(poBBox, 0);
6852 155 : double dfULY = dfMediaBoxHeight - Get(poBBox, 1);
6853 155 : double dfLRX = Get(poBBox, 2);
6854 155 : double dfLRY = dfMediaBoxHeight - Get(poBBox, 3);
6855 :
6856 : /* -------------------------------------------------------------------- */
6857 : /* Extract Measure attribute */
6858 : /* -------------------------------------------------------------------- */
6859 155 : GDALPDFObject *poMeasure = poVPEltDict->Get("Measure");
6860 310 : if (poMeasure == nullptr ||
6861 155 : poMeasure->GetType() != PDFObjectType_Dictionary)
6862 : {
6863 0 : CPLError(CE_Failure, CPLE_AppDefined, "Cannot find Measure object");
6864 0 : return FALSE;
6865 : }
6866 :
6867 155 : int bRet = ParseMeasure(poMeasure, dfMediaBoxWidth, dfMediaBoxHeight, dfULX,
6868 : dfULY, dfLRX, dfLRY);
6869 :
6870 : /* -------------------------------------------------------------------- */
6871 : /* Extract PointData attribute */
6872 : /* -------------------------------------------------------------------- */
6873 155 : GDALPDFObject *poPointData = poVPEltDict->Get("PtData");
6874 155 : if (poPointData != nullptr &&
6875 0 : poPointData->GetType() == PDFObjectType_Dictionary)
6876 : {
6877 0 : CPLDebug("PDF", "Found PointData");
6878 : }
6879 :
6880 155 : return bRet;
6881 : }
6882 :
6883 : /************************************************************************/
6884 : /* ParseMeasure() */
6885 : /************************************************************************/
6886 :
6887 155 : int PDFDataset::ParseMeasure(GDALPDFObject *poMeasure, double dfMediaBoxWidth,
6888 : double dfMediaBoxHeight, double dfULX,
6889 : double dfULY, double dfLRX, double dfLRY)
6890 : {
6891 155 : GDALPDFDictionary *poMeasureDict = poMeasure->GetDictionary();
6892 :
6893 : /* -------------------------------------------------------------------- */
6894 : /* Extract Subtype attribute */
6895 : /* -------------------------------------------------------------------- */
6896 155 : GDALPDFObject *poSubtype = poMeasureDict->Get("Subtype");
6897 155 : if (poSubtype == nullptr || poSubtype->GetType() != PDFObjectType_Name)
6898 : {
6899 0 : CPLError(CE_Failure, CPLE_AppDefined, "Cannot find Subtype object");
6900 0 : return FALSE;
6901 : }
6902 :
6903 155 : CPLDebug("PDF", "Subtype = %s", poSubtype->GetName().c_str());
6904 155 : if (!EQUAL(poSubtype->GetName().c_str(), "GEO"))
6905 0 : return FALSE;
6906 :
6907 : /* -------------------------------------------------------------------- */
6908 : /* Extract Bounds attribute (optional) */
6909 : /* -------------------------------------------------------------------- */
6910 :
6911 : /* http://acrobatusers.com/sites/default/files/gallery_pictures/SEVERODVINSK.pdf
6912 : */
6913 : /* has lgit:LPTS, lgit:GPTS and lgit:Bounds that have more precision than */
6914 : /* LPTS, GPTS and Bounds. Use those ones */
6915 :
6916 155 : GDALPDFObject *poBounds = poMeasureDict->Get("lgit:Bounds");
6917 155 : if (poBounds != nullptr && poBounds->GetType() == PDFObjectType_Array)
6918 : {
6919 0 : CPLDebug("PDF", "Using lgit:Bounds");
6920 : }
6921 308 : else if ((poBounds = poMeasureDict->Get("Bounds")) == nullptr ||
6922 153 : poBounds->GetType() != PDFObjectType_Array)
6923 : {
6924 2 : poBounds = nullptr;
6925 : }
6926 :
6927 155 : if (poBounds != nullptr)
6928 : {
6929 153 : int nBoundsLength = poBounds->GetArray()->GetLength();
6930 153 : if (nBoundsLength == 8)
6931 : {
6932 : double adfBounds[8];
6933 1296 : for (int i = 0; i < 8; i++)
6934 : {
6935 1152 : adfBounds[i] = Get(poBounds, i);
6936 1152 : CPLDebug("PDF", "Bounds[%d] = %f", i, adfBounds[i]);
6937 : }
6938 :
6939 : // TODO we should use it to restrict the neatline but
6940 : // I have yet to set a sample where bounds are not the four
6941 : // corners of the unit square.
6942 : }
6943 : }
6944 :
6945 : /* -------------------------------------------------------------------- */
6946 : /* Extract GPTS attribute */
6947 : /* -------------------------------------------------------------------- */
6948 155 : GDALPDFObject *poGPTS = poMeasureDict->Get("lgit:GPTS");
6949 155 : if (poGPTS != nullptr && poGPTS->GetType() == PDFObjectType_Array)
6950 : {
6951 0 : CPLDebug("PDF", "Using lgit:GPTS");
6952 : }
6953 310 : else if ((poGPTS = poMeasureDict->Get("GPTS")) == nullptr ||
6954 155 : poGPTS->GetType() != PDFObjectType_Array)
6955 : {
6956 0 : CPLError(CE_Failure, CPLE_AppDefined, "Cannot find GPTS object");
6957 0 : return FALSE;
6958 : }
6959 :
6960 155 : int nGPTSLength = poGPTS->GetArray()->GetLength();
6961 155 : if ((nGPTSLength % 2) != 0 || nGPTSLength < 6)
6962 : {
6963 0 : CPLError(CE_Failure, CPLE_AppDefined, "Invalid length for GPTS object");
6964 0 : return FALSE;
6965 : }
6966 :
6967 310 : std::vector<double> adfGPTS(nGPTSLength);
6968 1395 : for (int i = 0; i < nGPTSLength; i++)
6969 : {
6970 1240 : adfGPTS[i] = Get(poGPTS, i);
6971 1240 : CPLDebug("PDF", "GPTS[%d] = %.18f", i, adfGPTS[i]);
6972 : }
6973 :
6974 : /* -------------------------------------------------------------------- */
6975 : /* Extract LPTS attribute */
6976 : /* -------------------------------------------------------------------- */
6977 155 : GDALPDFObject *poLPTS = poMeasureDict->Get("lgit:LPTS");
6978 155 : if (poLPTS != nullptr && poLPTS->GetType() == PDFObjectType_Array)
6979 : {
6980 0 : CPLDebug("PDF", "Using lgit:LPTS");
6981 : }
6982 310 : else if ((poLPTS = poMeasureDict->Get("LPTS")) == nullptr ||
6983 155 : poLPTS->GetType() != PDFObjectType_Array)
6984 : {
6985 0 : CPLError(CE_Failure, CPLE_AppDefined, "Cannot find LPTS object");
6986 0 : return FALSE;
6987 : }
6988 :
6989 155 : int nLPTSLength = poLPTS->GetArray()->GetLength();
6990 155 : if (nLPTSLength != nGPTSLength)
6991 : {
6992 0 : CPLError(CE_Failure, CPLE_AppDefined, "Invalid length for LPTS object");
6993 0 : return FALSE;
6994 : }
6995 :
6996 310 : std::vector<double> adfLPTS(nLPTSLength);
6997 1395 : for (int i = 0; i < nLPTSLength; i++)
6998 : {
6999 1240 : adfLPTS[i] = Get(poLPTS, i);
7000 1240 : CPLDebug("PDF", "LPTS[%d] = %f", i, adfLPTS[i]);
7001 : }
7002 :
7003 : /* -------------------------------------------------------------------- */
7004 : /* Extract GCS attribute */
7005 : /* -------------------------------------------------------------------- */
7006 155 : GDALPDFObject *poGCS = poMeasureDict->Get("GCS");
7007 155 : if (poGCS == nullptr || poGCS->GetType() != PDFObjectType_Dictionary)
7008 : {
7009 0 : CPLError(CE_Failure, CPLE_AppDefined, "Cannot find GCS object");
7010 0 : return FALSE;
7011 : }
7012 :
7013 155 : GDALPDFDictionary *poGCSDict = poGCS->GetDictionary();
7014 :
7015 : /* -------------------------------------------------------------------- */
7016 : /* Extract GCS.Type attribute */
7017 : /* -------------------------------------------------------------------- */
7018 155 : GDALPDFObject *poGCSType = poGCSDict->Get("Type");
7019 155 : if (poGCSType == nullptr || poGCSType->GetType() != PDFObjectType_Name)
7020 : {
7021 0 : CPLError(CE_Failure, CPLE_AppDefined, "Cannot find GCS.Type object");
7022 0 : return FALSE;
7023 : }
7024 :
7025 155 : CPLDebug("PDF", "GCS.Type = %s", poGCSType->GetName().c_str());
7026 :
7027 : /* -------------------------------------------------------------------- */
7028 : /* Extract EPSG attribute */
7029 : /* -------------------------------------------------------------------- */
7030 155 : GDALPDFObject *poEPSG = poGCSDict->Get("EPSG");
7031 155 : int nEPSGCode = 0;
7032 155 : if (poEPSG != nullptr && poEPSG->GetType() == PDFObjectType_Int)
7033 : {
7034 129 : nEPSGCode = poEPSG->GetInt();
7035 129 : CPLDebug("PDF", "GCS.EPSG = %d", nEPSGCode);
7036 : }
7037 :
7038 : /* -------------------------------------------------------------------- */
7039 : /* Extract GCS.WKT attribute */
7040 : /* -------------------------------------------------------------------- */
7041 155 : GDALPDFObject *poGCSWKT = poGCSDict->Get("WKT");
7042 155 : if (poGCSWKT != nullptr && poGCSWKT->GetType() != PDFObjectType_String)
7043 : {
7044 0 : poGCSWKT = nullptr;
7045 : }
7046 :
7047 155 : if (poGCSWKT != nullptr)
7048 153 : CPLDebug("PDF", "GCS.WKT = %s", poGCSWKT->GetString().c_str());
7049 :
7050 155 : if (nEPSGCode <= 0 && poGCSWKT == nullptr)
7051 : {
7052 0 : CPLError(CE_Failure, CPLE_AppDefined,
7053 : "Cannot find GCS.WKT or GCS.EPSG objects");
7054 0 : return FALSE;
7055 : }
7056 :
7057 155 : if (poGCSWKT != nullptr)
7058 : {
7059 153 : m_oSRS.importFromWkt(poGCSWKT->GetString().c_str());
7060 : }
7061 :
7062 155 : bool bSRSOK = false;
7063 155 : if (nEPSGCode != 0)
7064 : {
7065 : // At time of writing EPSG CRS codes are <= 32767.
7066 : // The usual practice is that codes >= 100000 are in the ESRI namespace
7067 : // instead
7068 129 : if (nEPSGCode >= 100000)
7069 : {
7070 4 : CPLErrorHandlerPusher oHandler(CPLQuietErrorHandler);
7071 4 : OGRSpatialReference oSRS_ESRI;
7072 2 : oSRS_ESRI.SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER);
7073 2 : if (oSRS_ESRI.SetFromUserInput(CPLSPrintf("ESRI:%d", nEPSGCode)) ==
7074 : OGRERR_NONE)
7075 : {
7076 2 : bSRSOK = true;
7077 :
7078 : // Check consistency of ESRI:xxxx and WKT definitions
7079 2 : if (poGCSWKT != nullptr)
7080 : {
7081 3 : if (!m_oSRS.GetName() ||
7082 1 : (!EQUAL(oSRS_ESRI.GetName(), m_oSRS.GetName()) &&
7083 0 : !oSRS_ESRI.IsSame(&m_oSRS)))
7084 : {
7085 1 : CPLDebug("PDF",
7086 : "Definition from ESRI:%d and WKT=%s do not "
7087 : "match. Using WKT string",
7088 1 : nEPSGCode, poGCSWKT->GetString().c_str());
7089 1 : bSRSOK = false;
7090 : }
7091 : }
7092 2 : if (bSRSOK)
7093 : {
7094 1 : m_oSRS = std::move(oSRS_ESRI);
7095 : }
7096 : }
7097 : }
7098 127 : else if (m_oSRS.importFromEPSG(nEPSGCode) == OGRERR_NONE)
7099 : {
7100 127 : bSRSOK = true;
7101 : }
7102 : }
7103 :
7104 155 : if (!bSRSOK)
7105 : {
7106 27 : if (poGCSWKT == nullptr)
7107 : {
7108 0 : CPLError(CE_Failure, CPLE_AppDefined,
7109 : "Cannot resolve EPSG object, and GCS.WKT not found");
7110 0 : return FALSE;
7111 : }
7112 :
7113 27 : if (m_oSRS.importFromWkt(poGCSWKT->GetString().c_str()) != OGRERR_NONE)
7114 : {
7115 1 : m_oSRS.Clear();
7116 1 : return FALSE;
7117 : }
7118 : }
7119 :
7120 : /* -------------------------------------------------------------------- */
7121 : /* Compute geotransform */
7122 : /* -------------------------------------------------------------------- */
7123 154 : OGRSpatialReference *poSRSGeog = m_oSRS.CloneGeogCS();
7124 :
7125 : /* Files found at
7126 : * http://carto.iict.ch/blog/publications-cartographiques-au-format-geospatial-pdf/
7127 : */
7128 : /* are in a PROJCS. However the coordinates in GPTS array are not in (lat,
7129 : * long) as required by the */
7130 : /* ISO 32000 supplement spec, but in (northing, easting). Adobe reader is
7131 : * able to understand that, */
7132 : /* so let's also try to do it with a heuristics. */
7133 :
7134 154 : bool bReproject = true;
7135 154 : if (m_oSRS.IsProjected())
7136 : {
7137 560 : for (int i = 0; i < nGPTSLength / 2; i++)
7138 : {
7139 448 : if (fabs(adfGPTS[2 * i]) > 91 || fabs(adfGPTS[2 * i + 1]) > 361)
7140 : {
7141 0 : CPLDebug("PDF", "GPTS coordinates seems to be in (northing, "
7142 : "easting), which is non-standard");
7143 0 : bReproject = false;
7144 0 : break;
7145 : }
7146 : }
7147 : }
7148 :
7149 154 : OGRCoordinateTransformation *poCT = nullptr;
7150 154 : if (bReproject)
7151 : {
7152 154 : poCT = OGRCreateCoordinateTransformation(poSRSGeog, &m_oSRS);
7153 154 : if (poCT == nullptr)
7154 : {
7155 0 : delete poSRSGeog;
7156 0 : m_oSRS.Clear();
7157 0 : return FALSE;
7158 : }
7159 : }
7160 :
7161 308 : std::vector<GDAL_GCP> asGCPS(nGPTSLength / 2);
7162 :
7163 : /* Create NEATLINE */
7164 154 : OGRLinearRing *poRing = nullptr;
7165 154 : if (nGPTSLength == 8)
7166 : {
7167 154 : m_poNeatLine = new OGRPolygon();
7168 154 : poRing = new OGRLinearRing();
7169 154 : m_poNeatLine->addRingDirectly(poRing);
7170 : }
7171 :
7172 770 : for (int i = 0; i < nGPTSLength / 2; i++)
7173 : {
7174 : /* We probably assume LPTS is 0 or 1 */
7175 1232 : asGCPS[i].dfGCPPixel =
7176 616 : (dfULX * (1 - adfLPTS[2 * i + 0]) + dfLRX * adfLPTS[2 * i + 0]) /
7177 616 : dfMediaBoxWidth * nRasterXSize;
7178 1232 : asGCPS[i].dfGCPLine =
7179 616 : (dfULY * (1 - adfLPTS[2 * i + 1]) + dfLRY * adfLPTS[2 * i + 1]) /
7180 616 : dfMediaBoxHeight * nRasterYSize;
7181 :
7182 616 : double lat = adfGPTS[2 * i];
7183 616 : double lon = adfGPTS[2 * i + 1];
7184 616 : double x = lon;
7185 616 : double y = lat;
7186 616 : if (bReproject)
7187 : {
7188 616 : if (!poCT->Transform(1, &x, &y, nullptr))
7189 : {
7190 0 : CPLError(CE_Failure, CPLE_AppDefined,
7191 : "Cannot reproject (%f, %f)", lon, lat);
7192 0 : delete poSRSGeog;
7193 0 : delete poCT;
7194 0 : m_oSRS.Clear();
7195 0 : return FALSE;
7196 : }
7197 : }
7198 :
7199 616 : x = ROUND_IF_CLOSE(x);
7200 616 : y = ROUND_IF_CLOSE(y);
7201 :
7202 616 : asGCPS[i].dfGCPX = x;
7203 616 : asGCPS[i].dfGCPY = y;
7204 :
7205 616 : if (poRing)
7206 616 : poRing->addPoint(x, y);
7207 : }
7208 :
7209 154 : delete poSRSGeog;
7210 154 : delete poCT;
7211 :
7212 154 : if (!GDALGCPsToGeoTransform(nGPTSLength / 2, asGCPS.data(), m_gt.data(),
7213 : FALSE))
7214 : {
7215 0 : CPLDebug("PDF",
7216 : "Could not compute GT with exact match. Try with approximate");
7217 0 : if (!GDALGCPsToGeoTransform(nGPTSLength / 2, asGCPS.data(), m_gt.data(),
7218 : TRUE))
7219 : {
7220 0 : CPLError(CE_Failure, CPLE_AppDefined,
7221 : "Could not compute GT with approximate match.");
7222 0 : return FALSE;
7223 : }
7224 : }
7225 154 : m_bGeoTransformValid = true;
7226 :
7227 : // If the non scaling terms of the geotransform are significantly smaller
7228 : // than the pixel size, then nullify them as being just artifacts of
7229 : // reprojection and GDALGCPsToGeoTransform() numerical imprecisions.
7230 154 : const double dfPixelSize = std::min(fabs(m_gt[1]), fabs(m_gt[5]));
7231 154 : const double dfRotationShearTerm = std::max(fabs(m_gt[2]), fabs(m_gt[4]));
7232 161 : if (dfRotationShearTerm < 1e-5 * dfPixelSize ||
7233 7 : (m_bUseLib.test(PDFLIB_PDFIUM) &&
7234 154 : std::min(fabs(m_gt[2]), fabs(m_gt[4])) < 1e-5 * dfPixelSize))
7235 : {
7236 147 : dfLRX = m_gt[0] + nRasterXSize * m_gt[1] + nRasterYSize * m_gt[2];
7237 147 : dfLRY = m_gt[3] + nRasterXSize * m_gt[4] + nRasterYSize * m_gt[5];
7238 147 : m_gt[1] = (dfLRX - m_gt[0]) / nRasterXSize;
7239 147 : m_gt[5] = (dfLRY - m_gt[3]) / nRasterYSize;
7240 147 : m_gt[2] = m_gt[4] = 0;
7241 : }
7242 :
7243 154 : return TRUE;
7244 : }
7245 :
7246 : /************************************************************************/
7247 : /* GetSpatialRef() */
7248 : /************************************************************************/
7249 :
7250 225 : const OGRSpatialReference *PDFDataset::GetSpatialRef() const
7251 : {
7252 225 : const auto poSRS = GDALPamDataset::GetSpatialRef();
7253 225 : if (poSRS)
7254 200 : return poSRS;
7255 :
7256 25 : if (!m_oSRS.IsEmpty() && m_bGeoTransformValid)
7257 24 : return &m_oSRS;
7258 1 : return nullptr;
7259 : }
7260 :
7261 : /************************************************************************/
7262 : /* GetGeoTransform() */
7263 : /************************************************************************/
7264 :
7265 23 : CPLErr PDFDataset::GetGeoTransform(GDALGeoTransform >) const
7266 :
7267 : {
7268 23 : if (GDALPamDataset::GetGeoTransform(gt) == CE_None)
7269 : {
7270 3 : return CE_None;
7271 : }
7272 :
7273 20 : gt = m_gt;
7274 20 : return ((m_bGeoTransformValid) ? CE_None : CE_Failure);
7275 : }
7276 :
7277 : /************************************************************************/
7278 : /* SetSpatialRef() */
7279 : /************************************************************************/
7280 :
7281 6 : CPLErr PDFDataset::SetSpatialRef(const OGRSpatialReference *poSRS)
7282 : {
7283 6 : if (eAccess == GA_ReadOnly)
7284 2 : GDALPamDataset::SetSpatialRef(poSRS);
7285 :
7286 6 : m_oSRS.Clear();
7287 6 : if (poSRS)
7288 5 : m_oSRS = *poSRS;
7289 6 : m_bProjDirty = true;
7290 6 : return CE_None;
7291 : }
7292 :
7293 : /************************************************************************/
7294 : /* SetGeoTransform() */
7295 : /************************************************************************/
7296 :
7297 5 : CPLErr PDFDataset::SetGeoTransform(const GDALGeoTransform >)
7298 : {
7299 5 : if (eAccess == GA_ReadOnly)
7300 2 : GDALPamDataset::SetGeoTransform(gt);
7301 :
7302 5 : m_gt = gt;
7303 5 : m_bGeoTransformValid = true;
7304 5 : m_bProjDirty = true;
7305 :
7306 : /* Reset NEATLINE if not explicitly set by the user */
7307 5 : if (!m_bNeatLineDirty)
7308 5 : SetMetadataItem("NEATLINE", nullptr);
7309 5 : return CE_None;
7310 : }
7311 :
7312 : /************************************************************************/
7313 : /* GetMetadataDomainList() */
7314 : /************************************************************************/
7315 :
7316 1 : char **PDFDataset::GetMetadataDomainList()
7317 : {
7318 1 : return BuildMetadataDomainList(GDALPamDataset::GetMetadataDomainList(),
7319 : TRUE, "xml:XMP", "LAYERS",
7320 1 : "EMBEDDED_METADATA", nullptr);
7321 : }
7322 :
7323 : /************************************************************************/
7324 : /* GetMetadata() */
7325 : /************************************************************************/
7326 :
7327 1898 : char **PDFDataset::GetMetadata(const char *pszDomain)
7328 : {
7329 1898 : if (pszDomain != nullptr && EQUAL(pszDomain, "EMBEDDED_METADATA"))
7330 : {
7331 1 : char **papszRet = m_oMDMD_PDF.GetMetadata(pszDomain);
7332 1 : if (papszRet)
7333 0 : return papszRet;
7334 :
7335 1 : GDALPDFObject *poCatalog = GetCatalog();
7336 1 : if (poCatalog == nullptr)
7337 0 : return nullptr;
7338 : GDALPDFObject *poFirstElt =
7339 1 : poCatalog->LookupObject("Names.EmbeddedFiles.Names[0]");
7340 : GDALPDFObject *poF =
7341 1 : poCatalog->LookupObject("Names.EmbeddedFiles.Names[1].EF.F");
7342 :
7343 1 : if (poFirstElt == nullptr ||
7344 1 : poFirstElt->GetType() != PDFObjectType_String ||
7345 0 : poFirstElt->GetString() != "Metadata")
7346 1 : return nullptr;
7347 0 : if (poF == nullptr || poF->GetType() != PDFObjectType_Dictionary)
7348 0 : return nullptr;
7349 0 : GDALPDFStream *poStream = poF->GetStream();
7350 0 : if (poStream == nullptr)
7351 0 : return nullptr;
7352 :
7353 0 : char *apszMetadata[2] = {nullptr, nullptr};
7354 0 : apszMetadata[0] = poStream->GetBytes();
7355 0 : m_oMDMD_PDF.SetMetadata(apszMetadata, pszDomain);
7356 0 : VSIFree(apszMetadata[0]);
7357 0 : return m_oMDMD_PDF.GetMetadata(pszDomain);
7358 : }
7359 1897 : if (pszDomain == nullptr || EQUAL(pszDomain, ""))
7360 : {
7361 115 : char **papszPAMMD = GDALPamDataset::GetMetadata(pszDomain);
7362 118 : for (char **papszIter = papszPAMMD; papszIter && *papszIter;
7363 : ++papszIter)
7364 : {
7365 3 : char *pszKey = nullptr;
7366 3 : const char *pszValue = CPLParseNameValue(*papszIter, &pszKey);
7367 3 : if (pszKey && pszValue)
7368 : {
7369 3 : if (m_oMDMD_PDF.GetMetadataItem(pszKey, pszDomain) == nullptr)
7370 2 : m_oMDMD_PDF.SetMetadataItem(pszKey, pszValue, pszDomain);
7371 : }
7372 3 : CPLFree(pszKey);
7373 : }
7374 115 : return m_oMDMD_PDF.GetMetadata(pszDomain);
7375 : }
7376 1782 : if (EQUAL(pszDomain, "LAYERS") || EQUAL(pszDomain, "xml:XMP") ||
7377 1754 : EQUAL(pszDomain, "SUBDATASETS"))
7378 : {
7379 29 : return m_oMDMD_PDF.GetMetadata(pszDomain);
7380 : }
7381 1753 : return GDALPamDataset::GetMetadata(pszDomain);
7382 : }
7383 :
7384 : /************************************************************************/
7385 : /* SetMetadata() */
7386 : /************************************************************************/
7387 :
7388 70 : CPLErr PDFDataset::SetMetadata(char **papszMetadata, const char *pszDomain)
7389 : {
7390 70 : if (pszDomain == nullptr || EQUAL(pszDomain, ""))
7391 : {
7392 46 : char **papszMetadataDup = CSLDuplicate(papszMetadata);
7393 46 : m_oMDMD_PDF.SetMetadata(nullptr, pszDomain);
7394 :
7395 144 : for (char **papszIter = papszMetadataDup; papszIter && *papszIter;
7396 : ++papszIter)
7397 : {
7398 98 : char *pszKey = nullptr;
7399 98 : const char *pszValue = CPLParseNameValue(*papszIter, &pszKey);
7400 98 : if (pszKey && pszValue)
7401 : {
7402 95 : SetMetadataItem(pszKey, pszValue, pszDomain);
7403 : }
7404 98 : CPLFree(pszKey);
7405 : }
7406 46 : CSLDestroy(papszMetadataDup);
7407 46 : return CE_None;
7408 : }
7409 24 : else if (EQUAL(pszDomain, "xml:XMP"))
7410 : {
7411 22 : m_bXMPDirty = true;
7412 22 : return m_oMDMD_PDF.SetMetadata(papszMetadata, pszDomain);
7413 : }
7414 2 : else if (EQUAL(pszDomain, "SUBDATASETS"))
7415 : {
7416 2 : return m_oMDMD_PDF.SetMetadata(papszMetadata, pszDomain);
7417 : }
7418 : else
7419 : {
7420 0 : return GDALPamDataset::SetMetadata(papszMetadata, pszDomain);
7421 : }
7422 : }
7423 :
7424 : /************************************************************************/
7425 : /* GetMetadataItem() */
7426 : /************************************************************************/
7427 :
7428 1805 : const char *PDFDataset::GetMetadataItem(const char *pszName,
7429 : const char *pszDomain)
7430 : {
7431 1805 : if (pszDomain != nullptr && EQUAL(pszDomain, "_INTERNAL_") &&
7432 0 : pszName != nullptr && EQUAL(pszName, "PDF_LIB"))
7433 : {
7434 0 : if (m_bUseLib.test(PDFLIB_POPPLER))
7435 0 : return "POPPLER";
7436 0 : if (m_bUseLib.test(PDFLIB_PODOFO))
7437 0 : return "PODOFO";
7438 0 : if (m_bUseLib.test(PDFLIB_PDFIUM))
7439 0 : return "PDFIUM";
7440 : }
7441 1805 : return CSLFetchNameValue(GetMetadata(pszDomain), pszName);
7442 : }
7443 :
7444 : /************************************************************************/
7445 : /* SetMetadataItem() */
7446 : /************************************************************************/
7447 :
7448 724 : CPLErr PDFDataset::SetMetadataItem(const char *pszName, const char *pszValue,
7449 : const char *pszDomain)
7450 : {
7451 724 : if (pszDomain == nullptr || EQUAL(pszDomain, ""))
7452 : {
7453 676 : if (EQUAL(pszName, "NEATLINE"))
7454 : {
7455 : const char *pszOldValue =
7456 194 : m_oMDMD_PDF.GetMetadataItem(pszName, pszDomain);
7457 194 : if ((pszValue == nullptr && pszOldValue != nullptr) ||
7458 192 : (pszValue != nullptr && pszOldValue == nullptr) ||
7459 1 : (pszValue != nullptr && pszOldValue != nullptr &&
7460 1 : strcmp(pszValue, pszOldValue) != 0))
7461 : {
7462 190 : m_bProjDirty = true;
7463 190 : m_bNeatLineDirty = true;
7464 : }
7465 194 : return m_oMDMD_PDF.SetMetadataItem(pszName, pszValue, pszDomain);
7466 : }
7467 : else
7468 : {
7469 482 : if (EQUAL(pszName, "AUTHOR") || EQUAL(pszName, "PRODUCER") ||
7470 459 : EQUAL(pszName, "CREATOR") || EQUAL(pszName, "CREATION_DATE") ||
7471 405 : EQUAL(pszName, "SUBJECT") || EQUAL(pszName, "TITLE") ||
7472 386 : EQUAL(pszName, "KEYWORDS"))
7473 : {
7474 102 : if (pszValue == nullptr)
7475 1 : pszValue = "";
7476 : const char *pszOldValue =
7477 102 : m_oMDMD_PDF.GetMetadataItem(pszName, pszDomain);
7478 102 : if (pszOldValue == nullptr ||
7479 2 : strcmp(pszValue, pszOldValue) != 0)
7480 : {
7481 102 : m_bInfoDirty = true;
7482 : }
7483 102 : return m_oMDMD_PDF.SetMetadataItem(pszName, pszValue,
7484 102 : pszDomain);
7485 : }
7486 380 : else if (EQUAL(pszName, "DPI"))
7487 : {
7488 378 : return m_oMDMD_PDF.SetMetadataItem(pszName, pszValue,
7489 378 : pszDomain);
7490 : }
7491 : else
7492 : {
7493 2 : m_oMDMD_PDF.SetMetadataItem(pszName, pszValue, pszDomain);
7494 2 : return GDALPamDataset::SetMetadataItem(pszName, pszValue,
7495 2 : pszDomain);
7496 : }
7497 : }
7498 : }
7499 48 : else if (EQUAL(pszDomain, "xml:XMP"))
7500 : {
7501 0 : m_bXMPDirty = true;
7502 0 : return m_oMDMD_PDF.SetMetadataItem(pszName, pszValue, pszDomain);
7503 : }
7504 48 : else if (EQUAL(pszDomain, "SUBDATASETS"))
7505 : {
7506 0 : return m_oMDMD_PDF.SetMetadataItem(pszName, pszValue, pszDomain);
7507 : }
7508 : else
7509 : {
7510 48 : return GDALPamDataset::SetMetadataItem(pszName, pszValue, pszDomain);
7511 : }
7512 : }
7513 :
7514 : /************************************************************************/
7515 : /* GetGCPCount() */
7516 : /************************************************************************/
7517 :
7518 11 : int PDFDataset::GetGCPCount()
7519 : {
7520 11 : return m_nGCPCount;
7521 : }
7522 :
7523 : /************************************************************************/
7524 : /* GetGCPSpatialRef() */
7525 : /************************************************************************/
7526 :
7527 2 : const OGRSpatialReference *PDFDataset::GetGCPSpatialRef() const
7528 : {
7529 2 : if (!m_oSRS.IsEmpty() && m_nGCPCount != 0)
7530 1 : return &m_oSRS;
7531 1 : return nullptr;
7532 : }
7533 :
7534 : /************************************************************************/
7535 : /* GetGCPs() */
7536 : /************************************************************************/
7537 :
7538 2 : const GDAL_GCP *PDFDataset::GetGCPs()
7539 : {
7540 2 : return m_pasGCPList;
7541 : }
7542 :
7543 : /************************************************************************/
7544 : /* SetGCPs() */
7545 : /************************************************************************/
7546 :
7547 1 : CPLErr PDFDataset::SetGCPs(int nGCPCountIn, const GDAL_GCP *pasGCPListIn,
7548 : const OGRSpatialReference *poSRS)
7549 : {
7550 : const char *pszGEO_ENCODING =
7551 1 : CPLGetConfigOption("GDAL_PDF_GEO_ENCODING", "ISO32000");
7552 1 : if (nGCPCountIn != 4 && EQUAL(pszGEO_ENCODING, "ISO32000"))
7553 : {
7554 0 : CPLError(CE_Failure, CPLE_NotSupported,
7555 : "PDF driver only supports writing 4 GCPs when "
7556 : "GDAL_PDF_GEO_ENCODING=ISO32000.");
7557 0 : return CE_Failure;
7558 : }
7559 :
7560 : /* Free previous GCPs */
7561 1 : GDALDeinitGCPs(m_nGCPCount, m_pasGCPList);
7562 1 : CPLFree(m_pasGCPList);
7563 :
7564 : /* Duplicate in GCPs */
7565 1 : m_nGCPCount = nGCPCountIn;
7566 1 : m_pasGCPList = GDALDuplicateGCPs(m_nGCPCount, pasGCPListIn);
7567 :
7568 1 : m_oSRS.Clear();
7569 1 : if (poSRS)
7570 1 : m_oSRS = *poSRS;
7571 :
7572 1 : m_bProjDirty = true;
7573 :
7574 : /* Reset NEATLINE if not explicitly set by the user */
7575 1 : if (!m_bNeatLineDirty)
7576 1 : SetMetadataItem("NEATLINE", nullptr);
7577 :
7578 1 : return CE_None;
7579 : }
7580 :
7581 : #endif // #ifdef HAVE_PDF_READ_SUPPORT
7582 :
7583 : /************************************************************************/
7584 : /* GDALPDFOpen() */
7585 : /************************************************************************/
7586 :
7587 53 : GDALDataset *GDALPDFOpen(
7588 : #ifdef HAVE_PDF_READ_SUPPORT
7589 : const char *pszFilename, GDALAccess eAccess
7590 : #else
7591 : CPL_UNUSED const char *pszFilename, CPL_UNUSED GDALAccess eAccess
7592 : #endif
7593 : )
7594 : {
7595 : #ifdef HAVE_PDF_READ_SUPPORT
7596 106 : GDALOpenInfo oOpenInfo(pszFilename, eAccess);
7597 106 : return PDFDataset::Open(&oOpenInfo);
7598 : #else
7599 : return nullptr;
7600 : #endif
7601 : }
7602 :
7603 : /************************************************************************/
7604 : /* GDALPDFUnloadDriver() */
7605 : /************************************************************************/
7606 :
7607 8 : static void GDALPDFUnloadDriver(CPL_UNUSED GDALDriver *poDriver)
7608 : {
7609 : #ifdef HAVE_POPPLER
7610 8 : if (hGlobalParamsMutex != nullptr)
7611 3 : CPLDestroyMutex(hGlobalParamsMutex);
7612 : #endif
7613 : #ifdef HAVE_PDFIUM
7614 : if (PDFDataset::g_bPdfiumInit)
7615 : {
7616 : CPLCreateOrAcquireMutex(&g_oPdfiumLoadDocMutex, PDFIUM_MUTEX_TIMEOUT);
7617 : // Destroy every loaded document or page
7618 : TMapPdfiumDatasets::iterator itDoc;
7619 : TMapPdfiumPages::iterator itPage;
7620 : for (itDoc = g_mPdfiumDatasets.begin();
7621 : itDoc != g_mPdfiumDatasets.end(); ++itDoc)
7622 : {
7623 : TPdfiumDocumentStruct *pDoc = itDoc->second;
7624 : for (itPage = pDoc->pages.begin(); itPage != pDoc->pages.end();
7625 : ++itPage)
7626 : {
7627 : TPdfiumPageStruct *pPage = itPage->second;
7628 :
7629 : CPLCreateOrAcquireMutex(&g_oPdfiumReadMutex,
7630 : PDFIUM_MUTEX_TIMEOUT);
7631 : CPLCreateOrAcquireMutex(&(pPage->readMutex),
7632 : PDFIUM_MUTEX_TIMEOUT);
7633 : CPLReleaseMutex(pPage->readMutex);
7634 : CPLDestroyMutex(pPage->readMutex);
7635 : FPDF_ClosePage(FPDFPageFromIPDFPage(pPage->page));
7636 : delete pPage;
7637 : CPLReleaseMutex(g_oPdfiumReadMutex);
7638 : } // ~ foreach page
7639 :
7640 : FPDF_CloseDocument(FPDFDocumentFromCPDFDocument(pDoc->doc));
7641 : CPLFree(pDoc->filename);
7642 : VSIFCloseL(static_cast<VSILFILE *>(pDoc->psFileAccess->m_Param));
7643 : delete pDoc->psFileAccess;
7644 : pDoc->pages.clear();
7645 :
7646 : delete pDoc;
7647 : } // ~ foreach document
7648 : g_mPdfiumDatasets.clear();
7649 : FPDF_DestroyLibrary();
7650 : PDFDataset::g_bPdfiumInit = FALSE;
7651 :
7652 : CPLReleaseMutex(g_oPdfiumLoadDocMutex);
7653 :
7654 : if (g_oPdfiumReadMutex)
7655 : CPLDestroyMutex(g_oPdfiumReadMutex);
7656 : CPLDestroyMutex(g_oPdfiumLoadDocMutex);
7657 : }
7658 : #endif
7659 8 : }
7660 :
7661 : /************************************************************************/
7662 : /* PDFSanitizeLayerName() */
7663 : /************************************************************************/
7664 :
7665 660 : CPLString PDFSanitizeLayerName(const char *pszName)
7666 : {
7667 660 : if (!CPLTestBool(CPLGetConfigOption("GDAL_PDF_LAUNDER_LAYER_NAMES", "YES")))
7668 0 : return pszName;
7669 :
7670 1320 : CPLString osName;
7671 17194 : for (int i = 0; pszName[i] != '\0'; i++)
7672 : {
7673 16534 : if (pszName[i] == ' ' || pszName[i] == '.' || pszName[i] == ',')
7674 976 : osName += "_";
7675 15558 : else if (pszName[i] != '"')
7676 15558 : osName += pszName[i];
7677 : }
7678 660 : if (osName.empty())
7679 2 : osName = "unnamed";
7680 660 : return osName;
7681 : }
7682 :
7683 : /************************************************************************/
7684 : /* GDALPDFListLayersAlgorithm */
7685 : /************************************************************************/
7686 :
7687 : #ifdef HAVE_PDF_READ_SUPPORT
7688 :
7689 : class GDALPDFListLayersAlgorithm final : public GDALAlgorithm
7690 : {
7691 : public:
7692 22 : GDALPDFListLayersAlgorithm()
7693 22 : : GDALAlgorithm("list-layers",
7694 44 : std::string("List layers of a PDF dataset"),
7695 66 : "/drivers/raster/pdf.html")
7696 : {
7697 22 : AddInputDatasetArg(&m_dataset, GDAL_OF_RASTER | GDAL_OF_VECTOR);
7698 22 : AddOutputFormatArg(&m_format).SetDefault(m_format).SetChoices("json",
7699 22 : "text");
7700 22 : AddOutputStringArg(&m_output);
7701 22 : }
7702 :
7703 : protected:
7704 : bool RunImpl(GDALProgressFunc, void *) override;
7705 :
7706 : private:
7707 : GDALArgDatasetValue m_dataset{};
7708 : std::string m_format = "json";
7709 : std::string m_output{};
7710 : };
7711 :
7712 3 : bool GDALPDFListLayersAlgorithm::RunImpl(GDALProgressFunc, void *)
7713 : {
7714 3 : auto poDS = dynamic_cast<PDFDataset *>(m_dataset.GetDatasetRef());
7715 3 : if (!poDS)
7716 : {
7717 1 : ReportError(CE_Failure, CPLE_AppDefined, "%s is not a PDF",
7718 1 : m_dataset.GetName().c_str());
7719 1 : return false;
7720 : }
7721 2 : if (m_format == "json")
7722 : {
7723 2 : CPLJSonStreamingWriter oWriter(nullptr, nullptr);
7724 1 : oWriter.StartArray();
7725 10 : for (const auto &[key, value] : cpl::IterateNameValue(
7726 11 : const_cast<CSLConstList>(poDS->GetMetadata("LAYERS"))))
7727 : {
7728 5 : CPL_IGNORE_RET_VAL(key);
7729 5 : oWriter.Add(value);
7730 : }
7731 1 : oWriter.EndArray();
7732 1 : m_output = oWriter.GetString();
7733 1 : m_output += '\n';
7734 : }
7735 : else
7736 : {
7737 10 : for (const auto &[key, value] : cpl::IterateNameValue(
7738 11 : const_cast<CSLConstList>(poDS->GetMetadata("LAYERS"))))
7739 : {
7740 5 : CPL_IGNORE_RET_VAL(key);
7741 5 : m_output += value;
7742 5 : m_output += '\n';
7743 : }
7744 : }
7745 2 : return true;
7746 : }
7747 :
7748 : /************************************************************************/
7749 : /* GDALPDFInstantiateAlgorithm() */
7750 : /************************************************************************/
7751 :
7752 : static GDALAlgorithm *
7753 22 : GDALPDFInstantiateAlgorithm(const std::vector<std::string> &aosPath)
7754 : {
7755 22 : if (aosPath.size() == 1 && aosPath[0] == "list-layers")
7756 : {
7757 22 : return std::make_unique<GDALPDFListLayersAlgorithm>().release();
7758 : }
7759 : else
7760 : {
7761 0 : return nullptr;
7762 : }
7763 : }
7764 :
7765 : #endif // HAVE_PDF_READ_SUPPORT
7766 :
7767 : /************************************************************************/
7768 : /* GDALRegister_PDF() */
7769 : /************************************************************************/
7770 :
7771 17 : void GDALRegister_PDF()
7772 :
7773 : {
7774 17 : if (!GDAL_CHECK_VERSION("PDF driver"))
7775 0 : return;
7776 :
7777 17 : if (GDALGetDriverByName(DRIVER_NAME) != nullptr)
7778 0 : return;
7779 :
7780 17 : GDALDriver *poDriver = new GDALDriver();
7781 17 : PDFDriverSetCommonMetadata(poDriver);
7782 :
7783 : #ifdef HAVE_PDF_READ_SUPPORT
7784 17 : poDriver->pfnOpen = PDFDataset::OpenWrapper;
7785 17 : poDriver->pfnInstantiateAlgorithm = GDALPDFInstantiateAlgorithm;
7786 : #endif // HAVE_PDF_READ_SUPPORT
7787 :
7788 17 : poDriver->pfnCreateCopy = GDALPDFCreateCopy;
7789 17 : poDriver->pfnCreate = PDFWritableVectorDataset::Create;
7790 17 : poDriver->pfnUnloadDriver = GDALPDFUnloadDriver;
7791 :
7792 17 : GetGDALDriverManager()->RegisterDriver(poDriver);
7793 : }
|