Reputation: 1250
I am using the wkhtmltopdf C library to convert a local HTML file to PDF, but no matter what I've tried, it does not successfully convert the file. Using an external URI (like google.com) works fine, however any local files will fail, either with no error message or with HTTP error codes 1003 or 1302.
Here is the code I am using:
wkhtmltopdf_global_settings *globalSettings;
wkhtmltopdf_object_settings *objectSettings;
wkhtmltopdf_converter *converter;
wkhtmltopdf_init(1);
globalSettings = wkhtmltopdf_create_global_settings();
wkhtmltopdf_set_global_setting(globalSettings, "size.paperSize", "A4");
wkhtmltopdf_set_global_setting(globalSettings, "orientation", "Portrait");
wkhtmltopdf_set_global_setting(globalSettings, "colorMode", "Color");
wkhtmltopdf_set_global_setting(globalSettings, "size.paperSize", "A4");
wkhtmltopdf_set_global_setting(globalSettings, "out", "output.pdf");
converter = wkhtmltopdf_create_converter(globalSettings);
objectSettings = wkhtmltopdf_create_object_settings();
wkhtmltopdf_set_object_setting(objectSettings, "load.blockLocalFileAccess", "false");
wkhtmltopdf_set_object_setting(objectSettings, "page", "inputfile.html");
wkhtmltopdf_add_object(converter, objectSettings, NULL);
if (wkhtmltopdf_convert(converter) != 1)
{
qWarning(qPrintable("Error code: " + QString::number(wkhtmltopdf_http_error_code(converter))));
}
wkhtmltopdf_destroy_converter(converter);
wkhtmltopdf_deinit();
I am using QT, and the input file is within a resource file of mine. I have tried many variation to get wkhtmltopdf to load the file, but none of the following have worked (some liberties have been taken with the below source, but you should get the idea):
I tried to copy the contents of the input file into a QTemporaryFile, and load that file:
QTemporaryFile temp;
if (temp.open())
{
temp.write(inputFile.readAll());
wkhtmltopdf_set_object_setting(objectSettings, "page", temp.fileName());
}
I tried using the resource file path directly:
wkhtmltopdf_set_object_setting(objectSettings, "page", ":templates/input.html");
I've also tried adding in file://
for the above attempts. Does anyone have any idea why it may not be working, and if so, how to fix it?
Upvotes: 2
Views: 2259
Reputation: 98495
The Qt resource paths will most likely not work. The resource paths are only visible to APIs that internally use QFile
and use the same copy of the Qt library as your code is using.
The approach with temporary files is a decent workaround.
But this line can't really work:
wkhtmltopdf_set_object_setting(objectSettings, "page", temp.fileName());
The type that you pass (a QString
) is wrong. Unfortunately, the interface is C-like and there's no type safety, so you're lulled into complacency. You need to pass it a utf8-encoded file path:
wkhtmltopdf_set_object_setting(objectSettings, "page",
temp.fileName().toUtf8().constData());
Upvotes: 2