KItinerary

pdfdocument.cpp
1/*
2 SPDX-FileCopyrightText: 2018 Volker Krause <vkrause@kde.org>
3
4 SPDX-License-Identifier: LGPL-2.0-or-later
5*/
6
7#include "config-kitinerary.h"
8#include "pdfdocument.h"
9#include "pdfdocument_p.h"
10#include "pdfextractoroutputdevice_p.h"
11#include "pdfimage_p.h"
12#include "popplerglobalparams_p.h"
13#include "popplerutils_p.h"
14#include "logging.h"
15
16#include <QDebug>
17#include <QImage>
18#include <QScopedValueRollback>
19#include <QTimeZone>
20
21#include <DateInfo.h>
22#include <PDFDoc.h>
23#include <PDFDocEncoding.h>
24#include <Stream.h>
25#include <UTF.h>
26
27#include <cmath>
28
29using namespace KItinerary;
30
31void PdfPagePrivate::load()
32{
33 if (m_loaded) {
34 return;
35 }
36
37 PopplerGlobalParams gp;
38 PdfExtractorOutputDevice device;
39 m_doc->m_popplerDoc->displayPageSlice(&device, m_pageNum + 1, 72, 72, 0, false, true, false, -1, -1, -1, -1);
40 m_doc->m_popplerDoc->processLinks(&device, m_pageNum + 1);
41 device.finalize();
42 const auto pageRect = m_doc->m_popplerDoc->getPage(m_pageNum + 1)->getCropBox();
43 std::unique_ptr<GooString> s(device.getText(pageRect->x1, pageRect->y1, pageRect->x2, pageRect->y2));
44
45 m_text = QString::fromUtf8(s->c_str());
46 m_images = std::move(device.m_images);
47 for (auto it = m_images.begin(); it != m_images.end(); ++it) {
48 (*it).d->m_page = this;
49 }
50
51 m_links = std::move(device.m_links);
52 for (auto &link : m_links) {
53 link.convertToPageRect(pageRect);
54 }
55
56 m_loaded = true;
57}
58
59PdfPage::PdfPage()
60 : d(new PdfPagePrivate)
61{
62}
63
64PdfPage::PdfPage(const PdfPage&) = default;
65PdfPage::~PdfPage() = default;
66PdfPage& PdfPage::operator=(const PdfPage&) = default;
67
68QString PdfPage::text() const
69{
70 d->load();
71 return d->m_text;
72}
73
74static double ratio(double begin, double end, double ratio)
75{
76 return begin + (end - begin) * ratio;
77}
78
79QString PdfPage::textInRect(double left, double top, double right, double bottom) const
80{
81 PopplerGlobalParams gp;
82
83 const auto page = d->m_doc->m_popplerDoc->getPage(d->m_pageNum + 1);
84 const auto pageRect = page->getCropBox();
85
86 double l;
87 double t;
88 double r;
89 double b;
90 switch (page->getRotate()) {
91 case 0:
92 l = ratio(pageRect->x1, pageRect->x2, left);
93 t = ratio(pageRect->y1, pageRect->y2, top);
94 r = ratio(pageRect->x1, pageRect->x2, right);
95 b = ratio(pageRect->y1, pageRect->y2, bottom);
96 break;
97 case 90:
98 l = ratio(pageRect->y1, pageRect->y2, left);
99 t = ratio(pageRect->x1, pageRect->x2, top);
100 r = ratio(pageRect->y1, pageRect->y2, right);
101 b = ratio(pageRect->x1, pageRect->x2, bottom);
102 break;
103 default:
104 qCWarning(Log) << "Unsupported page rotation!" << page->getRotate();
105 return {};
106 }
107
108 TextOutputDev device(nullptr, false, 0, false, false);
109 d->m_doc->m_popplerDoc->displayPageSlice(&device, d->m_pageNum + 1, 72, 72, 0, false, true, false, -1, -1, -1, -1);
110 std::unique_ptr<GooString> s(device.getText(l, t, r, b));
111 return QString::fromUtf8(s->c_str());
112}
113
115{
116 d->load();
117 return d->m_images.size();
118}
119
120PdfImage PdfPage::image(int index) const
121{
122 d->load();
123 return d->m_images[index];
124}
125
126QVariantList PdfPage::imagesVariant() const
127{
128 d->load();
129 QVariantList l;
130 l.reserve(imageCount());
131 std::for_each(d->m_images.begin(), d->m_images.end(), [&l](const PdfImage& img) { l.push_back(QVariant::fromValue(img)); });
132 return l;
133}
134
135QVariantList PdfPage::imagesInRect(double left, double top, double right, double bottom) const
136{
137 d->load();
138 QVariantList l;
139 PopplerGlobalParams gp;
140 const auto pageRect = d->m_doc->m_popplerDoc->getPage(d->m_pageNum + 1)->getCropBox();
141
142 for (const auto &img : d->m_images) {
143 if ((img.d->m_transform.dx() >= ratio(pageRect->x1, pageRect->x2, left) && img.d->m_transform.dx() <= ratio(pageRect->x1, pageRect->x2, right)) &&
144 (img.d->m_transform.dy() >= ratio(pageRect->y1, pageRect->y2, top) && img.d->m_transform.dy() <= ratio(pageRect->y1, pageRect->y2, bottom)))
145 {
146 l.push_back(QVariant::fromValue(img));
147 }
148 }
149 return l;
150}
151
153{
154 d->load();
155 return d->m_links.size();
156}
157
158PdfLink PdfPage::link(int index) const
159{
160 d->load();
161 return d->m_links[index];
162}
163
164QVariantList PdfPage::linksVariant() const
165{
166 d->load();
167 QVariantList l;
168 l.reserve(d->m_links.size());
169 std::transform(d->m_links.begin(), d->m_links.end(), std::back_inserter(l), [](const PdfLink &link) { return QVariant::fromValue(link); });
170 return l;
171}
172
173QVariantList PdfPage::linksInRect(double left, double top, double right, double bottom) const
174{
175 QRectF bbox(QPointF(left, top), QPointF(right, bottom));
176 d->load();
177
178 QVariantList l;
179 for (const auto &link : d->m_links) {
180 if (!link.area().intersects(bbox)) {
181 continue;
182 }
183 l.push_back(QVariant::fromValue(link));
184 }
185
186 std::sort(l.begin(), l.end(), [](const auto &lhs, const auto &rhs) {
187 const auto lhsLink = lhs.template value<PdfLink>();
188 const auto rhsLink = rhs.template value<PdfLink>();
189 if (lhsLink.area().top() == rhsLink.area().top()) {
190 return lhsLink.area().left() < rhsLink.area().left();
191 }
192 return lhsLink.area().top() < rhsLink.area().top();
193 });
194
195 return l;
196}
197
198static constexpr inline double pdfToMM(double points)
199{
200 return points * 25.4 / 72.0;
201}
202
203int PdfPage::width() const
204{
205 const auto page = d->m_doc->m_popplerDoc->getPage(d->m_pageNum + 1);
206 const auto rot = page->getRotate();
207 if (rot == 90 || rot == 270) {
208 return pdfToMM(page->getCropHeight());
209 }
210 return pdfToMM(page->getCropWidth());
211}
212
213int PdfPage::height() const
214{
215 const auto page = d->m_doc->m_popplerDoc->getPage(d->m_pageNum + 1);
216 const auto rot = page->getRotate();
217 if (rot == 90 || rot == 270) {
218 return pdfToMM(page->getCropWidth());
219 }
220 return pdfToMM(page->getCropHeight());
221}
222
223
224PdfDocument::PdfDocument(QObject *parent)
225 : QObject(parent)
226 , d(new PdfDocumentPrivate)
227{
228}
229
230PdfDocument::~PdfDocument() = default;
231
232QString PdfDocument::text() const
233{
234 QString text;
235 std::for_each(d->m_pages.begin(), d->m_pages.end(), [&text](const PdfPage &p) { text += p.text(); });
236 return text;
237}
238
239int PdfDocument::pageCount() const
240{
241 return d->m_popplerDoc->getNumPages();
242}
243
245{
246 return d->m_pages[index];
247}
248
250{
251 return d->m_pdfData.size();
252}
253
254static QDateTime parsePdfDateTime(const GooString *str)
255{
256 int year;
257 int month;
258 int day;
259 int hour;
260 int min;
261 int sec;
262 int tzHours;
263 int tzMins;
264 char tz;
265
266 if (!parseDateString(str, &year, &month, &day, &hour, &min, &sec, &tz, &tzHours, &tzMins)) {
267 return {};
268 }
269
270 QDate date(year, month, day);
271 QTime time(hour, min, sec);
272 if (!date.isValid() || !time.isValid()) {
273 return {};
274 }
275
276 int offset = tzHours * 3600 + tzMins * 60;
277 if (tz == '+') {
278 return QDateTime(date, time, QTimeZone::fromSecondsAheadOfUtc(offset));
279 } else if (tz == '-') {
280 return QDateTime(date, time, QTimeZone::fromSecondsAheadOfUtc(-offset));
281 }
282 return QDateTime(date, time, QTimeZone::UTC);
283}
284
285QDateTime PdfDocument::creationTime() const
286{
287 std::unique_ptr<GooString> dt(d->m_popplerDoc->getDocInfoCreatDate());
288 if (!dt) {
289 return {};
290 }
291 return parsePdfDateTime(dt.get());
292}
293
294QDateTime PdfDocument::modificationTime() const
295{
296 std::unique_ptr<GooString> dt(d->m_popplerDoc->getDocInfoModDate());
297 if (!dt) {
298 return {};
299 }
300 return parsePdfDateTime(dt.get());
301}
302
303
304QString gooStringToUnicode(const std::unique_ptr<GooString> &s)
305{
306 if (!s) {
307 return {};
308 }
309
310#if KPOPPLER_VERSION >= QT_VERSION_CHECK(24, 5, 0)
311 if (hasUnicodeByteOrderMark(s->toStr()) || hasUnicodeByteOrderMarkLE(s->toStr())) {
312#else
313 if (s->hasUnicodeMarker() || s->hasUnicodeMarkerLE()) {
314#endif
315 return QString::fromUtf16(reinterpret_cast<const char16_t*>(s->toStr().c_str()), s->toStr().size() / 2);
316 } else {
317 int len = 0;
318 std::unique_ptr<const char[]> utf16Data(pdfDocEncodingToUTF16(s->toStr(), &len));
319 return QString::fromUtf16(reinterpret_cast<const char16_t*>(utf16Data.get()), len / 2);
320 }
321
322 return QString::fromUtf8(s->c_str());
323}
324
325QString PdfDocument::title() const
326{
327 return gooStringToUnicode(d->m_popplerDoc->getDocInfoTitle());
328}
329
330QString PdfDocument::producer() const
331{
332 return gooStringToUnicode(d->m_popplerDoc->getDocInfoProducer());
333}
334
335QString PdfDocument::creator() const
336{
337 return gooStringToUnicode(d->m_popplerDoc->getDocInfoCreator());
338}
339
340QString PdfDocument::author() const
341{
342 return gooStringToUnicode(d->m_popplerDoc->getDocInfoAuthor());
343}
344
345QVariantList PdfDocument::pagesVariant() const
346{
347 QVariantList l;
348 l.reserve(pageCount());
349 std::for_each(d->m_pages.begin(), d->m_pages.end(), [&l](const PdfPage& p) { l.push_back(QVariant::fromValue(p)); });
350 return l;
351}
352
354{
355 PopplerGlobalParams gp;
356
357 std::unique_ptr<PdfDocument> doc(new PdfDocument(parent));
358 doc->d->m_pdfData = data;
359 // PDFDoc takes ownership of stream
360 auto stream = new MemStream(const_cast<char*>(doc->d->m_pdfData.constData()), 0, doc->d->m_pdfData.size(), Object());
361 std::unique_ptr<PDFDoc> popplerDoc(new PDFDoc(stream));
362 if (!popplerDoc->isOk()) {
363 qCWarning(Log) << "Got invalid PDF document!" << popplerDoc->getErrorCode();
364 return nullptr;
365 }
366
367 doc->d->m_pages.reserve(popplerDoc->getNumPages());
368 for (int i = 0; i < popplerDoc->getNumPages(); ++i) {
370 page.d->m_pageNum = i;
371 page.d->m_doc = doc->d.get();
372 doc->d->m_pages.push_back(page);
373 }
374
375 doc->d->m_popplerDoc = std::move(popplerDoc);
376 return doc.release();
377}
378
380{
381 return data.startsWith("%PDF");
382}
383
384#include "moc_pdfdocument.cpp"
PDF document for extraction.
Definition pdfdocument.h:92
PdfPage page(int index) const
The n-thj page in this document.
int fileSize() const
File size of the entire document in bytes.
static PdfDocument * fromData(const QByteArray &data, QObject *parent=nullptr)
Creates a PdfDocument from the given raw data.
static bool maybePdf(const QByteArray &data)
Fast check whether data might be a PDF document.
An image in a PDF document.
Definition pdfimage.h:74
A page in a PDF document.
Definition pdfdocument.h:29
Q_INVOKABLE QVariantList linksInRect(double left, double top, double right, double bottom) const
Returns all links in the specified sub-rect of this page.
PdfImage image(int index) const
The n-th image found in this document.
int linkCount() const
The number of links found in this document.
Q_INVOKABLE QString textInRect(double left, double top, double right, double bottom) const
Returns the text in the specified sub-rect of this page.
PdfLink link(int index) const
The n-th link found in this document.
int imageCount() const
The number of images found in this document.
Q_INVOKABLE QVariantList imagesInRect(double left, double top, double right, double bottom) const
Returns the images in the specified sub-rect of this page.
KIOCORE_EXPORT CopyJob * link(const QList< QUrl > &src, const QUrl &destDir, JobFlags flags=DefaultFlags)
Classes for reservation/travel data models, data extraction and data augmentation.
Definition berelement.h:17
bool startsWith(QByteArrayView bv) const const
QObject * parent() const const
bool intersects(const QRectF &rectangle) const const
QString fromUtf16(const char16_t *unicode, qsizetype size)
QString fromUtf8(QByteArrayView str)
QTimeZone fromSecondsAheadOfUtc(int offset)
QVariant fromValue(T &&value)
This file is part of the KDE documentation.
Documentation copyright © 1996-2024 The KDE developers.
Generated on Fri Oct 11 2024 12:14:42 by doxygen 1.12.0 written by Dimitri van Heesch, © 1997-2006

KDE's Doxygen guidelines are available online.