-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwkhtml2pdf_wrapper.cpp
More file actions
189 lines (152 loc) · 5.56 KB
/
wkhtml2pdf_wrapper.cpp
File metadata and controls
189 lines (152 loc) · 5.56 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
#include "wkhtml2pdf_wrapper.hpp"
#include "html2pdf_converter.hpp"
#include <nlohmann/json.hpp>
#include <iostream>
#include <future>
using namespace std::chrono_literals;
WkHtmlToPdfWrapper::WkHtmlToPdfWrapper() {
// Инициализация в конструкторе НЕ выполняется!
// Она должна быть явно вызвана через initialize() из главного потока
}
WkHtmlToPdfWrapper::~WkHtmlToPdfWrapper() {
shutdown(false);
}
WkHtmlToPdfWrapper& WkHtmlToPdfWrapper::getInstance() {
static WkHtmlToPdfWrapper instance;
return instance;
}
bool WkHtmlToPdfWrapper::initialize() {
if (initialized_) {
return true;
}
running_ = true;
worker_thread_ = std::thread(&WkHtmlToPdfWrapper::workerThreadFunction, this);
// std::cout << "Worker started\n";
initialized_ = true;
return true;
}
void WkHtmlToPdfWrapper::shutdown(bool wait_for_completion) {
if (!initialized_) {
return;
}
running_ = false;
{
std::lock_guard<std::mutex> lock(queue_mutex_);
queue_cv_.notify_all();
}
if (worker_thread_.joinable()) {
if (wait_for_completion) {
worker_thread_.join();
} else {
worker_thread_.detach();
}
}
initialized_ = false;
}
bool WkHtmlToPdfWrapper::convertAsync(const std::string& input_html_path,
const std::string& output_pdf_path,
Callback callback) {
if (!initialized_) {
if (callback) {
callback(false, "Wrapper not initialized");
}
return false;
}
auto task = std::make_shared<ConversionTask>();
task->input_path = input_html_path;
task->output_path = output_pdf_path;
task->callback = callback;
{
std::lock_guard<std::mutex> lock(queue_mutex_);
task_queue_.push(task);
total_tasks_++;
}
queue_cv_.notify_one();
return true;
}
bool WkHtmlToPdfWrapper::convertSync(const std::string& input_html_path,
const std::string& output_pdf_path) {
// std::cout << "convertSync was called" << std::endl;
if (!initialized_) return false;
std::promise<bool> promise;
std::future<bool> future = promise.get_future();
auto task = std::make_shared<ConversionTask>();
task->input_path = input_html_path;
task->output_path = output_pdf_path;
task->promise = std::move(promise);
{
std::lock_guard<std::mutex> lock(queue_mutex_);
task_queue_.push(task);
// std::cout << "Convert task was added to queue" << std::endl;
}
// Даем время рабочему потоку начать ожидание
std::this_thread::sleep_for(std::chrono::milliseconds(10));
// Будим рабочий поток
queue_cv_.notify_one();
// std::cout << "Worker notified" << std::endl;
// Ждём завершения в том же потоке, где worker-поток будет обрабатывать задачу
return future.get();
}
void WkHtmlToPdfWrapper::workerThreadFunction() {
// 1. Инициализация wkhtmltopdf в worker-потоке
if (wkhtmltopdf_init(0) != 1) {
std::cerr << "Failed to initialize wkhtmltopdf" << std::endl;
return;
}
// std::cout << "workerThreadFunction was called" << std::endl;
running_ = true;
while (running_) {
std::shared_ptr<ConversionTask> task;
{
std::unique_lock<std::mutex> lock(queue_mutex_);
queue_cv_.wait(lock, [this]{ return !task_queue_.empty() || !running_; });
if (!running_ && task_queue_.empty()) break;
if (task_queue_.empty()) continue;
task = task_queue_.front();
task_queue_.pop();
// std::cout << "task was export from queue" << std::endl;
}
std::string error_message;
bool success = HtmlToPdfConverter::convertFile(task->input_path, task->output_path);
// std::cout << "file was converted!" << std::endl;
// Установка promise
try {
task->promise.set_value(success);
} catch (const std::future_error& e) {
// например, promise уже установлен
std::cerr << "Promise error: " << e.what() << std::endl;
}
if (task->callback) {
task->callback(success, error_message);
}
}
wkhtmltopdf_deinit();
}
bool WkHtmlToPdfWrapper::performConversion(const std::string& input_path,
const std::string& output_path,
std::string& error_message) {
try {
static std::mutex conversion_mutex;
std::lock_guard<std::mutex> lock(conversion_mutex);
bool success = HtmlToPdfConverter::convertFile(input_path, output_path);
if (!success) {
error_message = "Conversion failed";
}
return success;
} catch (const std::exception& e) {
error_message = e.what();
return false;
}
}
std::string WkHtmlToPdfWrapper::getStats() const {
std::lock_guard<std::mutex> lock(stats_mutex_);
nlohmann::json stats;
stats["initialized"] = initialized_.load();
stats["running"] = running_.load();
stats["total_tasks"] = total_tasks_;
stats["completed_tasks"] = completed_tasks_;
stats["failed_tasks"] = failed_tasks_;
stats["queue_size"] = task_queue_.size();
stats["last_error"] = last_error_;
return stats.dump(2);
}