Convert html string to pdf using wkhtmltopdf C library (wkhtmltox)
I am trying to convert an html string to pdf using the wkhtmltopdf C library. I checked the sample that comes with the installer and I compiled and converted the page successfully. Here is the code I used for reference.
wkhtmltopdf_global_settings * gs;
wkhtmltopdf_object_settings * os;
wkhtmltopdf_converter * c;
wkhtmltopdf_init(false);
gs = wkhtmltopdf_create_global_settings();
wkhtmltopdf_set_global_setting(gs, "out", "test.pdf");
os = wkhtmltopdf_create_object_settings();
wkhtmltopdf_set_object_setting(os, "page", "https://www.google.com.ph");
c = wkhtmltopdf_create_converter(gs);
wkhtmltopdf_set_progress_changed_callback(c, progress_changed);
wkhtmltopdf_set_phase_changed_callback(c, phase_changed);
wkhtmltopdf_set_error_callback(c, error);
wkhtmltopdf_set_warning_callback(c, warning);
wkhtmltopdf_add_object(c, os, NULL);
if (!wkhtmltopdf_convert(c))
fprintf(stderr, "Convertion failed!");
printf("httpErrorCode: %d\n", wkhtmltopdf_http_error_code(c));
wkhtmltopdf_destroy_converter(c);
wkhtmltopdf_deinit();
I suspect changing the parameters of a function
wkhtmltopdf_set_object_setting(os, "page", "https://www.google.com.ph");
to something like
wkhtmltopdf_set_object_setting(os, [name of setting], [html string]);
will do the job, however the documentation does not provide any name for a particular parameter other than the one included in the sample, which is a "page".
I may have missed this in the documentation, or it may not be the correct way to do it. Any suggestion would be much appreciated.
source to share
Yaroslav had the right idea.
Use the wkhtmltopdf_set_object_setting (os, "page", data) function, but instead of a string representing a website URL, prefix your HTML string with a data URI.
For example:
const char *pszText = "data:text/html,<!DOCTYPE html><HTML><HEAD> .... </HTML>";
wkhtmltopdf_set_object_setting(os, "page", pszText);
Works like a champion. I even introduced small images on the page with div.x: before specifying the data: image / png; base64 as the content url.
source to share